当前位置: 首页 > 知识库问答 >
问题:

不幸的是,应用程序已经停止,允许后允许或拒绝它的工作,但在一开始我会弹出我的应用程序已经停止

鲍国兴
2023-03-14

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

07-26 18:41:56.080 3003-3003/com.example.android.camerapermissionE/Android运行时:致命异常:主进程:com.example.android.camerapermission,PID:3003java.lang.运行时异常:无法启动活动组件信息{com.example.android.camerapermission/com.example.android.camerapermission.MainActivity}:java.lang.运行时异常:未能连接到android.app.ActivityT的摄像机服务hread.perform启动活动(ActivityThread.java:2416)在android.app.ActivityThread.handle启动活动(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. reect.法。调用(本机方法)在com. android. interal. os. ZygoteInit$MEodAndArgsCaller. run(ZygoteInit. java: 726)在com. android. interal. os. ZygoteInit. main(ZygoteInit. java: 616)造成:java. lang. Runtime异常:未能连接到android. hardware. Camera的摄像机服务。(相机。java: 495)在android. hardware。相机。打开(相机。java: 356)在com。示例。android. cammission。Mainactive. onCreed(Main

这是我的ctivity.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;
        }
    }
}

注意:清单中已经设置了摄像头权限。xml。

共有2个答案

锺离锦
2023-03-14

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

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行的分号,并在将来注意分号。

魏旭
2023-03-14

你需要把打开摄像头的电话放在试一试中。

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.
 类似资料:
  • 我正试图将我的启动器活动更改为我刚刚使用twitter数字开发的身份验证活动,我已经在android和java代码中进行了必要的调整,但注意到每次尝试启动时应用程序都会崩溃,身份验证活动的名称是。在调试会话期间,我从android监视器控制台观察到,在com.close.close.aboutactivity.oncreate(aboutactivity.java:34)处蓝色突出显示的一行

  • 这个想法是在警报开始时启动一个游戏。我在下面展示了manifest.xml。如果我犯了错误,请纠正我。因为我刚接触Android系统,所以我无法理解它。PS:我已经搜索了其他类似的问题,并纠正了许多其他错误,但问题仍然存在。 这是我从教程(AndroidTimeActivity)中获得的警报代码: 这是AlarmReceiver类:

  • 编辑问题以包括所需的行为、特定问题或错误以及重现问题所需的最短代码。这将帮助其他人回答问题。 我的主要活动: 我的清单: 我的下一个代码: 下一个: 对于堆栈跟踪排序: 我的xml文件显示第一页: 要显示第二个选项卡的我的xml文件: 最后我想告诉你,我已经坚持了三天了。请更正此代码。中的“TabListener”接口不可用。但忽略它,在几毫秒后运行我的应用程序,然后“很遗憾,你的应用程序停止工作

  • 我想在通知上打开我的MapsActive单击通知正常工作,但当我单击通知时,它会让我停止应用程序 通知活动。班 地图civity.class activity_map LogCat ethod.invokeActivityTcom.android.internal.os.LaunchActive(ActivityTaller.run)atnit.java:726ActivityTcom.andro

  • 代码 和logcat 06-03 16:59:26.570 972 0-9757/com.example.abhijitroy.superhero E/AndroidRuntime:致命异常:AsyncTask#1进程:com.example.abhijitroy.superhero,PID:9720 java.lang.RuntimeException:在Android.os.AsyncTask

  • 问题内容: 我是android应用程序开发的新手(仅从昨天开始我才开始学习android)。 我在AVD中收到消息,例如-不幸地已停止,请帮助我解决此错误,我想在android中学习更多信息,但被此错误所吸引.. plz..plz ..帮助我解决这个问题。 我的main.java是 } 我的main.xml是 和日志是 请解释为什么会这样。告诉我解决方案 问题答案: 您在第38行获得了NPE,即: