簡體   English   中英

相機應用程序在 Marshmallow API 23 中運行良好,但是在 API 中拍攝大於 23 的相機時崩潰

[英]Camera app working fine in Marshmallow API 23, but while taking camera in API grater than 23 is crashing

我創建了一個簡單的應用程序來拍攝照片,該應用程序將存儲在 SD 卡的SURVEYASSIST文件夾中。 它在我的移動 Redmi 3s prime(Android 版本 Marshmallow 6.0.1)中運行良好,但是當我在 Redmi Note 5 pro(Oreo 8.1.0)中打開應用程序並單擊相機按鈕時,應用程序崩潰了。 如圖所示,附加了錯誤代碼。

錯誤代碼截圖

public class MainActivity extends AppCompatActivity {

    public static final int CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE = 1777;
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final String Demo_ImagePath ="/storage/emulated/0/SURVEYASSIST/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                String imgcurTime = dateFormat.format(new Date());
                String _path = Demo_ImagePath + File.separator + imgcurTime + ".jpg";
                File file = new File(_path);

                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE);
            }
        });
    }
}

FileUriExposedException是被拋出的。 文檔

當應用程序向另一個應用程序公開 file:// Uri 時引發的異常。

這里有一篇關於如何解決這個問題的好文章,但我會總結一下,以防鏈接在某個時候失效:

  1. 將此添加到您的清單中:

     <manifest...> <application...> <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/> </provider> </application>

  2. 創建 XML 文件 res/xml/provider_paths.xml

     <?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="external_files" path="."/> </paths>
  3. 更改您的代碼:來自:

     intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));

    至:

     Uri apkURI = FileProvider.getUriForFile( this, this.getApplicationContext().getPackageName() + ".provider", file); intent.setDataAndType(apkURI, "image/*"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

暫無
暫無

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

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