本文參考文獻(xiàn):《瘋狂Android講義 : 第2版 》
本文參考文章: 《Android 6.0 - 動(dòng)態(tài)權(quán)限管理的解決方案》
檢測(cè)權(quán)限工具類
檢測(cè)權(quán)限工具類握截,我們可以將其在多個(gè)應(yīng)用中復(fù)用:
package com.toby.personal.testlistview;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import android.util.Log;
/**
* Created by toby on 2017/4/29.
*/
class PermissionsChecker {
private final Context mContext;
PermissionsChecker(Context context) {
mContext = context.getApplicationContext();
}
// 判斷權(quán)限集合
boolean lacksPermissions(String... permissions) {
for (String permission : permissions) {
if (lacksPermission(permission)) {
Log.d("","jkdfksahdfkhsadkjghdfskg: " + permission);
return true;
}
}
return false;
}
// 判斷是否缺少權(quán)限
private boolean lacksPermission(String permission) {
return ContextCompat.checkSelfPermission(mContext, permission) ==
PackageManager.PERMISSION_DENIED;
}
}
授權(quán)頁
授權(quán)頁, 首先使用系統(tǒng)默認(rèn)的授權(quán)頁, 當(dāng)用戶拒絕時(shí), 指導(dǎo)用戶手動(dòng)設(shè)置, 當(dāng)用戶再次操作失敗后, 返回繼續(xù)提示儒飒。用戶手動(dòng)退出授權(quán)頁時(shí), 給使用頁發(fā)送授權(quán)失敗的通知。我們可以保存這個(gè)授權(quán)頁并將其在多個(gè)應(yīng)用中復(fù)用箩祥。
package com.toby.personal.testlistview;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
/**
* Created by toby on 2017/4/29.
*/
public class PermissionsActivity extends AppCompatActivity {
public static final int PERMISSIONS_GRANTED = 0; // 權(quán)限授權(quán)
public static final int PERMISSIONS_DENIED = 1; // 權(quán)限拒絕
private static final int PERMISSION_REQUEST_CODE = 0; // 系統(tǒng)權(quán)限管理頁面的參數(shù)
private static final String EXTRA_PERMISSIONS =
"com.toby.personal.permission.extra_permission"; // 權(quán)限參數(shù)
private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
private PermissionsChecker mChecker; // 權(quán)限檢測(cè)器
private boolean isRequireCheck; // 是否需要系統(tǒng)權(quán)限檢測(cè), 防止和系統(tǒng)提示框重疊
// 啟動(dòng)當(dāng)前權(quán)限頁面的公開接口
public static void startActivityForResult(Activity activity, int requestCode, String... permissions) {
Intent intent = new Intent(activity, PermissionsActivity.class);
intent.putExtra(EXTRA_PERMISSIONS, permissions);
ActivityCompat.startActivityForResult(activity, intent, requestCode, null);
}
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent() == null || !getIntent().hasExtra(EXTRA_PERMISSIONS)) {
throw new RuntimeException("PermissionsActivity需要使用靜態(tài)startActivityForResult方法啟動(dòng)!");
}
setContentView(R.layout.activity_permissions);
mChecker = new PermissionsChecker(this);
isRequireCheck = true;
}
@Override protected void onResume() {
super.onResume();
if (isRequireCheck) {
String[] permissions = getPermissions();
if (mChecker.lacksPermissions(permissions)) {
requestPermissions(permissions); // 請(qǐng)求權(quán)限
} else {
allPermissionsGranted(); // 全部權(quán)限都已獲取
}
} else {
isRequireCheck = true;
}
}
// 返回傳遞的權(quán)限參數(shù)
private String[] getPermissions() {
return getIntent().getStringArrayExtra(EXTRA_PERMISSIONS);
}
// 請(qǐng)求權(quán)限兼容低版本
private void requestPermissions(String... permissions) {
ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
}
// 全部權(quán)限均已獲取
private void allPermissionsGranted() {
setResult(PERMISSIONS_GRANTED);
finish();
}
/**
* 用戶權(quán)限處理,
* 如果全部獲取, 則直接過.
* 如果權(quán)限缺失, 則提示Dialog.
*
* @param requestCode 請(qǐng)求碼
* @param permissions 權(quán)限
* @param grantResults 結(jié)果
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE && hasAllPermissionsGranted(grantResults)) {
isRequireCheck = true;
allPermissionsGranted();
} else {
isRequireCheck = false;
showMissingPermissionDialog();
}
}
// 含有全部的權(quán)限
private boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
return false;
}
}
return true;
}
// 顯示缺失權(quán)限提示
private void showMissingPermissionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(PermissionsActivity.this);
builder.setTitle(R.string.help);
builder.setMessage(R.string.string_help_text);
// 拒絕, 退出應(yīng)用
builder.setNegativeButton(R.string.quit, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
setResult(PERMISSIONS_DENIED);
finish();
}
});
builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
startAppSettings();
}
});
builder.setCancelable(false);
builder.show();
}
// 啟動(dòng)應(yīng)用的設(shè)置
private void startAppSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
startActivity(intent);
}
}
需要在 AndroidManifest.xml 中加入權(quán)限的申請(qǐng)內(nèi)容:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
主布局文件的內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container"
android:background="@color/colorGray"
android:orientation="vertical"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/start"
android:onClick="start"
/>
</LinearLayout>
主程序文件的內(nèi)容如下:
package com.toby.personal.testlistview;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
final private static String TAG = "Toby_Test";
final private static int REQUEST_CODE = 29; // 請(qǐng)求碼
static boolean listenerStart = false;
static final String[] PERMISSIONS = new String[]{
Manifest.permission.READ_PHONE_STATE
// ,Manifest.permission.ACCESS_COARSE_LOCATION
// ,Manifest.permission.ACCESS_FINE_LOCATION
};
private PermissionsChecker permissionsChecker;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "=========== onCreate ===========");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
permissionsChecker = new PermissionsChecker(this);
}
@Override
protected void onResume() {
super.onResume();
if (permissionsChecker.lacksPermissions(PERMISSIONS)) {
startPermissionsActivity();
}
}
private void startPermissionsActivity() {
PermissionsActivity.startActivityForResult(this, REQUEST_CODE, PERMISSIONS);
}
public void start(View view) {
if (!listenerStart) {
final TelephonyManager telephonyManager =
(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
OutputStream os = null;
try {
os = openFileOutput("phoneList", MODE_APPEND);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PrintStream ps = new PrintStream(os);
ps.println(new Date() + " 來電: " + incomingNumber);
ps.close();
break;
default:
break;
}
super.onCallStateChanged(state, incomingNumber);
}
};
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
listenerStart = true;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 拒絕時(shí), 關(guān)閉頁面, 缺少主要權(quán)限, 無法運(yùn)行
if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
finish();
}
}
}
我們可以在 /data/data/com.toby.personal.myapplication/files/phoneList 文件中查看監(jiān)聽的內(nèi)容:
程序的運(yùn)行效果志电,各位可以自行嘗試骇笔,如果有什么問題彻消,可以留言一起討論竿拆。