[英]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 时引发的异常。
这里有一篇关于如何解决这个问题的好文章,但我会总结一下,以防链接在某个时候失效:
将此添加到您的清单中:
<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>
创建 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>
更改您的代码:来自:
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.