Android常用代码片段

DP与PX转换

/**
 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
 */
public static int dp2px(float dpValue) {
    final float scale = Resources.getSystem().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}

/**
 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
 */
public static int px2dp(float pxValue) {
    final float scale = Resources.getSystem().getDisplayMetrics().density;
    return (int) (pxValue / scale + 0.5f);
}

状态栏高度

/**
 * @return 读取系统的状态栏高度,如果读取错误则取24dp
 */
private static int getStatusBarHeight() {
    try {
        int result = dp2px(24);
        int resourceId = getApplication()
                .getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getApplication()
                    .getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    } catch (Throwable t) {
        return dp2px(24);
    }
}

导航栏高度

/**
 * @return 读取系统的导航栏高度(如果不存在返回0)
 */
public static int getNavigationBarHeight() {
    try {
        int result = 0;
        int resourceId = getApplication()
                .getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getApplication()
                    .getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    } catch (Throwable t) {
        return 0;
    }
}

Launcher添加Icon

// 权限申请
// <uses-permission android:name=
// "com.android.launcher.permission.INSTALL_SHORTCUT" />
Intent intent = new Intent();
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "测试");
Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.faces);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
Intent openIntent = new Intent(this, MainActivity.class);
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, openIntent);
sendBroadcast(intent);

返回桌面

Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);

安装APK

// 7.0之前安装代码
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(new File(apkPath)), "application/vnd.android.package-archive");
context.startActivity(intent);

// 7.0之后需要配置FileProvider
Intent intent = new Intent(Intent.ACTION_VIEW);
File file = new File(apkPath);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri apkUri = FileProvider.getUriForFile(context, "com.example.test", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
context.startActivity(intent);

获取简体名称

/**
 * @return 获得简体应用名
 */
public static String getAppName(Context context) {
    String name = "";
    ApplicationInfo applicationInfo = context.getApplicationInfo();
    int stringId = applicationInfo.labelRes;
    Resources resources = context.getResources();
    try {
        Locale locale = resources.getConfiguration().locale;
        resources.getConfiguration().locale = Locale.SIMPLIFIED_CHINESE;
        resources.updateConfiguration(resources.getConfiguration(), resources.getDisplayMetrics());
        name = resources.getString(stringId);
        resources.getConfiguration().locale = locale;
        resources.updateConfiguration(resources.getConfiguration(), resources.getDisplayMetrics());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return name;
}

打开设置权限页面

Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.fromParts("package", getPackageName(), null));
startActivity(intent);

Android图片变灰

public Bitmap getGray(Bitmap source) {
    int width, height;
    height = source.getHeight();
    width = source.getWidth();

    Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    Canvas c = new Canvas(bmpGrayscale);
    Paint paint = new Paint();
    ColorMatrix cm = new ColorMatrix();
    cm.setSaturation(0);
    ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
    paint.setColorFilter(f);
    c.drawBitmap(source, 0, 0, paint);

    if(source!=null && source!=bmpGrayscale){
        source.recycle();
    }
    return bmpGrayscale;
}

插入新照片到相册

   /**
     * 插入新照片到媒体相册
     */
public static void addImageToGallery(Context context, String filepath) {
    final ContentValues values = new ContentValues(2);
    values.put(MediaStore.Video.Media.MIME_TYPE, "image/" + BitmapUtil.getImageType(filepath));
    values.put(MediaStore.Video.Media.DATA, filepath);
    context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
           Uri.parse("file://" + filepath)));
}

猜你喜欢

转载自blog.csdn.net/xingzhong128/article/details/79774137