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

版權聲明:本文爲xing_star原創文章,轉載請註明出處!html

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

最近線上報錯,有個用戶連續crash了10次左右,查看了下堆棧信息,發現是提示com.android.camera.action.CROP這個Intent找不到,報了ActivityNotFound的錯誤。根據經驗得出結論,這個用戶的設備上,確定是去掉了支持Crop的應用,因此直接作Intent隱私跳轉到這會crash,思考了下,解決思路是在跳轉前作檢測,或者是全局作檢測。android

全局檢測的方式:測試

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是支持的,也是一種辦法this

第二種就是在跳轉前檢測:url

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);
}

 

我修改後的檢測代碼以下:spa

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()) != nullcode

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

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

相關文章
相關標籤/搜索