通过Intent拍摄照片

时间:2019-04-04 13:40:56

标签: java android

我正在尝试制作here的“拍照”教程,按照所有步骤操作后,我仍然遇到错误。更确切地说,在我拍摄照片后,它显示消息“相机已停止”。我添加了一个按钮,可在单击时打开相机,并添加了imageView来显示照片。我正在尝试在Samsung Galaxy S7(Android 8.0.0,API 26)上部署该应用程序。

这是setOnClickListener:

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

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

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            button.setEnabled(false);
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dispatchTakePictureIntent();

            }
        });
    }

这是相机的方法:

private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File imageView = null;
            try {
                imageView = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
            }
            // Continue only if the File was successfully created
            if (imageView != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.camapp.fileprovider",
                        imageView);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

文件路径:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
        <external-path
            name="my_images"
            path="Android/data/com.example.camapp/files/Pictures" />
</paths>

权限:

<uses-feature android:name="android.hardware.camera"
        android:required="true" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

提供者:

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.camapp.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>

我对tutorial中的onActivityResult()createImageFile()和galleryAddPic()具有相同的方法。

这是堆栈跟踪:

java.lang.IllegalStateException: @NotNull method com/android/tools/idea/gradle/project/model/AndroidModuleModel.getRootDir must not return null
    at com.android.tools.idea.gradle.project.model.AndroidModuleModel.$$$reportNull$$$0(AndroidModuleModel.java)
    at com.android.tools.idea.gradle.project.model.AndroidModuleModel.getRootDir(AndroidModuleModel.java:571)
    at com.android.tools.idea.gradle.project.sync.setup.module.android.ContentRootsModuleSetupStep.findContentEntries(ContentRootsModuleSetupStep.java:71)
    at com.android.tools.idea.gradle.project.sync.setup.module.android.ContentRootsModuleSetupStep.doSetUpModule(ContentRootsModuleSetupStep.java:58)
    at com.android.tools.idea.gradle.project.sync.setup.module.android.ContentRootsModuleSetupStep.doSetUpModule(ContentRootsModuleSetupStep.java:41)
    at com.android.tools.idea.gradle.project.sync.setup.module.ModuleSetupStep.setUpModule(ModuleSetupStep.java:35)
    at com.android.tools.idea.gradle.project.sync.setup.module.common.BaseSetup.setUpModule(BaseSetup.java:41)
    at com.android.tools.idea.gradle.project.sync.ng.ModuleSetup.setupModuleModels(ModuleSetup.java:141)
    at com.android.tools.idea.gradle.project.sync.ng.CachedProjectModelsSetup.setUpModules(CachedProjectModelsSetup.java:116)
    at com.android.tools.idea.gradle.project.sync.ng.ProjectSetup$ProjectSetupImpl.setUpProject(ProjectSetup.java:82)
    at com.android.tools.idea.gradle.project.sync.ng.SyncResultHandler.onSyncSkipped(SyncResultHandler.java:164)
    at com.android.tools.idea.gradle.project.sync.ng.NewGradleSync.trySyncWithCachedGradleModels(NewGradleSync.java:219)
    at com.android.tools.idea.gradle.project.sync.ng.NewGradleSync.sync(NewGradleSync.java:165)
    at com.android.tools.idea.gradle.project.sync.ng.NewGradleSync.access$000(NewGradleSync.java:59)
    at com.android.tools.idea.gradle.project.sync.ng.NewGradleSync$2.run(NewGradleSync.java:151)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:736)
    at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$1(CoreProgressManager.java:157)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:580)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:525)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:85)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:144)
    at com.intellij.openapi.progress.impl.CoreProgressManager$4.run(CoreProgressManager.java:395)
    at com.intellij.openapi.application.impl.ApplicationImpl$1.run(ApplicationImpl.java:314)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

我想创建一个打开相机的按钮来拍摄照片并将其保存在图库或其他指定目录中,因为我将对该照片进行一些图像处理。我尝试了所有关于yt的教程,而我确实有一个很难找到解决这个问题的方法。对于您有任何解决方案或建议,我们深表感谢。感谢您的宝贵时间!

1 个答案:

答案 0 :(得分:1)

如果您的应用需要相机单击图片,则应询问CAMERA权限

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app">

<uses-permission android:name="android.permission.CAMERA"/>
<!-- other permissions go here -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application ...>
    ...
</application>

然后您的应用应提示用户授予相机和存储权限

if (ContextCompat.checkSelfPermission(YourActivityName.this,
    Manifest.permission.CAMERA)
    != PackageManager.PERMISSION_GRANTED) {

    ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
            YOUR_PERMISSIONS_REQUEST_CODE);

    // YOUR_PERMISSIONS_REQUEST_CODE is an
    // app-defined int constant. The callback method gets the
    // result of the request.

} else {
// Permission has already been granted
}

还要在清单文件中定义文件提供程序

 <provider
 android:name="android.support.v4.content.FileProvider"
 android:authorities="com.yourPackageName.fileprovider"
 android:exported="false"
 android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/file_list"></meta-data>
</provider>