android– 表面视图在我允许后不显示相机

android– 表面视图在我允许后不显示相机,第1张

概述publicViewonCreateView(LayoutInflaterinflater,@NullableViewGroupcontainer,BundlesavedInstanceState){Viewview=inflater.inflate(R.layout.fragment_camera,container,false);cameraId=Camera.CameraInfo.CAMERA_FACING_BACK;flipCamera

public VIEw onCreateVIEw(LayoutInflater inflater, @Nullable VIEwGroup container, Bundle savedInstanceState) {    VIEw vIEw = inflater.inflate(R.layout.fragment_camera, container, false);    cameraID = Camera.CameraInfo.CAMERA_FACING_BACK;    flipCamera = vIEw.findVIEwByID(R.ID.flipCamera);    flashCamerabutton = vIEw.findVIEwByID(R.ID.flash);    captureImage = vIEw.findVIEwByID(R.ID.captureImage);    surfaceVIEw = vIEw.findVIEwByID(R.ID.surfaceVIEw);    surfaceHolder = surfaceVIEw.getHolder();    surfaceHolder.addCallback(this);    flipCamera.setonClickListener(this);    captureImage.setonClickListener(this);    flashCamerabutton.setonClickListener(this);    getActivity().getwindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);    if (Camera.getNumberOfCameras() > 1) {        flipCamera.setVisibility(VIEw.VISIBLE);    }    if (!getActivity().getBaseContext().getPackageManager().hasSystemFeature(            PackageManager.FEATURE_CAMERA_FLASH)) {        flashCamerabutton.setVisibility(VIEw.GONE);    }    return vIEw;}@RequiresAPI(API = Build.VERSION_CODES.M)@OverrIDepublic voID surfaceCreated(SurfaceHolder holder) {    if (!openCamera(Camera.CameraInfo.CAMERA_FACING_BACK)) {        alertCameraDialog();    }}private boolean openCamera(int ID) {    boolean result = false;    cameraID = ID;    releaseCamera();    try {        camera = Camera.open(cameraID);    } catch (Exception e) {        e.printstacktrace();    }    if (camera != null) {        try {            setUpCamera(camera);            camera.setErrorCallback(new Camera.ErrorCallback() {                @OverrIDe                public voID one rror(int error, Camera camera) {                }            });            camera.setPrevIEwdisplay(surfaceHolder);            camera.startPrevIEw();            result = true;        } catch (IOException e) {            e.printstacktrace();            result = false;            releaseCamera();        }    }    return result;}private voID setUpCamera(Camera c) {    Camera.CameraInfo info = new Camera.CameraInfo();    Camera.getCameraInfo(cameraID, info);    rotation = getActivity().getwindowManager().getDefaultdisplay().getRotation();    int degree = 0;    switch (rotation) {        case Surface.ROTATION_0:            degree = 0;            break;        case Surface.ROTATION_90:            degree = 90;            break;        case Surface.ROTATION_180:            degree = 180;            break;        case Surface.ROTATION_270:            degree = 270;            break;        default:            break;    }    if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {        // frontFacing        rotation = (info.orIEntation + degree) % 330;        rotation = (360 - rotation) % 360;    } else {        // Back-facing        rotation = (info.orIEntation - degree + 360) % 360;    }    c.setdisplayOrIEntation(rotation);    Camera.Parameters params = c.getParameters();    showFlashbutton(params);    List<String> focusModes = params.getSupportedFlashModes();    if (focusModes != null) {        if (focusModes                .contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {            params.setFlashMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);        }    }    params.setRotation(rotation);}private voID showFlashbutton(Camera.Parameters params) {    boolean showFlash = (getActivity().getPackageManager().hasSystemFeature(            PackageManager.FEATURE_CAMERA_FLASH) && params.getFlashMode() != null)            && params.getSupportedFlashModes() != null            && params.getSupportedFocusModes().size() > 1;    flashCamerabutton.setVisibility(showFlash ? VIEw.VISIBLE            : VIEw.INVISIBLE);}private voID releaseCamera() {    try {        if (camera != null) {            camera.setPrevIEwCallback(null);            camera.setErrorCallback(null);            camera.stopPrevIEw();            camera.release();            camera = null;        }    } catch (Exception e) {        e.printstacktrace();        Log.e("error", e.toString());        camera = null;    }}@OverrIDepublic voID surfaceChanged(SurfaceHolder holder, int format, int wIDth,                           int height) {}@OverrIDepublic voID surfaceDestroyed(SurfaceHolder holder) {}@OverrIDepublic voID onClick(VIEw v) {    switch (v.getID()) {        case R.ID.flash:            flashOnbutton();            break;        case R.ID.flipCamera:            flipCamera();            break;        case R.ID.captureImage:            takeImage();            break;        default:            break;    }}private voID takeImage() {    camera.takePicture(null, null, new Camera.PictureCallback() {        private file imagefile;        @OverrIDe        public voID onPictureTaken(byte[] data, Camera camera) {            try {                // convert byte array into bitmap                Bitmap loadedImage = null;                Bitmap rotatedBitmap = null;                loadedImage = BitmapFactory.decodeByteArray(data, 0, data.length);                // rotate Image                Matrix rotateMatrix = new Matrix();                rotateMatrix.postRotate(rotation);                rotatedBitmap = Bitmap.createBitmap(loadedImage, 0, 0,                        loadedImage.getWIDth(), loadedImage.getHeight(),                        rotateMatrix, false);                String state = Environment.getExternalStorageState();                file folder = null;                if (state.contains(Environment.MEDIA_MOUNTED)) {                    folder = new file(Environment                            .getExternalStorageDirectory() + "/Demo");                } else {                    folder = new file(Environment                            .getExternalStorageDirectory() + "/Demo");                }                boolean success = true;                if (!folder.exists()) {                    success = folder.mkdirs();                }                if (success) {                    java.util.Date date = new java.util.Date();                    imagefile = new file(folder.getabsolutePath()                            + file.separator                            + new Timestamp(date.getTime()).toString()                            + "Image.jpg");                    imagefile.createNewfile();                    Toast.makeText(getActivity().getBaseContext(), "Image Saved", Toast.LENGTH_SHORT).show();                    openCamera(cameraID);                } else {                    Toast.makeText(getActivity().getBaseContext(), "Image Not saved", Toast.LENGTH_SHORT).show();                    return;                }                ByteArrayOutputStream ostream = new ByteArrayOutputStream();                // save image into gallery                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);                fileOutputStream fout = new fileOutputStream(imagefile);                fout.write(ostream.toByteArray());                fout.close();                ContentValues values = new ContentValues();                values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");                values.put(MediaStore.MediaColumns.DATA, imagefile.getabsolutePath());                getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);            } catch (Exception e) {                e.printstacktrace();            }        }    });}private voID flipCamera() {    int ID = (cameraID == Camera.CameraInfo.CAMERA_FACING_BACK ? Camera.CameraInfo.CAMERA_FACING_FRONT            : Camera.CameraInfo.CAMERA_FACING_BACK);    if (!openCamera(ID)) {        alertCameraDialog();    }}private voID alertCameraDialog() {    Toast.makeText(getActivity(), "Error to open camera", Toast.LENGTH_SHORT).show();}private voID flashOnbutton() {    if (camera != null) {        try {            Camera.Parameters param = camera.getParameters();            param.setFlashMode(!flashmode ? Camera.Parameters.FLASH_MODE_TORCH                    : Camera.Parameters.FLASH_MODE_OFF);            camera.setParameters(param);            flashmode = !flashmode;        } catch (Exception e) {            // Todo: handle exception        }    }}

}

这是我的相机片段代码.当我在运行时给予权限时,surfacevIEw不会显示相机.它在onResume()或该片段中的任何button单击时显示摄像头.如何解决此问题.如何设置当我单击允许按钮时,它会自动在表面视图中显示相机.

解决方法:

使用这个课程

公共类RunTimePermission扩展Activity
{

private Activity activity;private ArrayList<PermissionBean> arrayListPermission;private String[] arrayPermissions;private RunTimePermissionListener runTimePermissionListener;public RunTimePermission(Activity activity){    this.activity = activity;}public class PermissionBean{    String permission;    boolean isAccept;}public voID requestPermission(String[] permissions, RunTimePermissionListener runTimePermissionListener){    this.runTimePermissionListener = runTimePermissionListener;    arrayListPermission = new ArrayList<PermissionBean>();    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)    {        for (int i = 0; i < permissions.length; i++)        {            PermissionBean permissionBean = new PermissionBean();            if (ContextCompat.checkSelfPermission(activity, permissions[i]) == PackageManager.PERMISSION_GRANTED)            {                permissionBean.isAccept = true;            }            else            {                permissionBean.isAccept = false;                permissionBean.permission = permissions[i];                arrayListPermission.add(permissionBean);            }        }        if (arrayListPermission.size() <= 0)        {            runTimePermissionListener.permissionGranted();            return;        }        arrayPermissions = new String[arrayListPermission.size()];        for (int i = 0; i < arrayListPermission.size(); i++)        {            arrayPermissions[i] = arrayListPermission.get(i).permission;        }        activity.requestPermissions(arrayPermissions, 10);    }    else    {        if (runTimePermissionListener != null)        {            runTimePermissionListener.permissionGranted();        }    }}public interface RunTimePermissionListener{    voID permissionGranted();    voID permissionDenIEd();}private voID callSettingActivity(){    Intent intent = new Intent();    intent.setAction(Settings.ACTION_APPliCATION_DETAILS_SETTINGS);    Uri uri = Uri.fromParts("package", activity.getPackagename(), null);    intent.setData(uri);    activity.startActivity(intent);}private voID checkUpdate(){    boolean isGranted = true;    int denIEdCount = 0;    for (int i = 0; i < arrayListPermission.size(); i++)    {        if (!arrayListPermission.get(i).isAccept)        {            isGranted = false;            denIEdCount++;        }    }    if (isGranted)    {        if (runTimePermissionListener != null)        {            runTimePermissionListener.permissionGranted();        }    }    else    {        if (runTimePermissionListener != null)        {            setAlertMessage();            runTimePermissionListener.permissionDenIEd();        }    }}public voID setAlertMessage(){    AlertDialog.Builder adb;    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LolliPOP) {        adb = new AlertDialog.Builder(activity, androID.R.style.theme_Material_light_Dialog_Alert);    } else {        adb = new AlertDialog.Builder(activity);    }    adb.setTitle(activity.getResources().getString(R.string.app_name));    String msg = "<p>Dear User, </p>" +            "<p>Seems like you have <b>\"DenIEd\"</b> the minimum requirement permission to access more features of application.</p>" +            "<p>You must have to <b>\"Allow\"</b> all permission. We will not share your data with anyone else.</p>" +            "<p>Do you want to enable all requirement permission ?</p>" +            "<p>Go To : Settings >> App > " + activity.getResources().getString(R.string.app_name) + " Permission : Allow ALL</p>";    adb.setMessage(HTML.fromHTML(msg));    adb.setPositivebutton("Allow All", new AlertDialog.OnClickListener()    {        @OverrIDe        public voID onClick(DialogInterface dialog, int which)        {            callSettingActivity();            dialog.dismiss();        }    });    adb.setNegativebutton("Remind Me Later", new AlertDialog.OnClickListener()    {        @OverrIDe        public voID onClick(DialogInterface dialog, int which)        {            dialog.dismiss();        }    });    if (!((Activity) activity).isFinishing() && msg.length() > 0)    {        adb.show();    }    else    {        Log.v("log_tag", "either activity finish or message length is 0");    }}private voID updatePermissionResult(String permissions, int grantResults){    for (int i = 0; i < arrayListPermission.size(); i++)    {        if (arrayListPermission.get(i).permission.equals(permissions))        {            if (grantResults == 0)            {                arrayListPermission.get(i).isAccept = true;            }            else            {                arrayListPermission.get(i).isAccept = false;            }            break;        }    }}public voID onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){    for (int i = 0; i < permissions.length; i++)    {        updatePermissionResult(permissions[i], grantResults[i]);    }    checkUpdate();}}

