Android判断com.android.camera.action.CROP是否存在

版权声明:本文为xing_star原创文章,转载请注明出处!

本文同步自http://javaexception.com/archives/225

最近线上报错,有个用户连续crash了10次左右,查看了下堆栈信息,发现是提示com.android.camera.action.CROP这个Intent找不到,报了ActivityNotFound的错误。根据经验得出结论,这个用户的设备上,肯定是去掉了支持Crop的应用,所以直接做Intent隐私跳转到这会crash,思考了下,解决思路是在跳转前做检测,或者是全局做检测。

全局检测的方式:

public boolean isAvailable(Context context, Intent intent) { 
  PackageManager packageManager = context.getPackageManager();
List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
  return list.size() > 0;
}

经过测试,在com.android.camera.action.CROP没效果,只能放弃,但是这个对某些Intent是支持的,也是一种办法

第二种就是在跳转前检测:

private void crop(String imagePath) {
    File file = new File(FileUtils.createRootPath(this) + "/" + System.currentTimeMillis() + ".jpg");
 
    cropImagePath = file.getAbsolutePath();
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(getImageContentUri(new File(imagePath)), "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", config.aspectX);
    intent.putExtra("aspectY", config.aspectY);
    intent.putExtra("outputX", config.outputX);
    intent.putExtra("outputY", config.outputY);
    intent.putExtra("scale", true);
    intent.putExtra("scaleUpIfNeeded", true);
    intent.putExtra("return-data", false);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    intent.putExtra("noFaceDetection", true);
    startActivityForResult(intent, IMAGE_CROP_CODE);
}

 

我修改后的检测代码如下:

private boolean canCrop(String imagePath) {
    File file = new File(FileUtils.createRootPath(this) + "/" + System.currentTimeMillis() + ".jpg");
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(getImageContentUri(new File(imagePath)), "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", config.aspectX);
    intent.putExtra("aspectY", config.aspectY);
    intent.putExtra("outputX", config.outputX);
    intent.putExtra("outputY", config.outputY);
    intent.putExtra("scale", true);
    intent.putExtra("scaleUpIfNeeded", true);
    intent.putExtra("return-data", false);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    intent.putExtra("noFaceDetection", true);
    if (intent.resolveActivity(getPackageManager()) != null) {
        return true;
    } else {
        // 没有安装所需应用
        return false;
    }
}

关键代码是Intent.resolveActivity(getPackageManager()) != null

推荐一篇值得看看的文章:

https://juejin.im/entry/59a93530f265da24823642b3

 

Android判断com.android.camera.action.CROP是否存在

上一篇:SpringMVC注解@RequestMapping之produces属性导致的406错误


下一篇:EBS之实现报表的两种方式