@Override
 public void handleMessage(Message msg) {
   switch (msg.what) {
     case MSG_SET_TTY_MODE_RESPONSE:
       {
         Log.v(TtyManager.this, "got setTtyMode response");
         AsyncResult ar = (AsyncResult) msg.obj;
         if (ar.exception != null) {
           Log.d(TtyManager.this, "setTTYMode exception: %s", ar.exception);
         }
         mPhone.queryTTYMode(obtainMessage(MSG_GET_TTY_MODE_RESPONSE));
         break;
       }
     case MSG_GET_TTY_MODE_RESPONSE:
       {
         Log.v(TtyManager.this, "got queryTTYMode response");
         AsyncResult ar = (AsyncResult) msg.obj;
         if (ar.exception != null) {
           Log.d(TtyManager.this, "queryTTYMode exception: %s", ar.exception);
         } else {
           int ttyMode = phoneModeToTelecomMode(((int[]) ar.result)[0]);
           if (ttyMode != mTtyMode) {
             Log.d(
                 TtyManager.this,
                 "setting TTY mode failed, attempted %d, got: %d",
                 mTtyMode,
                 ttyMode);
           } else {
             Log.d(TtyManager.this, "setting TTY mode to %d succeeded", ttyMode);
           }
         }
         break;
       }
   }
 }
Пример #2
0
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // If your preview can change or rotate, take care of those events here.
    // Make sure to stop the preview before resizing or reformatting it.

    if (mHolder.getSurface() == null) {
      // preview surface does not exist
      return;
    }

    // stop preview before making changes
    try {
      mCamera.stopPreview();

      Log.v(TAG, "stopPreview");

      googleGlassXE10WorkAround(mCamera);

    } catch (Exception e) {
      // ignore: tried to stop a non-existent preview
      Log.d(TAG, "Tried to stop a non-existent preview: " + e.getMessage());
    }

    // start preview with new settings
    try {
      mCamera.setPreviewDisplay(mHolder);
      mCamera.startPreview();
      Log.v(TAG, "startPreview");

    } catch (Exception e) {
      Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
  }
Пример #3
0
  @Override
  public void onBackPressed() {
    boolean handled = false;
    try {
      FragmentManager fm = getSupportFragmentManager();
      Fragment frag = fm.findFragmentById(R.id.fragment_content);
      if (!(frag instanceof FragUtils.BackPressedHandler)) {
        Log.d(TAG, "frag type was: " + (frag == null ? "null" : frag.getClass().getSimpleName()));
        return;
      }

      if (!frag.isVisible()) {
        Log.d(TAG, "frag was not visible!");
        return;
      }

      handled = ((FragUtils.BackPressedHandler) frag).handleBackPressed();
      //      Log.w(TAG, "handleBackPressed returned: " + handled);
    } catch (Exception e) {
      Log.e(TAG, "Could not check onBackPressed", e);
    } finally {
      if (!handled) {
        super.onBackPressed();
      }
    }
  }
Пример #4
0
  /** * Parse HTML file and extract the relevant content, and send it to be downloaded. */
  @Override
  public void run() {
    Log.d(String.format("AnalyzerTask is running on %s", currUrl));
    HashMap<String, ArrayList<String>> exts = new HashMap<>();

    // Put the extensions from config.ini in a hash-map, for passing it to the HtmlParser.
    exts.put("imageExtensions", WebCrawler.imageExtensions);
    exts.put("videoExtensions", WebCrawler.videoExtensions);
    exts.put("documentExtensions", WebCrawler.documentExtensions);

    // Extracting the relevant URLs from the given HTML.
    HtmlParser parser = new HtmlParser(currUrl, currHtml, exts);
    parser.parse();

    // Filling the URL lists with downloadable data
    ArrayList<String> imgUrls = parser.getImagesUrls();
    ArrayList<String> videoUrls = parser.getVideosUrls();
    ArrayList<String> docUrls = parser.getDocsUrls();
    ArrayList<String> hrefUrls = parser.getHrefUrls();

    Log.d("Sending images to downloads");
    sendToDownload(imgUrls, DownloaderTask.RESOURCE_TYPE_IMG);
    Log.d("Sending videos to downloads");
    sendToDownload(videoUrls, DownloaderTask.RESOURCE_TYPE_VIDEO);
    Log.d("Sending documents to downloads");
    sendToDownload(docUrls, DownloaderTask.RESOURCE_TYPE_DOC);
    Log.d("Sending HREFs to downloads");
    sendToDownload(hrefUrls, DownloaderTask.RESOURCE_TYPE_HREF);

    decreaseNumOfAnalyzersAlive();
  }
Пример #5
0
  public static String encodeDocumentUrl(String urlString) {
    try {

      URL url = new URL(urlString);
      URI uri =
          new URI(
              url.getProtocol(),
              url.getUserInfo(),
              url.getHost(),
              url.getPort(),
              url.getPath(),
              url.getQuery(),
              url.getRef());

      return uri.toASCIIString();

    } catch (MalformedURLException e) {
      if (Log.LOGD)
        Log.d(ExoUtils.class.getSimpleName(), e.getMessage(), Log.getStackTraceString(e));
      return null;
    } catch (URISyntaxException e) {
      if (Log.LOGD)
        Log.d(ExoUtils.class.getSimpleName(), e.getMessage(), Log.getStackTraceString(e));
      return null;
    }
  }
Пример #6
0
 /**
  * Extract a name from a Server URL by keeping the 1st part of the FQDN, between the protocol and
  * the first dot or the end of the URL. It is then capitalized. If an IP address is given instead,
  * it is used as-is. Examples:
  *
  * <ul>
  *   <li>http://int.exoplatform.com => Int
  *   <li>http://community.exoplatform.com => Community
  *   <li>https://mycompany.com => Mycompany
  *   <li>https://intranet.secure.mycompany.co.uk => Intranet
  *   <li>http://localhost => Localhost
  *   <li>http://192.168.1.15 => 192.168.1.15
  * </ul>
  *
  * @param url the Server URL
  * @param defaultName a default name in case it is impossible to extract
  * @return a name
  */
 public static String getAccountNameFromURL(String url, String defaultName) {
   String finalName = defaultName;
   if (url != null && !url.isEmpty()) {
     if (!url.startsWith("http")) url = ExoConnectionUtils.HTTP + url;
     try {
       URI theURL = new URI(url);
       finalName = theURL.getHost();
       if (!isCorrectIPAddress(finalName)) {
         int firstDot = finalName.indexOf('.');
         if (firstDot > 0) {
           finalName = finalName.substring(0, firstDot);
         }
         // else, no dot was found in the host,
         // return the hostname as is, e.g. localhost
       }
       // else, URL is an IP address, return it as is
     } catch (URISyntaxException e) {
       if (Log.LOGD)
         Log.d(ExoUtils.class.getSimpleName(), e.getMessage(), Log.getStackTraceString(e));
       finalName = defaultName;
     } catch (IndexOutOfBoundsException e) {
       if (Log.LOGD)
         Log.d(ExoUtils.class.getSimpleName(), e.getMessage(), Log.getStackTraceString(e));
       finalName = defaultName;
     }
   }
   return capitalize(finalName);
 }
  public void recalculateCodebooks() throws IOException {
    String dir =
        "/Users/thomaskaiser/Documents/MCM/MC480_Project_I/SVN/trunk/Implementation/ProjectFiles/mobile phone folder structure";
    HashMap<String, String> sampleDirectories = readSampleDirectories(dir);
    Set<String> keySet = sampleDirectories.keySet();

    for (String speakerId : keySet) {
      Log.d("Recalculating codebook for %s", speakerId);
      FeatureVector pl = null;
      try {
        pl = readFeatureVectorFile(sampleDirectories.get(speakerId));
      } catch (Exception e) {
        Log.e("Error reading feature vector", e);
      }

      KMeans kmeans = new KMeans(Constants.CLUSTER_COUNT, pl, Constants.CLUSTER_MAX_ITERATIONS);
      Log.d("Prepared k means clustering");
      long start = System.currentTimeMillis();
      kmeans.run();
      Log.d("Clustering finished, total time = " + (System.currentTimeMillis() - start) + "ms");

      Codebook cb = makeCodebook(kmeans);

      writeCodebook(sampleDirectories.get(speakerId), cb);
    }
  }
  @Override
  protected Boolean doInBackground(Void... params) {
    File ffmpegFile = new File(FileUtils.getFFmpeg(context));
    if (ffmpegFile.exists() && isDeviceFFmpegVersionOld() && !ffmpegFile.delete()) {
      return false;
    }
    if (!ffmpegFile.exists()) {
      boolean isFileCopied =
          FileUtils.copyBinaryFromAssetsToData(
              context,
              cpuArchNameFromAssets + File.separator + FileUtils.ffmpegFileName,
              FileUtils.ffmpegFileName);

      // make file executable
      if (isFileCopied) {
        if (!ffmpegFile.canExecute()) {
          Log.d("FFmpeg is not executable, trying to make it executable ...");
          if (ffmpegFile.setExecutable(true)) {
            return true;
          }
        } else {
          Log.d("FFmpeg is executable");
          return true;
        }
      }
    }
    return ffmpegFile.exists() && ffmpegFile.canExecute();
  }