在活动onCreate()方法中写下此代码

getwindow().addFlags(WindowManager.LayoutParams.FLAG_FulLSCREEN);    runTimePermission = new RunTimePermission(this);    runTimePermission.requestPermission(new String[]{Manifest.permission.CAMERA,            Manifest.permission.RECORD_AUdio,            Manifest.permission.READ_EXTERNAL_STORAGE,            Manifest.permission.WRITE_EXTERNAL_STORAGE    }, new RunTimePermission.RunTimePermissionListener() {        @OverrIDe        public voID permissionGranted() {            // First we need to check availability of play services            initControls();            IDentifyOrIEntationEvents();            //create a folder to get image            folder = new file(Environment.getExternalStorageDirectory() + "/Media");            if (!folder.exists()) {                folder.mkdirs();            }            //capture image on callback            captureImageCallback();            //            if (camera != null) {                Camera.CameraInfo info = new Camera.CameraInfo();                if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {                    imgFlashOnOff.setVisibility(VIEw.GONE);                }            }        }        @OverrIDe        public voID permissionDenIEd() {        }    });

然后从onCreate()中编写此代码

  @OverrIDe    public voID onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {    if (runTimePermission != null) {        runTimePermission.onRequestPermissionsResult(requestCode, permissions, grantResults);    }    super.onRequestPermissionsResult(requestCode, permissions, grantResults);}
总结

以上是内存溢出为你收集整理的android – 表面视图在我允许后不显示相机全部内容,希望文章能够帮你解决android – 表面视图在我允许后不显示相机所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1118507.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存