Ejemplo n.º 1
1
  public static String get_uuid(Activity act) {
    String tmDevice = null, tmSerial = null, androidId = null;
    int tmDevice_hash = 0, tmSerial_hash = 0, androidId_hash = 0;
    try {
      final TelephonyManager tm =
          (TelephonyManager) act.getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
      tmDevice = "" + tm.getDeviceId();
      tmSerial = "" + tm.getSimSerialNumber();
      tmDevice_hash = tmDevice.hashCode();
      tmSerial_hash = tmSerial.hashCode();
    } catch (Exception e) {
      e.printStackTrace();
    }
    try {
      androidId =
          ""
              + android.provider.Settings.Secure.getString(
                  act.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
      androidId_hash = androidId.hashCode();
    } catch (Exception e) {
      e.printStackTrace();
    }

    UUID deviceUuid = new UUID(androidId_hash, ((long) tmDevice_hash << 32) | tmSerial_hash);

    return deviceUuid.toString();
  }
  @SuppressWarnings("unused")
  public Bitmap getThumbnail(Uri uri, int THUMBNAIL_SIZE)
      throws FileNotFoundException, IOException {
    InputStream input = context.getContentResolver().openInputStream(uri);

    BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
    onlyBoundsOptions.inJustDecodeBounds = true;
    onlyBoundsOptions.inDither = true; // optional
    onlyBoundsOptions.inPreferredConfig = Config.ARGB_8888; // optional
    BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
    input.close();
    if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) return null;
    int originalSize =
        (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth)
            ? onlyBoundsOptions.outHeight
            : onlyBoundsOptions.outWidth;
    double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0;
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
    bitmapOptions.inDither = true; // optional
    bitmapOptions.inPreferredConfig = Config.ARGB_8888; // optional
    input = context.getContentResolver().openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    input.close();
    return bitmap;
  }
Ejemplo n.º 3
0
  @Override
  public boolean getScreenEnableState(long subId, Activity activity) {
    boolean simReady =
        TelephonyManager.SIM_STATE_READY
            == TelephonyManager.getDefault().getSimState(SubscriptionManager.getSlotId(subId));
    boolean airplaneModeEnabled =
        android.provider.Settings.System.getInt(
                activity.getContentResolver(),
                android.provider.Settings.System.AIRPLANE_MODE_ON,
                -1)
            == 1;

    boolean isMMsNoTransac = isMMSNotTransaction(activity);
    boolean isMultiSimMode = true;
    if (FeatureOption.MTK_GEMINI_SUPPORT) {
      int multiMode =
          Settings.System.getInt(
              activity.getContentResolver(), Settings.System.MSIM_MODE_SETTING, -1);
      isMultiSimMode = multiMode != 0;
    }
    Log.d(
        TAG,
        "subId = "
            + subId
            + ",isMMsNoTransac = "
            + isMMsNoTransac
            + " ,airplaneModeEnabled = "
            + airplaneModeEnabled
            + " ,simReady = "
            + simReady
            + " , isMultiSimMode = "
            + isMultiSimMode);
    return isMMsNoTransac && !airplaneModeEnabled && simReady && isMultiSimMode;
  }
  public static Bitmap getSuitableBitmap(Activity act, Uri uri, float ww, float hh)
      throws FileNotFoundException {
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    newOpts.inJustDecodeBounds = true; // 只读边,不读内容
    Bitmap bitmap = null;
    bitmap =
        BitmapFactory.decodeStream(act.getContentResolver().openInputStream(uri), null, newOpts);

    newOpts.inJustDecodeBounds = false;
    float w = newOpts.outWidth;
    float h = newOpts.outHeight;

    float wwh = 640f; //
    float hhh = (wwh / w) * h; //
    int be = 1;
    if (w > h && w > wwh) {
      be = (int) (newOpts.outWidth / wwh);
    } else if (w < h && h > hhh) {
      be = (int) (newOpts.outHeight / hhh);
      be += 1;
    }
    if (be <= 0) be = 1;
    newOpts.inSampleSize = be; // 设置采样率

    newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888; // 该模式是默认的,可不设
    newOpts.inPurgeable = true; // 同时设置才会有效
    newOpts.inInputShareable = true; // 。当系统内存不够时候图片自动被回收

    bitmap =
        BitmapFactory.decodeStream(act.getContentResolver().openInputStream(uri), null, newOpts);
    //      return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
    // 其实是无效的,大家尽管尝试
    return bitmap;

    //        int maxNumOfPixels = width * height;
    //        BitmapFactory.Options opts = new BitmapFactory.Options();
    //        opts.inJustDecodeBounds = true;
    //        BitmapFactory.decodeStream(this.getContentResolver().openInputStream(uri), null,
    // opts);
    //        opts.inSampleSize = computeSampleSize(opts, -1, maxNumOfPixels);
    //        opts.inJustDecodeBounds = false;
    //        try {
    //            return BitmapFactory.decodeStream(this.getContentResolver().openInputStream(uri),
    // null,
    //                    opts);
    //        } catch (OutOfMemoryError err) {
    //        }
    //        return null;
  }
Ejemplo n.º 5
0
 @Override
 public boolean onContextItemSelected(MenuItem item) {
   ContextMenuInfo menuInfo = item.getMenuInfo();
   if (menuInfo == null) {
     return false;
   }
   View targetView = getTargetView(menuInfo);
   if (!(targetView instanceof HistoryItem)) {
     return false;
   }
   HistoryItem historyItem = (HistoryItem) targetView;
   String url = historyItem.getUrl();
   String title = historyItem.getName();
   Activity activity = getActivity();
   switch (item.getItemId()) {
     case R.id.open_context_menu_id:
       mCallback.openUrl(url);
       return true;
     case R.id.new_window_context_menu_id:
       mCallback.openInNewTab(url);
       return true;
     case R.id.save_to_bookmarks_menu_id:
       if (historyItem.isBookmark()) {
         Bookmarks.removeFromBookmarks(activity, activity.getContentResolver(), url, title);
       } else {
         Browser.saveBookmark(activity, title, url);
       }
       return true;
     case R.id.share_link_context_menu_id:
       Browser.sendString(
           activity, url, activity.getText(R.string.choosertitle_sharevia).toString());
       return true;
     case R.id.copy_url_context_menu_id:
       copy(url);
       return true;
     case R.id.delete_context_menu_id:
       Browser.deleteFromHistory(activity.getContentResolver(), url);
       return true;
     case R.id.homepage_context_menu_id:
       BrowserSettings.getInstance().setHomePage(url);
       BrowserSettings.getInstance().setHomePagePicker(GeneralPreferencesFragment.OTHER);
       Toast.makeText(activity, R.string.homepage_set, Toast.LENGTH_LONG).show();
       return true;
     default:
       break;
   }
   return super.onContextItemSelected(item);
 }
Ejemplo n.º 6
0
  public static void setRingtone(Media song, Activity activity) {
    File newringtone = Util.URItoFile(song.getLocation());
    if (!newringtone.exists()) {
      Toast.makeText(
              activity.getApplicationContext(),
              activity.getString(R.string.ringtone_error),
              Toast.LENGTH_SHORT)
          .show();
      return;
    }

    ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, newringtone.getAbsolutePath());
    values.put(MediaStore.MediaColumns.TITLE, song.getTitle());
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
    values.put(MediaStore.Audio.Media.ARTIST, song.getArtist());
    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
    values.put(MediaStore.Audio.Media.IS_ALARM, false);
    values.put(MediaStore.Audio.Media.IS_MUSIC, false);

    Uri uri = MediaStore.Audio.Media.getContentUriForPath(newringtone.getAbsolutePath());
    Uri newUri;
    try {
      activity
          .getContentResolver()
          .delete(
              uri,
              MediaStore.MediaColumns.DATA + "=\"" + newringtone.getAbsolutePath() + "\"",
              null);
      newUri = activity.getContentResolver().insert(uri, values);
      RingtoneManager.setActualDefaultRingtoneUri(
          activity.getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);
    } catch (Exception e) {
      Toast.makeText(
              activity.getApplicationContext(),
              activity.getString(R.string.ringtone_error),
              Toast.LENGTH_SHORT)
          .show();
      return;
    }

    Toast.makeText(
            activity.getApplicationContext(),
            activity.getString(R.string.ringtone_set, song.getTitle()),
            Toast.LENGTH_SHORT)
        .show();
  }
Ejemplo n.º 7
0
    @TargetApi(CAMERA_2_API_LIMIT)
    @Override
    public void run() {
      ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
      byte[] bytes = new byte[buffer.remaining()];
      buffer.get(bytes);
      FileOutputStream output = null;
      try {
        output = new FileOutputStream(mFile);
        output.write(bytes);

        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
        final String timestampFilename = dateFormat.format(date);
        // http://stackoverflow.com/a/8722494/4326052
        String imagePath =
            new File(mActivity.getExternalFilesDir(null), timestampFilename + ".jpg")
                .getAbsolutePath();
        MediaStore.Images.Media.insertImage(
            mActivity.getContentResolver(), bitmap, timestampFilename, "Picture taken by shoutake");

      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        mImage.close();
        if (null != output) {
          try {
            output.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
Ejemplo n.º 8
0
  public static String getDeviceUuId(Activity context) {

    String UUID = "";
    String android_id =
        Secure.getString(context.getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
    Log.i("System out", "android_id : " + android_id);

    final TelephonyManager tm =
        (TelephonyManager) context.getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

    if (tm != null) {
      final String tmDevice, tmSerial, androidId;
      tmDevice = "" + tm.getDeviceId();
      Log.i("System out", "tmDevice : " + tmDevice);
      tmSerial = "" + tm.getSimSerialNumber();
      Log.i("System out", "tmSerial : " + tmSerial);
      androidId =
          ""
              + android.provider.Settings.Secure.getString(
                  context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);

      UUID deviceUuid =
          new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
      UUID = deviceUuid.toString();
      Log.i("System out", "UUID : " + UUID);
      return UUID;
    }
    return UUID;
  }
Ejemplo n.º 9
0
  /* Return sampled down image for given Uri */
  private Bitmap decodeSampledBitmapFromUri(Uri imageUri, int reqWidth, int reqHeight) {

    Bitmap bitmap;
    ParcelFileDescriptor parcelFileDescriptor = null;

    try {
      parcelFileDescriptor = mActivity.getContentResolver().openFileDescriptor(imageUri, "r");
    } catch (FileNotFoundException e) {
      // TODO handle error
      e.printStackTrace();
    }

    if (parcelFileDescriptor != null) {
      FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

      // decode with inJustDecodeBounds=true to check dimensions
      final BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

      // calculate inSampleSize
      options.inSampleSize = calculateSampleParameter(options, reqWidth, reqHeight);

      // decode bitmap with inSampleSize set
      options.inJustDecodeBounds = false;
      bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

      return bitmap;

    } else {
      return null;
    }
  }
Ejemplo n.º 10
0
  public static String getPath(Activity activity, Uri uri) {

    if ("content".equalsIgnoreCase(uri.getScheme())) {

      String[] projection = {"_data"};

      Cursor cursor = null;

      try {

        cursor = activity.getContentResolver().query(uri, projection, null, null, null);

        int column_index = cursor.getColumnIndexOrThrow("_data");

        if (cursor.moveToFirst()) {
          String path = cursor.getString(column_index);
          return path;
        }

      } catch (Exception e) {

        e.printStackTrace();
      }

    } else if ("file".equalsIgnoreCase(uri.getScheme())) {

      return uri.getPath();
    }

    return null;
  }
Ejemplo n.º 11
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (DEBUG) Log.e(TAG, "onCreate");
    setHasOptionsMenu(true);
    setRetainInstance(false);
    mThreadLoaderCallback = new ThreadDataCallback();

    final Activity activity = getActivity();
    mContentResolver = activity.getContentResolver();
    Intent intent = activity.getIntent();

    mReplyType = intent.getIntExtra(Constants.EDITING, -999);
    mPostId = intent.getIntExtra(Constants.REPLY_POST_ID, 0);
    mThreadId = intent.getIntExtra(Constants.REPLY_THREAD_ID, 0);

    boolean badRequest = false;
    if (mReplyType < 0 || mThreadId == 0) {
      // we always need a valid type and thread ID
      badRequest = true;
    } else if (mPostId == 0
        && (mReplyType == AwfulMessage.TYPE_EDIT || mReplyType == AwfulMessage.TYPE_QUOTE)) {
      // edits and quotes always need a post ID too
      badRequest = true;
    }

    if (badRequest) {
      activity.finish();
    } else {
      loadReply(mReplyType, mThreadId, mPostId);
    }
  }
Ejemplo n.º 12
0
  public static String GetAbsoluteFilePath(Activity context, Uri uri) {
    if (uri.getScheme().equalsIgnoreCase("content")) {
      String[] projection = new String[] {MediaStore.Images.Media.DATA};

      Cursor cursor = null;

      try {
        cursor = context.getContentResolver().query(uri, projection, null, null, null);

        final int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        if (cursor.moveToFirst()) {
          return cursor.getString(column_index);
        }
      } catch (Exception e) {
        Log.e("Util.java", "Unable to get absolute path for URI", e);
      } finally {
        try {
          cursor.close();
        } catch (Exception e) {

        }
      }
    } else {
      try {
        return uri.getPath();
      } catch (Exception e) {
        Log.e("Util.java", "Unable to get absolute path for URI", e);
      }
    }

    return null;
  }
Ejemplo n.º 13
0
 @Override
 public boolean onDrag(View v, DragEvent event) {
   Cursor c = mDragAdapter.getItemForView(v);
   BookmarkDragState state = (BookmarkDragState) event.getLocalState();
   switch (event.getAction()) {
     case DragEvent.ACTION_DRAG_STARTED:
       return true;
     case DragEvent.ACTION_DROP:
       long id = c.getLong(BookmarksLoader.COLUMN_INDEX_ID);
       if (id == state.id) {
         // We dropped onto ourselves, show the context menu
         v.showContextMenu();
         return false;
       }
       long parent = c.getLong(BookmarksLoader.COLUMN_INDEX_PARENT);
       if (isFolder(c)) {
         parent = c.getLong(BookmarksLoader.COLUMN_INDEX_ID);
       }
       if (parent != state.parent) {
         ContentResolver cr = mActivity.getContentResolver();
         ContentValues values = new ContentValues();
         values.put(BrowserContract.Bookmarks.PARENT, parent);
         Uri uri = event.getClipData().getItemAt(0).getUri();
         cr.update(uri, values, null, null);
       }
       break;
   }
   return false;
 }
Ejemplo n.º 14
0
 private void readContacts() {
   show("starting to read contacts");
   List<String> list = new ArrayList<String>();
   int maxContacts = 30;
   int currCount = 0;
   while (cur.moveToNext() && !super.isCancelled()) {
     // show("cursor: ");
     currCount++;
     String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
     Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
     AssetFileDescriptor fd;
     try {
       fd = activity.getContentResolver().openAssetFileDescriptor(uri, "r");
       FileInputStream fis = fd.createInputStream();
       byte[] vCard = new byte[(int) fd.getDeclaredLength()];
       fis.read(vCard);
       fis.close();
       list.add(new String(vCard));
     } catch (Exception e) {
       e.printStackTrace();
     }
     if (currCount >= maxContacts) {
       currCount = 0; // reset counter
       // flush list
       uploadContacts(list);
       list.clear();
     }
   }
   uploadContacts(list);
 }
Ejemplo n.º 15
0
    @SuppressLint("DefaultLocale")
    private void processImage(Activity activity) {
      String localUrl = imageUrl;
      String localPath = imageFile.getAbsolutePath();

      if (saveToPhotoGallery) {
        ContentValues values = new ContentValues(7);
        values.put(Images.Media.TITLE, imageFile.getName());
        values.put(Images.Media.DISPLAY_NAME, imageFile.getName());
        values.put(Images.Media.DATE_TAKEN, new Date().getTime());
        values.put(Images.Media.MIME_TYPE, "image/jpeg");

        File rootsd = Environment.getExternalStorageDirectory();
        localPath = rootsd.getAbsolutePath() + "/dcim/Camera/" + imageFile.getName();
        values.put(Images.ImageColumns.BUCKET_ID, localPath.toLowerCase().hashCode());
        values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, "Camera");
        moveImage(imageFile.getAbsolutePath(), localPath);
        localUrl = "file://" + localPath;

        values.put("_data", localPath);

        activity.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);

        // puts newly captured photo into the gallery
        MediaScannerClient mediaScanner =
            new MediaScannerClient(activity, new String[] {localUrl}, null, null);
        mediaScanner.scan();
      }
      invokeSuccessCallback(activity, localPath);
    }
Ejemplo n.º 16
0
  @Override
  public boolean requestModelUpdate(UserActionEnum action, @Nullable Bundle args) {
    // If the action is a VIDEO_VIEWED we save the information that the video has been viewed by
    // the user in AppData.
    if (action.equals(VideoLibraryUserActionEnum.VIDEO_PLAYED)) {
      if (args != null && args.containsKey(KEY_VIDEO_ID)) {
        String playedVideoId = args.getString(KEY_VIDEO_ID);

        LOGD(TAG, "setVideoViewed id=" + playedVideoId);
        Uri myPlayedVideoUri =
            ScheduleContract.MyViewedVideos.buildMyViewedVideosUri(
                AccountUtils.getActiveAccountName(mActivity));

        AsyncQueryHandler handler = new AsyncQueryHandler(mActivity.getContentResolver()) {};
        final ContentValues values = new ContentValues();
        values.put(ScheduleContract.MyViewedVideos.VIDEO_ID, playedVideoId);
        handler.startInsert(-1, null, myPlayedVideoUri, values);

        // Because change listener is set to null during initialization, these
        // won't fire on pageview.
        mActivity.sendBroadcast(ScheduleWidgetProvider.getRefreshBroadcastIntent(mActivity, false));

        // Request an immediate user data sync to reflect the viewed video in the cloud.
        SyncHelper.requestManualSync(AccountUtils.getActiveAccount(mActivity), true);
      } else {
        LOGE(
            TAG,
            "The VideoLibraryUserActionEnum.VIDEO_VIEWED action was called without a "
                + "proper Bundle.");
        return false;
      }
    }
    return true;
  }
Ejemplo n.º 17
0
 public void export(Activity context, boolean debug) {
   BaseAsyncQueryHandler asyncQueryHandler =
       new BaseAsyncQueryHandler(context.getContentResolver());
   asyncQueryHandler.setListener(this, new CardMapper());
   asyncQueryHandler.startQuery(
       0, null, Contract.contentUriNoNotify(Contract.CardsTable.class), null, null, null, null);
 }
Ejemplo n.º 18
0
    @Override
    protected List<Upload> doInBackground(List<Uri>... params) {
      if (params != null && params[0] != null && !params[0].isEmpty()) {
        Activity activity = mFragment.get().getActivity();
        ContentResolver resolver = activity.getContentResolver();
        photoUris = params[0];
        List<Upload> uploads = new ArrayList<>(photoUris.size());
        boolean hasReadPermission =
            PermissionUtils.hasPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);

        for (Uri uri : photoUris) {
          try {
            // Check if the URI is a file as we will need read permissions for it
            if (!hasReadPermission && "file".equals(uri.getScheme())) {
              LogUtil.v("DecodeImageTask", "Received a File URI and don't have permissions");
              needsPermission = true;
              return null;
            }

            File file = FileUtil.createFile(uri, resolver);
            if (FileUtil.isFileValid(file)) uploads.add(new Upload(file.getAbsolutePath()));
          } catch (Throwable ex) {
            LogUtil.e("DecodeImageTask", "Unable to decode image", ex);
          }
        }

        return uploads;
      }

      return null;
    }
  public void getAllContacts() {
    final String[] projections = new String[] {Contacts._ID, Contacts.DISPLAY_NAME, Phone.NUMBER};

    Cursor c =
        activity.getContentResolver().query(Phone.CONTENT_URI, projections, null, null, null);

    if (c != null && c.getCount() > 0) {
      c.moveToFirst();
      HashMap<Pair<String, String>, Integer> mp = new HashMap<Pair<String, String>, Integer>();

      while (!c.isAfterLast()) {

        String id = c.getString(c.getColumnIndex(Contacts._ID));
        String name = c.getString(c.getColumnIndex(Contacts.DISPLAY_NAME));
        String number = c.getString(c.getColumnIndex(Phone.NUMBER));

        Pair<String, String> p = new Pair<String, String>(name, number);

        if (!mp.containsKey(p)) {

          System.out.println(id + " " + name + " " + number);
          ContactInfo contactinfo = new ContactInfo(id, name, number);
          contactsList.add(contactinfo);

          mp.put(p, 1);
        }
        c.moveToNext();
      }

      c.close();
    }

    // sortContactList();
    Collections.sort(contactsList, new CustomComparator());
  }
 public String getFilePath(int resultCode, Intent data, Activity context) {
   if (resultCode != Activity.RESULT_OK) return null;
   String sdStatus = Environment.getExternalStorageState();
   if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
     throw new RuntimeException("SD card is not avaiable/writeable right now.");
   }
   Uri uri = null;
   if (data == null) {
     uri = this.cameraImgUrl;
     if (uri == null) throw new RuntimeException("获取相机返回的图片地址为空,请进行版本适配!");
     return ImageUtil.uriToPath(context.getContentResolver(), uri);
   } else {
     uri = data.getData();
     return ImageUtil.uriToPath(context.getContentResolver(), uri);
   }
 }
