Java Code Examples for android.app.Activity#getContentResolver()

The following examples show how to use android.app.Activity#getContentResolver() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PhotoMetadataUtils.java    From Matisse with Apache License 2.0 6 votes vote down vote up
public static Point getBitmapSize(Uri uri, Activity activity) {
    ContentResolver resolver = activity.getContentResolver();
    Point imageSize = getBitmapBound(resolver, uri);
    int w = imageSize.x;
    int h = imageSize.y;
    if (PhotoMetadataUtils.shouldRotate(resolver, uri)) {
        w = imageSize.y;
        h = imageSize.x;
    }
    if (h == 0) return new Point(MAX_WIDTH, MAX_WIDTH);
    DisplayMetrics metrics = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
    float screenWidth = (float) metrics.widthPixels;
    float screenHeight = (float) metrics.heightPixels;
    float widthScale = screenWidth / w;
    float heightScale = screenHeight / h;
    if (widthScale > heightScale) {
        return new Point((int) (w * widthScale), (int) (h * heightScale));
    }
    return new Point((int) (w * widthScale), (int) (h * heightScale));
}
 
Example 2
Source File: OnboardingManager.java    From zom-android-matrix with Apache License 2.0 6 votes vote down vote up
/**
private final static String PASSWORD_LETTERS = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789+@!#";
private final static int PASSWORD_LENGTH = 12;

public static String generatePassword()
{
    // Pick from some letters that won't be easily mistaken for each
    // other. So, for example, omit o O and 0, 1 l and L.
    SecureRandom random = new SecureRandom();

    StringBuffer pw = new StringBuffer();
    for (int i=0; i<PASSWORD_LENGTH; i++)
    {
        int index = (int)(random.nextDouble()*PASSWORD_LETTERS.length());
        pw.append(PASSWORD_LETTERS.substring(index, index+1));
    }
    return pw.toString();
}**/



public static boolean changeLocalPassword (Activity context, long providerId, long accountId, String password)
{
    try {
        final ContentResolver cr = context.getContentResolver();
        ImPluginHelper helper = ImPluginHelper.getInstance(context);
        ImApp.insertOrUpdateAccount(cr, providerId, accountId, null, null, password);

        /**
        XmppConnection xmppConn = new XmppConnection(context);
        xmppConn.initUser(providerId, accountId);
        boolean success = xmppConn.changeServerPassword(providerId, accountId, oldPassword, newPassword);
        **/
        return false;

        //return success;
    }
    catch (Exception e)
    {
        return false;
    }
}
 
Example 3
Source File: ImageUtils.java    From monolog-android with MIT License 6 votes vote down vote up
/**
 * 获取图片缩略�? 只有Android2.1以上版本支持
 *
 * @param imgName
 * @param kind    MediaStore.Images.Thumbnails.MICRO_KIND
 * @return
 */
@SuppressWarnings("deprecation")
public static Bitmap loadImgThumbnail(Activity context, String imgName,
                                      int kind) {
    Bitmap bitmap = null;

    String[] proj = {MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DISPLAY_NAME};

    Cursor cursor = context.managedQuery(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
            MediaStore.Images.Media.DISPLAY_NAME + "='" + imgName + "'",
            null, null);

    if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
        ContentResolver crThumb = context.getContentResolver();
        Options options = new Options();
        options.inSampleSize = 1;
        bitmap = getThumbnail(crThumb, cursor.getInt(0),
                kind, options);
    }
    return bitmap;
}
 
Example 4
Source File: ImageUtils.java    From wakao-app with MIT License 6 votes vote down vote up
/**
 * 获取图片缩略图 只有Android2.1以上版本支持
 * 
 * @param imgName
 * @param kind
 *            MediaStore.Images.Thumbnails.MICRO_KIND
 * @return
 */
public static Bitmap loadImgThumbnail(Activity context, String imgName,
		int kind) {
	Bitmap bitmap = null;

	String[] proj = { MediaStore.Images.Media._ID,
			MediaStore.Images.Media.DISPLAY_NAME };

	Cursor cursor = context.managedQuery(
			MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
			MediaStore.Images.Media.DISPLAY_NAME + "='" + imgName + "'",
			null, null);

	if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
		ContentResolver crThumb = context.getContentResolver();
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 1;
		bitmap = MethodsCompat.getThumbnail(crThumb, cursor.getInt(0),
				kind, options);
	}
	return bitmap;
}
 
Example 5
Source File: PhotoMetadataUtils.java    From AlbumCameraRecorder with MIT License 6 votes vote down vote up
/**
     * @param uri      图片uri
     * @param activity 界面
     * @return xy
     */
    public static Point getBitmapSize(Uri uri, Activity activity) {
        ContentResolver resolver = activity.getContentResolver(); // ContentResolver共享数据库
        Point imageSize = getBitmapBound(resolver, uri);
        int w = imageSize.x;
        int h = imageSize.y;
        // 判断图片是否旋转了
        if (PhotoMetadataUtils.shouldRotate(resolver, uri)) {
            w = imageSize.y;
            h = imageSize.x;
        }
        if (h == 0) return new Point(MAX_WIDTH, MAX_WIDTH);
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        // 获取屏幕的宽度高度
        float screenWidth = (float) metrics.widthPixels;
        float screenHeight = (float) metrics.heightPixels;
        // 屏幕宽度 / 图片宽度 = ??
        float widthScale = screenWidth / w;
        float heightScale = screenHeight / h;
//        if (widthScale > heightScale) {
//            return new Point((int) (w * widthScale), (int) (h * heightScale));
//        }
        // ?? * 宽度
        return new Point((int) (w * widthScale), (int) (h * heightScale));
    }
 
Example 6
Source File: DeviceContactMatcher.java    From buddycloud-android with Apache License 2.0 5 votes vote down vote up
@Override
public void match(Activity activity, ModelCallback<JSONArray> callback) {
	ContentResolver contentResolver = activity.getContentResolver();
	JSONArray myHashes = getMyHashes(contentResolver);
	JSONArray friendHashes = getOtherHashes(contentResolver);
	ContactMatcherUtils.reportToFriendFinder(activity, callback, friendHashes, myHashes);
}
 
Example 7
Source File: MediaObserver.java    From Gallery-example with GNU General Public License v3.0 5 votes vote down vote up
static void initContentObserver(Activity activity) {

        Uri externalImagesUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        Uri internalImagesUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
        Uri externalVideosUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        Uri internalVideosUri = MediaStore.Video.Media.INTERNAL_CONTENT_URI;

        ContentResolver contentResolver = activity.getContentResolver();

        contentResolver.
                registerContentObserver(
                        externalImagesUri,
                        true,
                        new MediaObserver(new Handler(), activity));

        contentResolver.
                registerContentObserver(
                        internalImagesUri,
                        true,
                        new MediaObserver(new Handler(), activity));

        contentResolver.
                registerContentObserver(
                        externalVideosUri,
                        true,
                        new MediaObserver(new Handler(), activity));

        contentResolver.
                registerContentObserver(
                        internalVideosUri,
                        true,
                        new MediaObserver(new Handler(), activity));
    }
 
Example 8
Source File: Launcher.java    From LaunchEnr with GNU General Public License v3.0 5 votes vote down vote up
static void initContentObserver(Activity activity) {

            Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;

            ContentResolver contentResolver = activity.getContentResolver();

            contentResolver.
                    registerContentObserver(
                            contactsUri,
                            true,
                            new ContactsObserver(new Handler(), activity));
        }
 
Example 9
Source File: PermissionsChecker.java    From permissions4m with Apache License 2.0 5 votes vote down vote up
/**
 * write or delete call log, {@link android.Manifest.permission#WRITE_CALL_LOG}
 *
 * @param activity
 * @return true if success
 */
