添加CAMERA,RECORD_AUDIO,WRITE_EXTERNAL_STORAGE 的persmisstions过程

来源:互联网 发布:sql 查询分析器 编辑:程序博客网 时间:2024/06/08 11:56


注意: 本方法是要针对MainActivity 做的权限,如果不是的话,需要修改PermissionsActivity.java里的函数名称,以便处理完可以启动主接口。
private void handlePermissionsSuccess() {    Intent intent = new Intent(this, MainActivity.class);    startActivity(intent);    finish();}

1 复制PermissionsActivity.java,QucickActivity.java到本工程。

2 复制permission.xml 到本工程

3 复制以下内容到string.xml
<string name="camera_error_title">camera not permission grant error!</string><string name="error_permissions">error_permissions</string><string name="dialog_dismiss">dialog_dismiss</string>

4 复制以下内容到AndroidManifest.xml

<activity android:name=".PermissionsActivity"    android:excludeFromRecents="true"    android:parentActivityName=".MainActivity">    <meta-data android:name="android.support.PARENT_ACTIVITY"      android:value=".MainActivity"/></activity>

 

5 复制以下内容到MainActivity.java


private boolean mHasCriticalPermissions=false;private boolean isMorHight(){    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M || "MNC".equals(Build.VERSION.CODENAME);}private void checkPermissions(){    if(!isMorHight())    {        Log.v("GLCamera-MainActivity","not running on M,skipping permission checks");        mHasCriticalPermissions = true;        return;    }    if(checkSelfPermission(Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED &&            checkSelfPermission(Manifest.permission.RECORD_AUDIO)==PackageManager.PERMISSION_GRANTED &&            checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED)    {        mHasCriticalPermissions = true;    }    else    {        mHasCriticalPermissions= false;    }    if(!mHasCriticalPermissions)    {        Intent intent = new Intent(this,PermissionsActivity.class);        startActivity(intent);        finish();    }}
6  修改 MainActivity 继承为 QuickActivity , public class MainActivity extends QuickActivity 
7 修改onCreate() onCreateTasks()
 @Overrideprotected void onCreateTasks(Bundle savedInstanceState) {    // super.onCreate(savedInstanceState);    // addPermissions();    checkPermissions();    if(!mHasCriticalPermissions)    {        finish();        return;    }   //下面部分和原来的 onCreate一样,注意不需要调用super.onCreate()    //initView();}

 

8 修改onResume() onResumeTasks()

 

@Overrideprotected void onResumeTasks(){    checkPermissions();    if(!mHasCriticalPermissions)    {        finish();        return;    }
//下面部分和原来的 onResume一样,注意不需要调用super.onResume()   //resumeother();}

 

9修改onPause() onPauseTasks()

 内容和原来的一样,注意不需要调用super.onPause()

 
 
10修改onDestroy() onDestroyTasks()

 内容和原来的一样,注意不需要调用super.onDestroy()

11  其它一些 onXXX 修改,如onStop()…onStopTasks().


附带上PermissionsActivity.java,QucickActivity.java permission.xml


//PermissionsActivity.java
//package com.company.camera.recorderAV;
import android.Manifest;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.app.DownloadManager;import android.app.KeyguardManager;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.os.Bundle;import android.util.Log;import android.view.KeyEvent;import android.view.Window;import android.view.WindowManager;/** * Created by me on 2017/6/27. */public class PermissionsActivity extends QuickActivity { private KeyguardManager mKeygardManger; private static final String TAG = "PermissionsActivity"; private static int PERMISSION_REQUEST_CODE = 1; private static int RESULT_CODE_OK = 1; private static int RESULT_CODE_FAILED = 2; private int mIndexPermissionRequestCamera; private int mIndexPermissionRequestMicrophone; private int mIndexPermissionRequestLocation; private int mIndexPermissionRequestStorage; private boolean mShouldRequestCameraPermission; private boolean mShouldRequestMicrophonePermission; private boolean mShouldRequestLocationPermission; private boolean mShouldRequestStoragePermission; private int mNumPermissionsToRequest; private boolean mFlagHasCameraPermission; private boolean mFlagHasMicrophonePermission; private boolean mFlagHasStoragePermission; @Override protected void onCreateTasks(Bundle savedInstanceState) { setContentView(R.layout.permission); Window win = getWindow(); if(isKeyguardLocked()) { win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); } else { win.clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); } } @Override protected void onResumeTasks() { mNumPermissionsToRequest =0; checkPermissions(); } private void checkPermissions() { if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { mNumPermissionsToRequest++; mShouldRequestCameraPermission = true; } else { mFlagHasCameraPermission = true; } if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { mNumPermissionsToRequest++; mShouldRequestMicrophonePermission = true; } else { mFlagHasMicrophonePermission = true; } if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { mNumPermissionsToRequest++; mShouldRequestStoragePermission = true; } else { mFlagHasStoragePermission = true; } if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { mNumPermissionsToRequest++; mShouldRequestLocationPermission = true; } if (mNumPermissionsToRequest != 0) { if (!isKeyguardLocked()) { buildPermissionsRequest(); } else { // Permissions dialog has already been shown, or we're on // lockscreen, and we're still missing permissions. handlePermissionsFailure(); } } else { handlePermissionsSuccess(); } } private void buildPermissionsRequest() { String[] permissionsToRequest = new String[mNumPermissionsToRequest]; int permissionsRequestIndex = 0; if (mShouldRequestCameraPermission) { permissionsToRequest[permissionsRequestIndex] = Manifest.permission.CAMERA; mIndexPermissionRequestCamera = permissionsRequestIndex; permissionsRequestIndex++; } if (mShouldRequestMicrophonePermission) { permissionsToRequest[permissionsRequestIndex] = Manifest.permission.RECORD_AUDIO; mIndexPermissionRequestMicrophone = permissionsRequestIndex; permissionsRequestIndex++; } if (mShouldRequestStoragePermission) { permissionsToRequest[permissionsRequestIndex] = Manifest.permission.READ_EXTERNAL_STORAGE; mIndexPermissionRequestStorage = permissionsRequestIndex; permissionsRequestIndex++; } if (mShouldRequestLocationPermission) { permissionsToRequest[permissionsRequestIndex] = Manifest.permission.ACCESS_COARSE_LOCATION; mIndexPermissionRequestLocation = permissionsRequestIndex; } Log.v(TAG, "requestPermissions count: " + permissionsToRequest.length); requestPermissions(permissionsToRequest, PERMISSION_REQUEST_CODE); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { Log.v(TAG, "onPermissionsResult counts: " + permissions.length + ":" + grantResults.length); if (mShouldRequestCameraPermission) { if (grantResults.length > 0 && grantResults[mIndexPermissionRequestCamera] == PackageManager.PERMISSION_GRANTED) { mFlagHasCameraPermission = true; } else { handlePermissionsFailure(); } } if (mShouldRequestMicrophonePermission) { if (grantResults.length > 0 && grantResults[mIndexPermissionRequestMicrophone] == PackageManager.PERMISSION_GRANTED) { mFlagHasMicrophonePermission = true; } else { handlePermissionsFailure(); } } if (mShouldRequestStoragePermission) { if (grantResults.length > 0 && grantResults[mIndexPermissionRequestStorage] == PackageManager.PERMISSION_GRANTED) { mFlagHasStoragePermission = true; } else { handlePermissionsFailure(); } } if (mShouldRequestLocationPermission) { if (grantResults.length > 0 && grantResults[mIndexPermissionRequestLocation] == PackageManager.PERMISSION_GRANTED) { // Do nothing } else { // Do nothing } } if (mFlagHasCameraPermission && mFlagHasMicrophonePermission && mFlagHasStoragePermission) { handlePermissionsSuccess(); } } private void handlePermissionsSuccess() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } private void handlePermissionsFailure() { new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.camera_error_title)) .setMessage(getResources().getString(R.string.error_permissions)) .setCancelable(false) .setOnKeyListener(new Dialog.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { finish(); } return true; } }) .setPositiveButton(getResources().getString(R.string.dialog_dismiss), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .show(); }}
//QuickActivity.java

//package com.company.camera.recorderAV;
import android.app.Activity;/** * Created by me on 2017/6/27. *//* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import android.app.Activity;import android.app.KeyguardManager;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.os.SystemClock;import android.util.Log;/** * Workaround for lockscreen double-onResume() bug: * <p> * We track 3 startup situations: * <ul> * <li>Normal startup -- e.g. from GEL.</li> * <li>Secure lock screen startup -- e.g. with a keycode.</li> * <li>Non-secure lock screen startup -- e.g. with just a swipe.</li> * </ul> * The KeyguardManager service can be queried to determine which state we are in. * If started from the lock screen, the activity may be quickly started, * resumed, paused, stopped, and then started and resumed again. This is * problematic for launch time from the lock screen because we typically open the * camera in onResume() and close it in onPause(). These camera operations take * a long time to complete. To workaround it, this class filters out * high-frequency onResume()->onPause() sequences if the KeyguardManager * indicates that we have started from the lock screen. * </p> * <p> * Subclasses should override the appropriate on[Create|Start...]Tasks() method * in place of the original. * </p> * <p> * Sequences of onResume() followed quickly by onPause(), when the activity is * started from a lockscreen will result in a quick no-op.<br> * </p> */public abstract class QuickActivity extends Activity { private static final String TAG = "QuickActivity"; /** onResume tasks delay from secure lockscreen. */ private static final long ON_RESUME_DELAY_SECURE_MILLIS = 30; /** onResume tasks delay from non-secure lockscreen. */ private static final long ON_RESUME_DELAY_NON_SECURE_MILLIS = 15; /** A reference to the main handler on which to run lifecycle methods. */ private Handler mMainHandler; /** * True if onResume tasks have been skipped, and made false again once they * are executed within the onResume() method or from a delayed Runnable. */ private boolean mSkippedFirstOnResume = false; /** When application execution started in SystemClock.elapsedRealtimeNanos(). */ protected long mExecutionStartNanoTime = 0; /** Was this session started with onCreate(). */ protected boolean mStartupOnCreate = false; /** Handle to Keyguard service. */ private KeyguardManager mKeyguardManager = null; /** * A runnable for deferring tasks to be performed in onResume() if starting * from the lockscreen. */ private final Runnable mOnResumeTasks = new Runnable() { @Override public void run() { if (mSkippedFirstOnResume) { Log.v(TAG, "delayed Runnable --> onResumeTasks()"); // Doing the tasks, can set to false. mSkippedFirstOnResume = false; onResumeTasks(); } } }; @Override protected final void onNewIntent(Intent intent) { logLifecycle("onNewIntent", true); Log.v(TAG, "Intent Action = " + intent.getAction()); setIntent(intent); super.onNewIntent(intent); onNewIntentTasks(intent); logLifecycle("onNewIntent", false); } @Override protected final void onCreate(Bundle bundle) { mExecutionStartNanoTime = SystemClock.elapsedRealtimeNanos(); logLifecycle("onCreate", true); mStartupOnCreate = true; super.onCreate(bundle); mMainHandler = new Handler(getMainLooper()); onCreateTasks(bundle); logLifecycle("onCreate", false); } @Override protected final void onStart() { logLifecycle("onStart", true); onStartTasks(); super.onStart(); logLifecycle("onStart", false); } @Override protected final void onResume() { logLifecycle("onResume", true); // For lockscreen launch, there are two possible flows: // 1. onPause() does not occur before mOnResumeTasks is executed: // Runnable mOnResumeTasks sets mSkippedFirstOnResume to false // 2. onPause() occurs within ON_RESUME_DELAY_*_MILLIS: // a. Runnable mOnResumeTasks is removed // b. onPauseTasks() is skipped, mSkippedFirstOnResume remains true // c. next onResume() will immediately execute onResumeTasks() // and set mSkippedFirstOnResume to false Log.v(TAG, "onResume(): isKeyguardLocked() = " + isKeyguardLocked()); mMainHandler.removeCallbacks(mOnResumeTasks); if (isKeyguardLocked() && mSkippedFirstOnResume == false) { // Skipping onResumeTasks; set to true. mSkippedFirstOnResume = true; long delay = isKeyguardSecure() ? ON_RESUME_DELAY_SECURE_MILLIS : ON_RESUME_DELAY_NON_SECURE_MILLIS; Log.v(TAG, "onResume() --> postDelayed(mOnResumeTasks," + delay + ")"); mMainHandler.postDelayed(mOnResumeTasks, delay); } else { Log.v(TAG, "onResume --> onResumeTasks()"); // Doing the tasks, can set to false. mSkippedFirstOnResume = false; onResumeTasks(); } super.onResume(); logLifecycle("onResume", false); } @Override protected final void onPause() { logLifecycle("onPause", true); mMainHandler.removeCallbacks(mOnResumeTasks); // Only run onPauseTasks if we have not skipped onResumeTasks in a // first call to onResume. If we did skip onResumeTasks (note: we // just killed any delayed Runnable), we also skip onPauseTasks to // adhere to lifecycle state machine. if (mSkippedFirstOnResume == false) { Log.v(TAG, "onPause --> onPauseTasks()"); onPauseTasks(); } super.onPause(); mStartupOnCreate = false; logLifecycle("onPause", false); } @Override protected final void onStop() { if (isChangingConfigurations()) { Log.v(TAG, "changing configurations"); } logLifecycle("onStop", true); onStopTasks(); super.onStop(); logLifecycle("onStop", false); } @Override protected final void onRestart() { logLifecycle("onRestart", true); super.onRestart(); // TODO Support onRestartTasks() and handle the workaround for that too. logLifecycle("onRestart", false); } @Override protected final void onDestroy() { logLifecycle("onDestroy", true); onDestroyTasks(); super.onDestroy(); logLifecycle("onDestroy", false); } private void logLifecycle(String methodName, boolean start) { String prefix = start ? "START" : "END"; Log.v(TAG, prefix + " " + methodName + ": Activity = " + toString()); } protected boolean isKeyguardLocked() { if(mKeyguardManager==null) mKeyguardManager=(KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); return mKeyguardManager.isKeyguardLocked(); } protected boolean isKeyguardSecure() { if (mKeyguardManager == null) { mKeyguardManager=(KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); } if (mKeyguardManager != null) { return mKeyguardManager.isKeyguardSecure(); } return false; } /** * Subclasses should override this in place of {@link Activity#onNewIntent}. */ protected void onNewIntentTasks(Intent newIntent) { } /** * Subclasses should override this in place of {@link Activity#onCreate}. */ protected void onCreateTasks(Bundle savedInstanceState) { } /** * Subclasses should override this in place of {@link Activity#onStart}. */ protected void onStartTasks() { } /** * Subclasses should override this in place of {@link Activity#onResume}. */ protected void onResumeTasks() { } /** * Subclasses should override this in place of {@link Activity#onPause}. */ protected void onPauseTasks() { } /** * Subclasses should override this in place of {@link Activity#onStop}. */ protected void onStopTasks() { } /** * Subclasses should override this in place of {@link Activity#onDestroy}. */ protected void onDestroyTasks() { }}

//permission.xml

<?xml version="1.0" encoding="utf-8"?><FrameLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/permissions"    android:background="@android:color/black"    android:layout_width="match_parent"    android:layout_height="match_parent" />


原创粉丝点击