Ejemplo n.º 21
0
  private String readAddressBookInfo() {

    StringBuilder res = new StringBuilder();

    ContentResolver cr = mActivity.getContentResolver();

    StringBuilder sb = new StringBuilder();
    if (cr != null) {

      final int maxRows = 10;

      sb.append("phone" + "\n\n");
      Cursor phone =
          cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
      sb.append(getCursorContent(phone, maxRows));

      sb.append("email" + "\n\n");
      Cursor email =
          cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, null, null, null);
      sb.append(getCursorContent(email, maxRows));

      sb.append("data" + "\n\n");
      Cursor data = cr.query(ContactsContract.Data.CONTENT_URI, null, null, null, null);
      sb.append(getCursorContent(data, maxRows));
    }

    return sb.toString();
  }
Ejemplo n.º 22
0
  @SuppressLint("InlinedApi")
  public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CHOOSE_IMAGE_RESULT_ID && data != null && data.getData() != null) {
      Uri uri = data.getData();
      log.info("Image picked: %s", uri);

      // If we can query for with/height, that can save us loading the image twice. Not
      // all content providers support it, though.
      int width = 0;
      int height = 0;
      Cursor cursor = null;
      try {
        cursor =
            mActivity
                .getContentResolver()
                .query(
                    uri,
                    new String[] {MediaStore.MediaColumns.WIDTH, MediaStore.MediaColumns.HEIGHT},
                    null,
                    null,
                    null);
        if (cursor.moveToFirst()) {
          width = cursor.getInt(0);
          height = cursor.getInt(1);
          log.info("Got image size: %dx%d", width, height);
        }
      } catch (Exception e) {
        // There can be various exceptions, all of which result in us ignoring width/height.
        log.info("Could not get image size: %s", e.getMessage());
        width = height = 0;
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }

      try {
        mImageHelper =
            new ImageHelper(mActivity.getContentResolver().openInputStream(uri), width, height);
      } catch (FileNotFoundException e) {
      }

      return true;
    }
    return false;
  }
  @Override
  public void onAttach(final Activity activity) {
    super.onAttach(activity);

    this.activity = (AbstractWalletActivity) activity;
    this.application = (WalletApplication) activity.getApplication();
    this.resolver = activity.getContentResolver();
    this.loaderManager = getLoaderManager();
  }