private static boolean checkWriteCallLog(Activity activity) throws Exception {
    ContentResolver contentResolver = activity.getContentResolver();
    ContentValues content = new ContentValues();
    content.put(CallLog.Calls.TYPE, CallLog.Calls.INCOMING_TYPE);
    content.put(CallLog.Calls.NUMBER, TAG_NUMBER);
    content.put(CallLog.Calls.DATE, 20140808);
    content.put(CallLog.Calls.NEW, "0");
    contentResolver.insert(Uri.parse("content://call_log/calls"), content);

    contentResolver.delete(Uri.parse("content://call_log/calls"), "number = ?", new
            String[]{TAG_NUMBER});

    return true;
}
 
Example 10
Source File: ScreenUtil.java    From Aria with Apache License 2.0 5 votes vote down vote up
/**
 * 获取屏幕的亮度
 */
public float getScreenBrightness(Activity activity) {
  int nowBrightnessValue = 0;
  ContentResolver resolver = activity.getContentResolver();
  try {
    nowBrightnessValue = Settings.System.getInt(
        resolver, Settings.System.SCREEN_BRIGHTNESS);
  } catch (Exception e) {
    e.printStackTrace();
  }
  return nowBrightnessValue;
}
 
Example 11
Source File: loveviayou.java    From styT with Apache License 2.0 5 votes vote down vote up
public static InputStream GetISfromIntent(Intent u, Activity con) {
    ContentResolver cr = con.getContentResolver();
    try {
        return cr.openInputStream(u.getData());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    }

}
 
Example 12
Source File: TalkBackDeveloperPreferencesActivity.java    From talkback with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the preferences state to match the actual state of touch exploration. This is called
 * once when the preferences activity launches and again whenever the actual state of touch
 * exploration changes.
 */
private void updateTouchExplorationDisplay() {
  TwoStatePreference prefTouchExploration =
      (TwoStatePreference)
          findPreference(getString(R.string.pref_explore_by_touch_reflect_key));
  if (prefTouchExploration == null) {
    return;
  }

  Activity activity = getActivity();
  if (activity == null) {
    return;
  }

  ContentResolver resolver = activity.getContentResolver();
  Resources res = getResources();
  SharedPreferences prefs = SharedPreferencesUtils.getSharedPreferences(activity);

  boolean requestedState =
      SharedPreferencesUtils.getBooleanPref(
          prefs, res, R.string.pref_explore_by_touch_key, R.bool.pref_explore_by_touch_default);
  boolean reflectedState = prefTouchExploration.isChecked();
  boolean actualState =
      TalkBackService.isServiceActive() ? isTouchExplorationEnabled(resolver) : requestedState;

  // If touch exploration is actually off and we requested it on, the user
  // must have declined the "Enable touch exploration" dialog. Update the
  // requested value to reflect this.
  if (requestedState != actualState) {
    LogUtils.d(TAG, "Set touch exploration preference to reflect actual state %b", actualState);
    SharedPreferencesUtils.putBooleanPref(
        prefs, res, R.string.pref_explore_by_touch_key, actualState);
  }

  // Ensure that the check box preference reflects the requested state,
  // which was just synchronized to match the actual state.
  if (reflectedState != actualState) {
    prefTouchExploration.setChecked(actualState);
  }
}
 
Example 13
Source File: ScreenUtils.java    From LLApp with Apache License 2.0 5 votes vote down vote up
/**
 * 获取当前屏幕亮度
 *
 * @param activity
 * @return
 */
public static int getScreenBrightness(Activity activity) {
    int value = 0;
    ContentResolver cr = activity.getContentResolver();
    try {
        value = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS);
    } catch (Settings.SettingNotFoundException e) {

    }
    return value;
}
 
Example 14
Source File: SystemUtil.java    From KeyboardView with Apache License 2.0 5 votes vote down vote up
/**
 * 设置亮度(每30递增)
 *
 * @param activity
 */
public static void setBrightness(Activity activity) {
    ContentResolver resolver = activity.getContentResolver();
    Uri uri = Settings.System.getUriFor("screen_brightness");
    int nowScreenBri = getScreenBrightness(activity);
    nowScreenBri = nowScreenBri <= 225 ? nowScreenBri + 30 : 30;
    System.out.println("nowScreenBri==" + nowScreenBri);
    Settings.System.putInt(resolver, "screen_brightness", nowScreenBri);
    resolver.notifyChange(uri, null);
}
 
Example 15
Source File: DisableSecurityCheck.java    From MIUIAnesthetist with MIT License 5 votes vote down vote up
private void callPreference(XC_MethodHook.MethodHookParam param, String key, boolean value){
    Activity activity = (Activity) param.thisObject;
    ContentResolver contentResolver = activity.getContentResolver();
    Bundle bundle = new Bundle();
    bundle.putInt("type", 1);
    bundle.putString("key", key);
    bundle.putBoolean("value", value);
    remoteChange("SET", bundle,contentResolver);
    contentResolver.notifyChange(Uri.withAppendedPath(Uri.parse("content://com.miui.securitycenter.remoteprovider"), key), null, false);
}
 
Example 16
Source File: AccountAdapter.java    From Zom-Android-XMPP with GNU General Public License v3.0 4 votes vote down vote up
private void runBindTask( final Activity context, final List<AccountInfo> accountInfoList ) {
    final Resources resources = context.getResources();
    final ContentResolver resolver = context.getContentResolver();
    final ImApp mApp = (ImApp)context.getApplication();

    // if called multiple times
    if (mBindTask != null)
        mBindTask.cancel(false);
    //


    mBindTask = new AsyncTask<Void, Void, List<AccountSetting>>() {

        @Override
        protected List<AccountSetting> doInBackground(Void... params) {
            List<AccountSetting> accountSettingList = new ArrayList<AccountSetting>();
            for( AccountInfo ai : accountInfoList ) {
                accountSettingList.add( getAccountSettings(ai) );
            }
            return accountSettingList;
        }

        private AccountSetting getAccountSettings(AccountInfo ai) {
            AccountSetting as = new AccountSetting();


            Cursor pCursor = resolver.query(Imps.ProviderSettings.CONTENT_URI,new String[] {Imps.ProviderSettings.NAME, Imps.ProviderSettings.VALUE},Imps.ProviderSettings.PROVIDER + "=?",new String[] { Long.toString(ai.providerId)},null);

            if (pCursor != null)
            {
                Imps.ProviderSettings.QueryMap settings =
                        new Imps.ProviderSettings.QueryMap(pCursor, resolver, ai.providerId, false , null);

                as.connectionStatus = ai.dbConnectionStatus;
                as.activeUserName = ai.activeUserName;
                as.domain = settings.getDomain();
                as.host = settings.getServer();
                as.port = settings.getPort();

                /**
                IImConnection conn = mApp.getConnection(ai.providerId,settings.get);
                if (conn == null) {
                    as.connectionStatus = ImConnection.DISCONNECTED;
                } else {
                    try {
                        as.connectionStatus = conn.getState();
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }*/

                settings.close();
            }
            return as;
        }

        @Override
        protected void onPostExecute(List<AccountSetting> result) {
            // store
            mBindTask = null;
            // swap
            AccountAdapter.super.swapCursor(mStashCursor);
            if (mListener != null)
                mListener.onPopulate();
        }
    };
    mBindTask.execute();
}
 
Example 17
Source File: PBitmapUtils.java    From YImagePicker with Apache License 2.0 4 votes vote down vote up
public static String getMimeTypeFromUri(Activity context, Uri uri) {
    ContentResolver resolver = context.getContentResolver();
    return resolver.getType(uri);
}
 
