【问题标题】:Unfortunately app has stopped, permission allow or deny after allow it works but in the begining i get pop up that my app has stopped不幸的是应用程序已停止,允许它工作后允许或拒绝,但一开始我弹出我的应用程序已停止
【发布时间】:2017-07-26 13:24:40
【问题描述】:

我正在尝试请求相机权限,但是每当我运行我的项目时,我的应用程序首先停止弹出,然后如果我单击不再显示选项,它会显示允许或拒绝选项,它不会让我按下允许。如果我允许我的应用程序运行它存在并且我必须再次打开应用程序。但问题将消失,我的应用程序将在下一次尝试中完美运行.. 这是 logcat

07-26 18:41:56.080 3003-3003/com.example.android.camerapermission E/AndroidRuntime: 致命异常: main 进程:com.example.android.camerapermission,PID:3003 java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.android.camerapermission/com.example.android.camerapermission.MainActivity}:java.lang.RuntimeException:无法连接到相机服务 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 在 android.app.ActivityThread.-wrap11(ActivityThread.java) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.java:5417) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 原因:java.lang.RuntimeException:无法连接到相机服务 在 android.hardware.Camera.(Camera.java:495) 在 android.hardware.Camera.open(Camera.java:356) 在 com.example.android.camerapermission.MainActivity.onCreate(MainActivity.java:52) 在 android.app.Activity.performCreate(Activity.java:6237) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 在 android.app.ActivityThread.-wrap11(ActivityThread.java) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.java:5417) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

这是我的 MainActivity.java

 package com.example.android.camerapermission;

import android.Manifest;
import android.content.DialogInterface;

import android.content.pm.PackageManager;
import android.hardware.Camera;

import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.test.mock.MockPackageManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import com.nispok.snackbar.Snackbar;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CAMERA = 0;


    ImageButton imageButton;
    Camera camera;
    Camera.Parameters parameters;
    boolean isflash = false;
    boolean isOn = false;


    public static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageButton = (ImageButton) findViewById(R.id.imageButton);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[] {Manifest.permission.CAMERA}, 0);
            }
        }
        if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
            ;

        {
            camera = Camera.open();
            parameters = camera.getParameters();
            isflash = true;

        }


        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (isflash) {

                    if (!isOn) {
                        imageButton.setImageResource(R.drawable.on);
                        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                        camera.setParameters(parameters);
                        camera.startPreview();
                        isOn = true;

                    } else {
                        imageButton.setImageResource(R.drawable.off);
                        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                        camera.setParameters(parameters);
                        camera.stopPreview();
                        isOn = false;
                    }


                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Error.....");
                    builder.setMessage("Flashlight is not available on this device...");
                    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            dialog.dismiss();
                            finish();
                        }
                    });

                    AlertDialog alertDialog = builder.create();
                    alertDialog.show();
                }

            }
        });


    }

    public void showCamera(View view) {

        Log.i(TAG, "Show that camera button is clicked. Checking permission.");
        /**
         * Include camera permission and
         * check if camera is available in phone or not
         */
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // Camera permission is not granted yet
            requestCameraPermission();
        } else {
            //Camera is available, show the camera preview

            Log.i(TAG, "CAMERA permission has granted, displaying camera preview");
            showCameraPreview();
        }

    }

    /**
     * Request the Camera Permission again in the case of user mistakenly denied permission.
     * Create a SnackBar that will prompt the user to grant the permission, otherwise it is requested direcly.
     */

    private void requestCameraPermission() {
        Log.i(TAG, " Camera permission is still not granted. Requesting permission.");

        //Start (camera_permission_request)
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {
            // show an additional request to the user if the permission was not granted earlier.


        } else {
            //Camera permission has not been granted yet. Request directly.
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA);
        }
        // END (camera_permission_request)
    }


    private void showCameraPreview() {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.sample_content_fragment, CameraPreviewFragment.newInstance())
                .commit();
    }


    /**
     * Receiving permission after granted
     */

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == REQUEST_CAMERA) {
            //Begin request (permission_result)
            //Recieved permission result for the camera permission.
            Log.i(TAG, "Request for Camera permission is received. ");

            //Check if the only required permission has been granted
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Camera permission is safely granted, now you can preview.
                Log.i(TAG, "Camera permission has succesfully granted, preview is being displayed");


            } else {
                Log.i(TAG, "CAMERA permission is not granted.");

                // Finish(permission_result)
            }

            super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        camera.setParameters(parameters);
        camera.stopPreview();
        isflash = false;

        if (camera != null) {
            camera.release();
            camera = null;
        }
    }
}

注意:相机权限已在 Manifest.xml 中设置。

【问题讨论】:

  • 是的。我正在我的手机上测试这个,它是 7.1.2,我正在模拟器中测试 6.0。同样的问题。
  • 我认为您必须请求读取和写入 ExternalStorage 权限才能使用相机。因为在拍摄后相机将存储图像时,您必须获得写入权限。此示例还使用写入权限(不是运行时,而是在清单中)-androidhive.info/2013/09/android-working-with-camera-api

标签: android android-camera runtime-permissions


【解决方案1】:

您需要将相机打开调用包含在 try catch 中。

try {
        c = Camera.open(); // attempt to get a Camera instance
    }
    catch (Exception e){
        // Camera is not available (in use or does not exist)
    }

来自 Android 开发者网站,

Caution: Always check for exceptions when using Camera.open(). Failing to check for exceptions if the camera is in use or does not exist will cause your application to be shut down by the system.

【讨论】:

  • 问题依旧出现。不幸的是,由于字符限制,我无法粘贴代码。
【解决方案2】:

让我们分解一下,这是你的代码:

1.  if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
2.      ;
3.  {
        camera = Camera.open();
        parameters = camera.getParameters();
        isflash = true;
    }

这就是发生的事情。

1.  // If the system has a camera flash
2.  // Do nothing. The condition terminates here.
3.  // Open camera in any case.

要解决此问题,请删除第 2 行的杂散分号,以后请注意分号。

【讨论】:

  • 我删除了它,但问题仍然存在。
  • 您检查权限,但无论权限检查结果如何,都尝试打开相机。相机周围缺少一个 else 块。或者也许换个方向。如果设备没有摄像头,为什么还要请求许可?
猜你喜欢
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 2016-10-03
  • 2018-03-23
  • 2015-05-09
  • 2016-11-19
相关资源
最近更新 更多