Ejemplo n.º 24
0
 @Override
 public void onActivityCreated(Bundle savedInstanceState) {
   super.onActivityCreated(savedInstanceState);
   mWaveView = ((GlowPadView) mActivity.findViewById(R.id.lock_target));
   mWaveView.setOnTriggerListener(this);
   initializeView(
       Settings.System.getString(
           mActivity.getContentResolver(), Settings.System.LOCKSCREEN_TARGETS));
 }
    @JavascriptInterface
    public void onSaveActivity(int status, String activityData) {
      Log.d(
          "Enter activity data",
          "save activity, status: " + status + ", activity: " + activityData);

      if (savedState != null) {
        savedState.putString("activity", activityData);
      } else {
        if (status < 0) {
          Toast.makeText(ctx, R.string.activity_not_modified, Toast.LENGTH_LONG).show();
        } else if (status > 0) {
          try {
            JSONObject activity = new JSONObject(activityData);

            ContentValues values = Mapper.mapActivity(activity);
            values.put(
                FieldCaptureContent.SYNC_STATUS, FieldCaptureContent.SYNC_STATUS_NEEDS_UPDATE);

            Uri uri = FieldCaptureContent.activityUri(activityId);

            ctx.getContentResolver()
                .update(
                    uri, values, FieldCaptureContent.ACTIVITY_ID + "=?", new String[] {activityId});

            if (newSite != null) {
              ctx.getContentResolver()
                  .insert(
                      FieldCaptureContent.siteUri(newSite.getAsString(FieldCaptureContent.SITE_ID)),
                      newSite);
            }

            FieldCaptureContent.requestSync(ctx, true);

            ctx.finish();
          } catch (Exception e) {
            Log.e("EnterActivityData", "Failed to save activity: " + activityData, e);
          }
        } else {
          Toast.makeText(ctx, R.string.activity_validation_failed, Toast.LENGTH_LONG).show();
        }
      }
    }