Example 18
Source File: loveviayou.java    From stynico with MIT License 4 votes vote down vote up
public static void Modi_WangYi_Mp3_UI_doing(Activity con, int requestCode, int resultCode, Intent in)
{
	if (requestCode == requestcode && resultCode == Activity.RESULT_OK)
	{
		Uri uri = in.getData();
		ContentResolver cr = con.getContentResolver();  
		try
		{
			Bitmap bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
			File[] files = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/netease/cloudmusic/Ad/").listFiles();
			if (files == null)
			{
				Toast.makeText(con, "没安装网易音乐或者是没有加载广告", Toast.LENGTH_LONG).show();
				return;
			}
			Vector<String> c=new Vector<String>();
			for (File f : files) 
			{
				if (f.isDirectory())
				{
					File[] temp_files=f.listFiles();
					if (temp_files == null) continue;
					for (File inner_f : temp_files)
					{

						if (inner_f.isFile())
							c.add(inner_f.getAbsolutePath());
					}
				}
				if (f.isFile())
					c.add(f.getAbsolutePath());
			}
			for (String s : c)
			{
				OutputStream ops=new FileOutputStream(s);
				bmp.compress(Bitmap.CompressFormat.JPEG, 100, ops);
			}


		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}  
		Toast.makeText(con, "替换完成", Toast.LENGTH_SHORT).show();
		//finish();
	}
}
 
Example 19
Source File: MainFragment.java    From continuous-audiorecorder with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Creates new item in the system's media database.
 *
 * @see <a href="https://github.com/android/platform_packages_apps_soundrecorder/blob/master/src/com/android/soundrecorder/SoundRecorder.java">Android Recorder source</a>
 */
public Uri saveCurrentRecordToMediaDB(final String fileName) {
    if (mAudioRecordUri != null) return mAudioRecordUri;

    final Activity activity = getActivity();
    final Resources res = activity.getResources();
    final ContentValues cv = new ContentValues();
    final File file = new File(fileName);
    final long current = System.currentTimeMillis();
    final long modDate = file.lastModified();
    final Date date = new Date(current);
    final String dateTemplate = res.getString(R.string.audio_db_title_format);
    final SimpleDateFormat formatter = new SimpleDateFormat(dateTemplate, Locale.getDefault());
    final String title = formatter.format(date);
    final long sampleLengthMillis = 1;
    // Lets label the recorded audio file as NON-MUSIC so that the file
    // won't be displayed automatically, except for in the playlist.
    cv.put(MediaStore.Audio.Media.IS_MUSIC, "0");

    cv.put(MediaStore.Audio.Media.TITLE, title);
    cv.put(MediaStore.Audio.Media.DATA, file.getAbsolutePath());
    cv.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
    cv.put(MediaStore.Audio.Media.DATE_MODIFIED, (int) (modDate / 1000));
    cv.put(MediaStore.Audio.Media.DURATION, sampleLengthMillis);
    cv.put(MediaStore.Audio.Media.MIME_TYPE, "audio/*");
    cv.put(MediaStore.Audio.Media.ARTIST, res.getString(R.string.audio_db_artist_name));
    cv.put(MediaStore.Audio.Media.ALBUM, res.getString(R.string.audio_db_album_name));

    Log.d(TAG, "Inserting audio record: " + cv.toString());

    final ContentResolver resolver = activity.getContentResolver();
    final Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Log.d(TAG, "ContentURI: " + base);

    mAudioRecordUri = resolver.insert(base, cv);
    if (mAudioRecordUri == null) {
        return null;
    }
    activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, mAudioRecordUri));
    return mAudioRecordUri;
}
 
Example 20
Source File: Launcher.java    From LaunchEnr with GNU General Public License v3.0 3 votes vote down vote up
static void removeContentObserver(Activity activity) {

            ContentResolver contentResolver = activity.getContentResolver();

            contentResolver.unregisterContentObserver(new ContactsObserver(new Handler(), activity));

        }