安卓获取权限之onRequestPermissionResult

1.所有安卓一定要先把权限请了
2.检查权限时,由于会在机器上弹出选择框,当你选择完是否获取权限后,执行onRequestPermissionResult回调函数,获取选择的结果
3.检查权限时,机器弹出选择框,这时,继续执行检查权限后的语句,不会等待你选完是否获取,这个过程是异步的,容易出现问题
4.所以一般是在执行onRequestPermissionResult之后确认获取权限的位置之后,再进行相关函数的执行。

package com.sensetime.asteriamtk;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.sensetime.asteriamtk.Utils.NV21ToBitmap;
import com.sensetime.asteriamtk.Utils.Utils;
import com.sensetime.render.STRender;

import com.tcl.bean.EvaBean;
import com.tcl.bean.EvaPoint;
import com.tcl.bean.face.EvaFace;
import com.tcl.vision.listeners.EvaInitResultCallback;
import com.tcl.vision.listeners.OnBeanResultListener;
import com.tcl.vision.managers.EvaVisionAPUManager;
import com.tcl.vision.managers.EvaVisionManager;
import com.tcl.vision.managers.EvaVisionNPUManager;
import com.tcl.vision.utils.EvaConstants;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import static android.opengl.GLSurfaceView.RENDERMODE_WHEN_DIRTY;
import static com.sensetime.asteriamtk.Utils.Utils.getNV21FromBitmap;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = "AsteriaMTK";

    private static final int WIDTH_720 = 1280;
    private static final int HEIGHT_720 = 720;





    private Queue mCpuQueue = new LinkedList<>();
    private final Object mCpuQueueLock = new Object();
    private EvaVisionAPUManager mEvaVisionManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initAlogrithmModule();//初始化
        checkCameraPermission();//检查权限,联动把所有权限都申请了
        if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            addModelAndStartDetect();
        }//第一次打开软件不执行,以后打开软件才执行//(3)

    }

    private void initAlogrithmModule() {
        mEvaVisionManager = EvaVisionManager.getInstance().getEvaAPUVisionManager();
        mEvaVisionManager.init(this, new EvaInitResultCallback() {
            @Override
            public void onInitEvaSuccess() {
                Log.i(TAG, "onInitEvaSuccess: ");
            }

            @Override
            public void onInitEvaFailure(Exception e) {
                Log.i(TAG, "onInitEvaFailure: ");
            }
        });
        mEvaVisionManager.setAIDetections(EvaConstants.DETECT_FACE);

    }



    private void addModelAndStartDetect() {
        startDetect();
    }

    private void startDetect() {
        resetFps();
        clearCpuInfo();
        mDetectThread = new DetectThread();
        mDetectThread.start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDetectThread != null) {
            try {
                mDetectThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mDetectThread = null;
        }
        mEvaVisionManager.release();
//        mDetectManager.release();
    }

    private void clearCpuInfo() {
        synchronized (mCpuQueueLock) {
            mCpuQueue.clear();
        }
    }

    private int mFps = 0;
    private long mLastUpdateFpsTime = 0;

    private void resetFps() {
        mLastUpdateFpsTime = 0;
        mFps = 0;
    }



    private DetectThread mDetectThread;
    private class DetectThread extends Thread {

        @Override
        public void run() {
            byte[] image;
            String filename = "//sdcard//2";
            String[] fileList = getFileList(filename);
            int numGender = 0, numAge = 0, numAge0_12 = 0, numAge12_18 = 0, numAge24_ = 0;
            Log.e("lenth", String.valueOf(fileList.length));

            for (int i = 0; i < fileList.length; i++) {

                Log.e("i", String.valueOf(i));

                Bitmap bm = readPicture(filename+"//"+fileList[i]);
                image = getNV21FromBitmap(bm);
                //EvaBean res = mEvaVisionManager.detect(image, EvaConstants.PixelFormats.NV21, WIDTH_720, HEIGHT_720);
                EvaBean res = mEvaVisionManager.detect(image, EvaConstants.PixelFormats.NV21, WIDTH_720, HEIGHT_720);
                if (res != null && res.getFaceInfos() != null) {
                    if (res.getFaceInfos().size() > 0) {
                        EvaFace evaFace = res.getFaceInfos().get(0);
                        if (evaFace.getFaceAttribute() != null) {
                            Log.i(TAG, "age = " + evaFace.getFaceAttribute().age);
                            Log.i(TAG, " gender = " + evaFace.getFaceAttribute().gender);
                        }
                        String[] nameSplit = fileList[i].split("_");
                        if (evaFace.getFaceAttribute().age == Integer.parseInt(nameSplit[1])) {//将数据保存
                            numAge++;
                        }
                        int sex = 0;
                        if (nameSplit[2] == "m.jpg") {
                            sex = 0;
                        } else {
                            sex = 1;
                        }
                        if (evaFace.getFaceAttribute().gender == sex) {
                            numGender++;
                        }
                    }
                } else {
                    Log.i("没获取到信息", "NULL ");
                }

            }
        }
    }


    private static final int ST_PERMISSION_REQUEST_CAMERA = 1;
    private static final int ST_PERMISSION_REQUEST_READ_EXTERNAL_STORAGE = 2;
    private static final int ST_PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 3;

    private void checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {//只有当!=PackageManager.PERMISSION_GRANTED时候才执行,保证只在第一次打开软件时候申请权限(4)
                requestPermissions(new String[]{Manifest.permission.CAMERA},
                        ST_PERMISSION_REQUEST_CAMERA);
            }
        }
    }

    private void checkReadPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        ST_PERMISSION_REQUEST_READ_EXTERNAL_STORAGE);
            }
        }
    }

    private void checkWritePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    ST_PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
        }
       }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {//第一次打开软件可以进来
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ST_PERMISSION_REQUEST_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e("----","cameraPermisssion");
                checkReadPermission();//联动申请读

            }
        } else if (requestCode == ST_PERMISSION_REQUEST_READ_EXTERNAL_STORAGE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e("----","readPermisssion");
                checkWritePermission();//联动申请写
            }
        } else if (requestCode == ST_PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e("----","writePermission");
                //File file=new File("//sdcard//text.txt");
                //try {
                  //  file.createNewFile();
                  //  Log.d("创建文件成功","wenjianshibai");
               // } catch (IOException e) {

                  //  e.printStackTrace();
                //}
                //addModelAndStartDetect();

            } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                Log.e("----","write申请失败");
            }
        }

    }
    public Bitmap readPicture(String filepath){
        Log.d("filepath",filepath);
        Bitmap bm = BitmapFactory.decodeFile(filepath);
        if(bm==null){
            Log.e("bm","null");
        }
        return bm;
    }
    public  String[]  getFileList(String filename){
        File files = new File(filename);
        String[] list1=files.list();
        return  list1;
    }

}

例如上述代码会获得一定的权限,第一步会获取权限,要保证获取权限后在进行后续操作于是有了(3),在第一次打开软件获取权限后就要进行后续,原因是(3)处的代码已经在你点击确认获取权限前,异步执行,等你点击,调用回调函数onRequestPermissionsResult的时候,早就执行了,所以如果不在onRequestPermissionsResult执行的时候执行后续操作,第一次打开软件就不会进行后续操作了,但是在以后打开软件时候我们又不需要再取申请权限,每次都去申请很蛮烦,于是有了(4),有了(4)会导致,第二次第三次。。。。打开软件后不会去申请权限,也就不会调用onRequestPermissionsResult,就不会执行后续操作,所以必须写(3),与onRequestPermissionsResult配合保证每次都去执行后续操作。
总之一句话:(3)保证了除第一次之外都可以执行后续程序
(4)保证了只在第一次打开软件时候获取权限和第一次打开软件可以执行后续操作

你可能感兴趣的:(安卓)