Пример #9
0
 private static void freeArrays(final int[] hashes, final Object[] array, final int size) {
   if (hashes.length == (BASE_SIZE * 2)) {
     synchronized (ArrayMap.class) {
       if (mTwiceBaseCacheSize < CACHE_SIZE) {
         array[0] = mTwiceBaseCache;
         array[1] = hashes;
         for (int i = (size << 1) - 1; i >= 2; i--) {
           array[i] = null;
         }
         mTwiceBaseCache = array;
         mTwiceBaseCacheSize++;
         if (DEBUG)
           Log.d(
               TAG, "Storing 2x cache " + array + " now have " + mTwiceBaseCacheSize + " entries");
       }
     }
   } else if (hashes.length == BASE_SIZE) {
     synchronized (ArrayMap.class) {
       if (mBaseCacheSize < CACHE_SIZE) {
         array[0] = mBaseCache;
         array[1] = hashes;
         for (int i = (size << 1) - 1; i >= 2; i--) {
           array[i] = null;
         }
         mBaseCache = array;
         mBaseCacheSize++;
         if (DEBUG)
           Log.d(TAG, "Storing 1x cache " + array + " now have " + mBaseCacheSize + " entries");
       }
     }
   }
 }
 @Override
 public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
     this.callbackContext = callbackContext;
     Log.d("WIFI", action);
     if(ACTION_START.equals(action)){
         PluginResult pgRes = new PluginResult(PluginResult.Status.OK, "Registered");
         pgRes.setKeepCallback(true);
         mWifiManager = (WifiManager) this.cordova.getActivity().getSystemService(Context.WIFI_SERVICE);
         this.reciever = new BroadcastReceiver()
         {
             @Override
             public void onReceive(Context c, Intent intent)
             {
                List<ScanResult> scanResults = mWifiManager.getScanResults();
                handleResults(scanResults);
             }
         };
         this.cordova.getActivity().registerReceiver(this.reciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
         callbackContext.sendPluginResult(pgRes);
         Log.d("WIFI", "inside " + action);
         return true;
     } else if (ACTION_SCAN.equals(action)){
         PluginResult pgRes = new PluginResult(PluginResult.Status.OK, []);
         pgRes.setKeepCallback(true);
         mWifiManager = (WifiManager) this.cordova.getActivity().getSystemService(Context.WIFI_SERVICE);
         mWifiManager.startScan();
         callbackContext.sendPluginResult(pgRes);
         Log.d("WIFI", "inside " + action);
         return true;
     } else if (ACTION_STOP.equals(action)){
Пример #11
0
 public static File saveBitmap(Bitmap bmp, String id, Context context) {
   File file = getFile(id, context);
   if (!file.exists() && !file.isDirectory()) {
     try {
       FileOutputStream out = new FileOutputStream(file);
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       int quality = 100;
       bmp.compress(Bitmap.CompressFormat.PNG, quality, baos);
       Log.d("图片压缩前大小:" + baos.toByteArray().length / 1024 + "kb");
       if (baos.toByteArray().length / 1024 > 50) {
         quality = 80;
         baos.reset();
         bmp.compress(Bitmap.CompressFormat.PNG, quality, baos);
         Log.d("质量压缩到原来的" + quality + "%时大小为:" + baos.toByteArray().length / 1024 + "kb");
       }
       Log.d("图片压缩后大小:" + baos.toByteArray().length / 1024 + "kb");
       baos.writeTo(out);
       baos.flush();
       baos.close();
       out.close();
       //				bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return file;
 }
Пример #12
0
 static void dumpAll(Path p, String prefix1, String prefix2) {
   synchronized (Path.class) {
     MediaObject obj = p.getObject();
     Log.d(
         TAG,
         prefix1 + p.mSegment + ":" + (obj == null ? "null" : obj.getClass().getSimpleName()));
     if (p.mChildren != null) {
       ArrayList<String> childrenKeys = p.mChildren.keys();
       int i = 0, n = childrenKeys.size();
       for (String key : childrenKeys) {
         Path child = p.mChildren.get(key);
         if (child == null) {
           ++i;
           continue;
         }
         Log.d(TAG, prefix2 + "|");
         if (++i < n) {
           dumpAll(child, prefix2 + "+-- ", prefix2 + "|   ");
         } else {
           dumpAll(child, prefix2 + "+-- ", prefix2 + "    ");
         }
       }
     }
   }
 }
Пример #13
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.v(
        TAG,
        getClass().getSimpleName()
            + ".onCreate ("
            + hashCode()
            + "): "
            + (savedInstanceState != null));

    ApiCompatUtil compatUtil = ApiCompatUtil.getInstance();
    compatUtil.requestWindowFeatures(this);
    setContentView(R.layout.prime);
    compatUtil.setWindowFeatures(this);

    compatUtil.setupActionBar(this);

    int curTab = DEFAULT_TAB;

    if (savedInstanceState != null) {
      Bundle fragData = savedInstanceState.getBundle("fragData");
      if (fragData != null) {
        Log.d(TAG, "MainActivity.onCreate: got fragData!");
        for (String key : fragData.keySet()) {
          Log.d(TAG, "  fragData key: " + key);
          if (!m_fragData.containsKey(key)) m_fragData.putBundle(key, fragData.getBundle(key));
        }
      }

      curTab = savedInstanceState.getInt(PrefKey.opentab.name(), DEFAULT_TAB);
    }

    boolean upgraded = false;
    if (savedInstanceState != null) {
      //      setCurrentTab(savedInstanceState.getInt(PrefKey.opentab.name(), -1));
    } else {
      Resources resources = getResources();
      SharedPreferences p = StaticUtils.getApplicationPreferences(this);
      upgraded = StaticUtils.checkUpgrade(this);
      if (!readInstanceState(this)) setInitialState();
      if (PrefKey.sync_on_open.getBoolean(p, resources)) {
        WeaveAccountInfo loginInfo = StaticUtils.getLoginInfo(this);
        if (upgraded || loginInfo == null) {
          StaticUtils.requestSync(this, m_handler);
        }
      }
    }

    FragmentManager fm = getSupportFragmentManager();
    // You can find Fragments just like you would with a View by using FragmentManager.
    Fragment fragment = fm.findFragmentById(R.id.fragment_content);

    // If we are using activity_fragment_xml.xml then this the fragment will not be null, otherwise
    // it will be.
    if (fragment == null) {
      setMyFragment(new MiscListFragment(), false);
    }
  }
Пример #14
0
    public void handleMessage(Message msg) {
      WorkerArgs args = (WorkerArgs) msg.obj;
      Uri uri = null;
      if (msg.arg1 == EVENT_LOAD_IMAGE) {
        PhotoViewTag photoTag = (PhotoViewTag) args.view.getTag(TAG_PHOTO_INFOS);
        if (photoTag != null && photoTag.uri != null) {
          uri = photoTag.uri;
          Log.d(THIS_FILE, "get : " + uri);
          Bitmap img = contactsWrapper.getContactPhoto(args.context, uri, args.defaultResource);
          if (img != null) {
            args.result = img;
          } else {
            args.result = null;
          }
        }
      } else if (msg.arg1 == EVENT_LOAD_IMAGE_URI) {
        PhotoViewTag photoTag = (PhotoViewTag) args.view.getTag(TAG_PHOTO_INFOS);
        if (photoTag != null && photoTag.uri != null) {
          uri = photoTag.uri;
          Log.d(THIS_FILE, "get : " + uri);

          byte[] buffer = new byte[1024 * 16];
          Bitmap img = null;
          try {
            InputStream is = args.context.getContentResolver().openInputStream(uri);
            if (is != null) {
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              try {
                int size;
                while ((size = is.read(buffer)) != -1) {
                  baos.write(buffer, 0, size);
                }
              } finally {
                is.close();
              }
              byte[] boasBytes = baos.toByteArray();
              img = BitmapFactory.decodeByteArray(boasBytes, 0, boasBytes.length, null);
            }
          } catch (Exception ex) {
            Log.v(THIS_FILE, "Cannot load photo " + uri, ex);
          }

          if (img != null) {
            args.result = img;
          } else {
            args.result = null;
          }
        }
      }
      args.loadedUri = uri;

      // send the reply to the enclosing class.
      Message reply = ContactsAsyncHelper.this.obtainMessage(msg.what);
      reply.arg1 = msg.arg1;
      reply.obj = msg.obj;
      reply.sendToTarget();
    }
 // called by the javascript interface
 public void dialogOpened(final String id, final boolean open) {
   if (open) {
     Log.d("Dialog " + id + " added");
     mDialogStack.push(id);
   } else {
     Log.d("Dialog " + id + " closed");
     mDialogStack.remove(id);
   }
 }
Пример #16
0
 @Override
 public void onReceive(Context ctx, Intent intent) {
   Log.d("BroadcastReceiver called.");
   if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
     if (checkBlack(ctx, intent)) {
       Log.d("Check black success, abort the broadcast.");
       abortBroadcast();
     }
   }
 }
 /**
  * This gets called when an important state change happens. Based on the type of the event/state
  * change, either we will record the time of the event, or calculate the duration/latency.
  *
  * @param eventType type of a event to track
  */
 public static void onEvent(int eventType) {
   if (sInstance == null) {
     sInstance = new CameraPerformanceTracker();
   }
   long currentTime = System.currentTimeMillis();
   switch (eventType) {
     case ACTIVITY_START:
       sInstance.mAppStartTime = currentTime;
       break;
     case ACTIVITY_PAUSE:
       sInstance.mFirstPreviewFrameLatencyWarmStart = UNSET;
       break;
     case ACTIVITY_RESUME:
       sInstance.mAppResumeTime = currentTime;
       break;
     case FIRST_PREVIEW_FRAME:
       Log.d(TAG, "First preview frame received");
       if (sInstance.mFirstPreviewFrameLatencyColdStart == UNSET) {
         // Cold start.
         sInstance.mFirstPreviewFrameLatencyColdStart = currentTime - sInstance.mAppStartTime;
       } else {
         // Warm Start.
         sInstance.mFirstPreviewFrameLatencyWarmStart = currentTime - sInstance.mAppResumeTime;
       }
       // If the new frame is triggered by the mode switch, track the duration.
       if (sInstance.mModeSwitchStartTime != UNSET) {
         sInstance.mModeSwitchDuration = currentTime - sInstance.mModeSwitchStartTime;
         sInstance.mModeSwitchStartTime = UNSET;
       }
       break;
     case MODE_SWITCH_START:
       sInstance.mModeSwitchStartTime = currentTime;
       break;
     default:
       break;
   }
   if (DEBUG && eventType == FIRST_PREVIEW_FRAME) {
     Log.d(
         TAG,
         "Mode switch duration: "
             + (sInstance.mModeSwitchDuration == UNSET ? "UNSET" : sInstance.mModeSwitchDuration));
     Log.d(
         TAG,
         "Cold start latency: "
             + (sInstance.mFirstPreviewFrameLatencyColdStart == UNSET
                 ? "UNSET"
                 : sInstance.mFirstPreviewFrameLatencyColdStart));
     Log.d(
         TAG,
         "Warm start latency: "
             + (sInstance.mFirstPreviewFrameLatencyWarmStart == UNSET
                 ? "UNSET"
                 : sInstance.mFirstPreviewFrameLatencyWarmStart));
   }
 }
Пример #18
0
  public static int addOrThrowContact(Context context, String phoneNumber, long time) {
    Cursor c = null;
    int _id = -1;
    int count = 0;
    String selection = DBConstant.CONTACT_NUMBER + " LIKE '%" + phoneNumber + "'";
    try {
      c =
          context
              .getContentResolver()
              .query(
                  DBConstant.CONTACT_URI,
                  new String[] {DBConstant._ID, DBConstant.CONTACT_CALL_LOG_COUNT},
                  selection,
                  null,
                  null);
      if (c != null && c.moveToFirst() && c.getCount() > 0) {
        _id = c.getInt(c.getColumnIndex(DBConstant._ID));
        count = c.getInt(c.getColumnIndex(DBConstant.CONTACT_CALL_LOG_COUNT));
      }
    } catch (Exception e) {

    } finally {
      if (c != null) {
        c.close();
      }
    }
    Log.d(Log.TAG, "addOrThrowContact = id = " + _id);
    String name = getNameFromContact(context, phoneNumber);
    Log.d(Log.TAG, "name = " + name);
    if (_id != -1) {
      ContentValues values = new ContentValues();
      values.put(DBConstant.CONTACT_CALL_LOG_COUNT, (count + 1));
      values.put(DBConstant.CONTACT_UPDATE, time);
      if (!TextUtils.isEmpty(name)) {
        values.put(DBConstant.CONTACT_NAME, name);
        values.put(DBConstant.CONTACT_MODIFY_NAME, DBConstant.MODIFY_NAME_FORBID);
      }
      context
          .getContentResolver()
          .update(ContentUris.withAppendedId(DBConstant.CONTACT_URI, _id), values, null, null);
      return _id;
    }
    ContentValues values = new ContentValues();
    values.put(DBConstant.CONTACT_NUMBER, phoneNumber);
    values.put(DBConstant.CONTACT_CALL_LOG_COUNT, 1);
    values.put(DBConstant.CONTACT_UPDATE, time);
    if (!TextUtils.isEmpty(name)) {
      values.put(DBConstant.CONTACT_NAME, name);
      values.put(DBConstant.CONTACT_MODIFY_NAME, DBConstant.MODIFY_NAME_FORBID);
    }
    Uri contentUri = context.getContentResolver().insert(DBConstant.CONTACT_URI, values);

    return (int) ContentUris.parseId(contentUri);
  }
Пример #19
0
  /**
   * Links all keys with secrets to the main ("me") contact
   * http://developer.android.com/reference/android/provider/ContactsContract.Profile.html
   *
   * @param context
   */
  public static void writeKeysToMainProfileContact(Context context, ContentResolver resolver) {
    // deletes contacts hidden by the user so they can be reinserted if necessary
    deleteFlaggedMainProfileRawContacts(resolver);

    Set<Long> keysToDelete = getMainProfileMasterKeyIds(resolver);

    // get all keys which have associated secret keys
    // TODO: figure out why using selectionArgs does not work in this case
    Cursor cursor =
        resolver.query(
            KeychainContract.KeyRings.buildUnifiedKeyRingsUri(),
            KEYS_TO_CONTACT_PROJECTION,
            KeychainContract.KeyRings.HAS_ANY_SECRET + "!=0",
            null,
            null);
    if (cursor != null)
      try {
        while (cursor.moveToNext()) {
          long masterKeyId = cursor.getLong(INDEX_MASTER_KEY_ID);
          boolean isExpired = cursor.getInt(INDEX_IS_EXPIRED) != 0;
          boolean isRevoked = cursor.getInt(INDEX_IS_REVOKED) > 0;
          KeyRing.UserId userIdSplit = KeyRing.splitUserId(cursor.getString(INDEX_USER_ID));

          if (!isExpired && !isRevoked && userIdSplit.name != null) {
            // if expired or revoked will not be removed from keysToDelete or inserted
            // into main profile ("me" contact)
            boolean existsInMainProfile = keysToDelete.remove(masterKeyId);
            if (!existsInMainProfile) {
              long rawContactId = -1; // new raw contact

              Log.d(Constants.TAG, "masterKeyId with secret " + masterKeyId);

              ArrayList<ContentProviderOperation> ops = new ArrayList<>();
              insertMainProfileRawContact(ops, masterKeyId);
              writeContactKey(ops, context, rawContactId, masterKeyId, userIdSplit.name);

              try {
                resolver.applyBatch(ContactsContract.AUTHORITY, ops);
              } catch (Exception e) {
                Log.w(Constants.TAG, e);
              }
            }
          }
        }
      } finally {
        cursor.close();
      }

    for (long masterKeyId : keysToDelete) {
      deleteMainProfileRawContactByMasterKeyId(resolver, masterKeyId);
      Log.d(Constants.TAG, "Delete main profile raw contact with masterKeyId " + masterKeyId);
    }
  }
Пример #20
0
 private static final boolean isAndroidEmulator() {
   String model = Build.MODEL;
   Log.d(TAG, "model=" + model);
   String product = Build.PRODUCT;
   Log.d(TAG, "product=" + product);
   boolean isEmulator = false;
   if (product != null) {
     isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
   }
   Log.d(TAG, "isEmulator=" + isEmulator);
   return isEmulator;
 }
Пример #21
0
  /**
   * Add a new value to the array map.
   *
   * @param key The key under which to store the value. <b>Must not be null.</b> If this key already
   *     exists in the array, its value will be replaced.
   * @param value The value to store for the given key.
   * @return Returns the old value that was stored for the given key, or null if there was no such
   *     key.
   */
  @Override
  public V put(K key, V value) {
    final int hash;
    int index;
    if (key == null) {
      hash = 0;
      index = indexOfNull();
    } else {
      hash = key.hashCode();
      index = indexOf(key, hash);
    }
    if (index >= 0) {
      index = (index << 1) + 1;
      final V old = (V) mArray[index];
      mArray[index] = value;
      return old;
    }

    index = ~index;
    if (mSize >= mHashes.length) {
      final int n =
          mSize >= (BASE_SIZE * 2)
              ? (mSize + (mSize >> 1))
              : (mSize >= BASE_SIZE ? (BASE_SIZE * 2) : BASE_SIZE);

      if (DEBUG) Log.d(TAG, "put: grow from " + mHashes.length + " to " + n);

      final int[] ohashes = mHashes;
      final Object[] oarray = mArray;
      allocArrays(n);

      if (mHashes.length > 0) {
        if (DEBUG) Log.d(TAG, "put: copy 0-" + mSize + " to 0");
        System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length);
        System.arraycopy(oarray, 0, mArray, 0, oarray.length);
      }

      freeArrays(ohashes, oarray, mSize);
    }

    if (index < mSize) {
      if (DEBUG) Log.d(TAG, "put: move " + index + "-" + (mSize - index) + " to " + (index + 1));
      System.arraycopy(mHashes, index, mHashes, index + 1, mSize - index);
      System.arraycopy(mArray, index << 1, mArray, (index + 1) << 1, (mSize - index) << 1);
    }

    mHashes[index] = hash;
    mArray[index << 1] = key;
    mArray[(index << 1) + 1] = value;
    mSize++;
    return null;
  }
Пример #22
0
 public void liveCardPublish(boolean nonSilent, long drawFrequency) {
   if (liveCard != null) return;
   this.drawFrequency = drawFrequency;
   liveCard = new LiveCard(context, "myid");
   Log.d(TAG, "Publishing LiveCard");
   liveCard.setDirectRenderingEnabled(true).getSurfaceHolder().addCallback(this);
   Intent intent = new Intent(context, MenuActivity.class);
   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
   liveCard.setAction(PendingIntent.getActivity(context, 0, intent, 0));
   if (nonSilent) liveCard.publish(LiveCard.PublishMode.REVEAL);
   else liveCard.publish(LiveCard.PublishMode.SILENT);
   Log.d(TAG, "Done publishing LiveCard");
 }
  /**
   * Notify the result.
   *
   * @param result The result.
   */
  public void notifyResult(CtsTestResult result) {

    Log.d("Test.notifyResult() is called. (Test.getFullName()=" + getFullName());
    mResult = result;
    if (mTimeOutTimer != null) {
      synchronized (mTimeOutTimer) {
        // set result again in case timeout just happened
        mResult = result;
        Log.d("notifyUpdateResult() detects that it needs to cancel mTimeOutTimer");
        if (mTimeOutTimer != null) {
          mTimeOutTimer.sendNotify();
        }
      }
    }
  }
Пример #24
0
 public static boolean isDocumentUrlValid(String str) {
   try {
     URL url = new URL(str.replaceAll(" ", "%20"));
     url.toURI();
     return true;
   } catch (MalformedURLException e) {
     if (Log.LOGD)
       Log.d(ExoUtils.class.getSimpleName(), e.getMessage(), Log.getStackTraceString(e));
     return false;
   } catch (URISyntaxException e) {
     if (Log.LOGD)
       Log.d(ExoUtils.class.getSimpleName(), e.getMessage(), Log.getStackTraceString(e));
     return false;
   }
 }
Пример #25
0
  private void _showUri() {
    version = bible.getVersion();
    Log.d(TAG, "showuri: " + uri);
    if (uri == null) {
      Log.d(TAG, "show null uri, use default");
      uri =
          Provider.CONTENT_URI_CHAPTER
              .buildUpon()
              .appendEncodedPath(null)
              .fragment(version)
              .build();
    }
    Cursor cursor = null;
    try {
      cursor = getContentResolver().query(uri, null, null, null, null);
    } catch (SQLiteException e) {
      showContent("", getString(R.string.queryerror));
      return;
    } catch (Exception e) {
    }
    if (cursor != null) {
      cursor.moveToFirst();

      osis = cursor.getString(cursor.getColumnIndexOrThrow(Provider.COLUMN_OSIS));
      osis_next = cursor.getString(cursor.getColumnIndexOrThrow(Provider.COLUMN_NEXT));
      osis_prev = cursor.getString(cursor.getColumnIndexOrThrow(Provider.COLUMN_PREVIOUS));
      final String human = cursor.getString(cursor.getColumnIndexOrThrow(Provider.COLUMN_HUMAN));
      final String content =
          cursor.getString(cursor.getColumnIndexOrThrow(Provider.COLUMN_CONTENT));
      cursor.close();

      showContent(human + " | " + version, content);
    } else {
      Log.d(TAG, "no such chapter, try first chapter");
      Uri nulluri =
          Provider.CONTENT_URI_CHAPTER
              .buildUpon()
              .appendEncodedPath(null)
              .fragment(version)
              .build();
      if (!nulluri.equals(uri)) {
        uri = nulluri;
        showUri();
      } else {
        showContent("", getString(R.string.queryerror));
      }
    }
  }
    @Override
    public void run() {
      if (mmSocket == null) return;
      Log.d("Device " + OneSheeldDevice.this.name + ": Establishing connection.");
      LooperThread =
          new Thread(
              new Runnable() {

                @Override
                public void run() {
                  Looper.prepare();
                  writeHandlerLooper = Looper.myLooper();
                  writeHandler = new Handler();
                  Looper.loop();
                }
              });
      LooperThread.setName("OneSheeldConnectedWriteThread: " + OneSheeldDevice.this.getName());
      LooperThread.start();
      while (!LooperThread.isAlive()) ;
      synchronized (isConnectedLock) {
        isConnected = true;
      }
      byte[] buffer = new byte[MAX_BUFFER_SIZE];
      int bufferLength;
      Log.d(
          "Device "
              + OneSheeldDevice.this.name
              + ": Initializing board and querying its information.");
      initFirmware();
      Log.d(
          "Device "
              + OneSheeldDevice.this.name
              + ": Device connected, initialized and ready for communication.");
      onConnect();
      while (!this.isInterrupted()) {
        try {
          bufferLength = mmInStream.read(buffer, 0, buffer.length);
          bufferLength = bufferLength >= buffer.length ? buffer.length : bufferLength;
          for (int i = 0; i < bufferLength; i++) {
            bluetoothBuffer.add(buffer[i]);
          }
        } catch (IOException e) {
          if (writeHandlerLooper != null) writeHandlerLooper.quit();
          closeConnection();
          break;
        }
      }
    }
Пример #27
0
 private void swapConference(String callId) {
   Log.d(this, "swapConference(%s)", callId);
   Conference conference = findConferenceForAction(callId, "swapConference");
   if (conference != null) {
     conference.onSwap();
   }
 }
Пример #28
0
 private void mergeConference(String callId) {
   Log.d(this, "mergeConference(%s)", callId);
   Conference conference = findConferenceForAction(callId, "mergeConference");
   if (conference != null) {
     conference.onMerge();
   }
 }
Пример #29
0
 @Override
 public void onStateChanged(Connection c, int state) {
   String id = mIdByConnection.get(c);
   Log.d(this, "Adapter set state %s %s", id, Connection.stateToString(state));
   switch (state) {
     case Connection.STATE_ACTIVE:
       mAdapter.setActive(id);
       break;
     case Connection.STATE_DIALING:
       mAdapter.setDialing(id);
       break;
     case Connection.STATE_DISCONNECTED:
       // Handled in onDisconnected()
       break;
     case Connection.STATE_HOLDING:
       mAdapter.setOnHold(id);
       break;
     case Connection.STATE_NEW:
       // Nothing to tell Telecom
       break;
     case Connection.STATE_RINGING:
       mAdapter.setRinging(id);
       break;
   }
 }
  /*
   * imageView = (ImageView) findViewById(R.id.imageView); Bitmap myImg =
   * BitmapFactory.decodeResource(getResources(), R.drawable.image);
   *
   * Matrix matrix = new Matrix(); matrix.postRotate(30);
   *
   * Bitmap rotated = Bitmap.createBitmap(myImg, 0, 0, myImg.getWidth(),
   * myImg.getHeight(), matrix, true);
   *
   * imageView.setImageBitmap(rotated);
   */
  public static void showImage(ImageView imageView, String imageName) throws IOException {
    Log.d(TAG, "showImage");

    Bitmap bm;
    bm = ImageManager.getBitmapFromAssets(imageName);
    imageView.setImageBitmap(bm);
  }