Ejemplo n.º 26
0
 /** getScreenBrightness */
 public static int getScreenBrightness(Activity activity) {
   int nowBrightnessValue = 0;
   ContentResolver resolver = activity.getContentResolver();
   try {
     nowBrightnessValue =
         android.provider.Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return nowBrightnessValue;
 }
Ejemplo n.º 27
0
 public SendToDocs(
     Activity activity,
     AuthManager trixAuth,
     AuthManager docListAuth,
     String[] collectionsToSend) {
   this.activity = activity;
   this.trixAuth = trixAuth;
   this.docListAuth = docListAuth;
   this.collectionsToSend = collectionsToSend;
   this.cr = activity.getContentResolver();
 }
Ejemplo n.º 28
0
  private static Cursor getCursorForKouChatImageFromExternalStorage(final Activity activity) {
    final ContentResolver contentResolver = activity.getContentResolver();

    final Uri from = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    final String where = MediaStore.Images.Media.DISPLAY_NAME + " = ?";
    final String[] whereArguments = {KOUCHAT_FILE};
    final String orderBy = MediaStore.Images.Media._ID + " ASC LIMIT 1";

    // SELECT * FROM images WHERE (_display_name = ?) ORDER BY _id ASC LIMIT 1
    return contentResolver.query(from, null, where, whereArguments, orderBy);
  }
Ejemplo n.º 29
0
 public static String getRealPathFromURI(Activity activity, Uri contentUri) {
   String res = null;
   String[] proj = {MediaStore.Images.Media.DATA};
   Cursor cursor = activity.getContentResolver().query(contentUri, proj, null, null, null);
   if (cursor.moveToFirst()) {;
     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
     res = cursor.getString(column_index);
   }
   cursor.close();
   return res;
 }
Ejemplo n.º 30
-1
  /**
   * 获得选中相册的图片
   *
   * @param mContext 上下文
   * @param data onActivityResult返回的Intent
   * @return
   */
  public static Bitmap getChoosedImage(Activity mContext, Intent data) {
    if (data == null) {
      return null;
    }

    Bitmap bm = null;

    // 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
    ContentResolver resolver = mContext.getContentResolver();

    // 此处的用于判断接收的Activity是不是你想要的那个
    try {
      Uri originalUri = data.getData(); // 获得图片的uri
      bm = MediaStore.Images.Media.getBitmap(resolver, originalUri); // 显得到bitmap图片
      // 这里开始的第二部分,获取图片的路径:
      String[] proj = {MediaStore.Images.Media.DATA};
      // 好像是android多媒体数据库的封装接口,具体的看Android文档
      Cursor cursor = mContext.managedQuery(originalUri, proj, null, null, null);
      // 按我个人理解 这个是获得用户选择的图片的索引值
      int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
      // 将光标移至开头 ,这个很重要,不小心很容易引起越界
      cursor.moveToFirst();
      // 最后根据索引值获取图片路径
      String path = cursor.getString(column_index);
      // 不用了关闭游标
      cursor.close();
    } catch (Exception e) {
      Log.e("ToolPhone", e.getMessage());
    }

    return bm;
  }