簡體   English   中英

啟動相機導致Android崩潰

[英]launch Camera causing crash Android

我遵循了這個簡單的應用程序AndroidScannerDemo ,它有兩個主要按鈕打開相機和打開畫廊。 相機在我的手機 API 19 上運行良好,但是當我嘗試在其他設備或模擬器上啟動相機時,應用程序崩潰。

據我所知,這可能是由於許可

編輯:顯然這也是前一段時間在這里過的,但問題仍然存在

錯誤更新來自createImageFile方法的根本問題

我嘗試改變//cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempFileUri);

cameraIntent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, preference);

我可以啟動相機,但拍照后立即崩潰

更新 2 :我正在嘗試按照本文提供的答案在我使用片段的唯一問題下方

那么如何更改這一行tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(), "com.scanlibrary.provider", // As defined in Manifest file);

tempFileUri = FileProvider.getUriForFile(PickImageFragment.this, getString(R.string.file_provider_authority), file); 在一個片段里面!

錯誤的第一個參數 PickImageFragment

編輯:更改了 PickImageFragment 內的 openCamera() 方法

我錯過了什么?

堆棧跟蹤

2019-11-29 23:45:05.750 27993-27993/com.nabeeltech.capturedoc E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nabeeltech.capturedoc, PID: 27993
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nabeeltech.capturedoc/com.scanlibrary.ScanActivity}: java.lang.SecurityException: UID 10091 does not have permission to content://com.scanlibrary.provider/external_files/scanSample/IMG_20191129_224505.jpg [user 0]
 Caused by: java.lang.SecurityException: UID 10091 does not have permission to content://com.scanlibrary.provider/external_files/scanSample/IMG_20191129_224505.jpg [user 0]
    at com.scanlibrary.PickImageFragment.openCamera(PickImageFragment.java:131)
    at com.scanlibrary.PickImageFragment.handleIntentPreference(PickImageFragment.java:79)
    at com.scanlibrary.PickImageFragment.init(PickImageFragment.java:60)
    at com.scanlibrary.PickImageFragment.onCreateView(PickImageFragment.java:50)

選擇圖像片段

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.pick_image_fragment, null);
    init();
    return view;
}

private void init() {
    cameraButton = (ImageButton) view.findViewById(R.id.cameraButton);
    cameraButton.setOnClickListener(new CameraButtonClickListener());
    galleryButton = (ImageButton)
 view.findViewById(R.id.selectButton);
    galleryButton.setOnClickListener(new GalleryClickListener());
    if (isIntentPreferenceSet()) {
        handleIntentPreference();
    } else {
        getActivity().finish();
    }
}

private void handleIntentPreference() {
    int preference = getIntentPreference();
    if (preference == ScanConstants.OPEN_CAMERA) {
        openCamera();
    } else if (preference == ScanConstants.OPEN_MEDIA) {
        openMediaContent();
    }
}

public void openCamera() {
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    Uri tempFileUri = null;
        File file = createImageFile();
        boolean isDirectoryCreated = file.getParentFile().mkdirs();
        Log.d("", "openCamera: isDirectoryCreated: " + isDirectoryCreated);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
                "com.scanlibrary.provider", // As defined in Manifest
                file);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempFileUri);
    } else {
        tempFileUri = Uri.fromFile(file);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempFileUri);
    }
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
        cameraIntent.setClipData(ClipData.newRawUri("", tempFileUri));
        cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    }
    startActivityForResult(cameraIntent, ScanConstants.START_CAMERA_REQUEST_CODE);

private File createImageFile() {
    clearTempImages();
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
            Date());
    File file = new File(ScanConstants.IMAGE_PATH, "IMG_" + timeStamp +
            ".jpg");
    fileUri = Uri.fromFile(file);
    return file;
}

private void clearTempImages() {
    try {
        File tempFolder = new File(ScanConstants.IMAGE_PATH);
        for (File f : tempFolder.listFiles())
            f.delete();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

掃描常數

public class ScanConstants {

public final static int PICKFILE_REQUEST_CODE = 1;
public final static int START_CAMERA_REQUEST_CODE = 2;
public final static String OPEN_INTENT_PREFERENCE = "selectContent";
public final static String IMAGE_BASE_PATH_EXTRA = "ImageBasePath";
public final static int OPEN_CAMERA = 4;
public final static int OPEN_MEDIA = 5;
public final static String SCANNED_RESULT = "scannedResult";
public final static String IMAGE_PATH = Environment
        .getExternalStorageDirectory().getPath() + "/scanSample";

public final static String SELECTED_BITMAP = "selectedBitmap";
}

您已經編寫了很好的代碼Fileprovider.getUriforFile ,但是您是否聲明了所需的權限。

解決這個問題的唯一方法是向所有可能需要它的包授予權限,如下所示:

List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
    String packageName = resolveInfo.activityInfo.packageName;
    context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}

如果以上沒有解決問題,我建議參考 Lorenzo Quiroli 的這篇文章,該文章為舊版 Android 解決了這個問題。

他發現需要手動設置Intent的ClipDataClipData設置權限,像這樣:

if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP ) {
    takePictureIntent.setClipData( ClipData.newRawUri( "", photoURI ) );
    takePictureIntent.addFlags( Intent.FLAG_GRANT_WRITE_URI_PERMISSION|Intent.FLAG_GRANT_READ_URI_PERMISSION );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM