Android Permission 权限 工具类

【导读】
为了方便Android 6.0的权限申请,记录两个工具类的使用。一是通过单独的activity去申请,一是通过BaseActivity去申请。

【步骤】

    <!--AndroidManifest.xml 申请需要的权限-->
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <uses-permission android:name="android.permission.READ_CALL_LOG"/>
    <uses-permission android:name="android.permission.WRITE_CALL_LOG"/>
    <uses-permission android:name="android.permission.USE_SIP"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.BODY_SENSORS"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
//布局代码

<?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:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:padding="8dp">

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/bt_request"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FF9800"
            android:paddingStart="8dp"
            android:paddingEnd="8dp"
            android:text="申请权限"
            android:textColor="#ffffff"
            android:textSize="12sp" />

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/bt_quit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:background="#F44336"
            android:text="退出"
            android:textColor="#ffffff"
            android:textSize="12sp" />

    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true"
        android:overScrollMode="never">

        <LinearLayout
            android:id="@+id/ll_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

</LinearLayout>
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.technology.myapplication.R;
import com.technology.myapplication.utils.LogUtils;
import java.util.ArrayList;
import java.util.List;


public class PermissionActivity extends AppCompatActivity {

    private final String TAG = "PermissionActivity";
    /**
     * 1. 摄像头: android.permission-group.CAMERA
     * android.permission.CAMERA
     * <p>
     * 2.定位:android.permission-group.LOCATION
     * android.permission.ACCESS_FINE_LOCATION
     * android.permission.ACCESS_COARSE_LOCATION
     * <p>
     * 3.麦克风:android.permission-group.MICROPHONE
     * android.permission.RECORD_AUDIO
     * <p>
     * 4.设备相关信息:android.permission-group.PHONE
     * android.permission.READ_PHONE_STATE
     * android.permission.CALL_PHONE
     * android.permission.READ_CALL_LOG
     * android.permission.WRITE_CALL_LOG
     * com.android.voicemail.permission.ADD_VOICEMAIL
     * android.permission.USE_SIP
     * android.permission.PROCESS_OUTGOING_CALLS
     * <p>
     * 5.存储空间:android.permission-group.STORAGE
     * android.permission.READ_EXTERNAL_STORAGE
     * android.permission.WRITE_EXTERNAL_STORAGE
     * <p>
     * 6.传感器: group:android.permission-group.SENSORS
     * permission:android.permission.BODY_SENSORS
     */
    private final String[] mStrings = {
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.WRITE_CALL_LOG,
//            Manifest.permission.ADD_VOICEMAIL,
            Manifest.permission.USE_SIP,
//            Manifest.permission.PROCESS_OUTGOING_CALLS,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.BODY_SENSORS,
            Manifest.permission.CHANGE_WIFI_STATE
//            Manifest.permission.WRITE_SETTINGS
    };


    private LinearLayout mLinearLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);
        mLinearLayout = findViewById(R.id.ll_layout);

        findViewById(R.id.bt_quit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        findViewById(R.id.bt_request).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSystem();
            }
        });


        check();
    }


    private void check() {
        List<String> data = new ArrayList<>();
        for (String permission : mStrings) {
            if (ActivityCompat.checkSelfPermission(PermissionActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
                //没有权限,申请权限
                data.add(permission);

            } else {
                addView(permission, "已经申请过了");
            }
        }

        String[] strings = new String[data.size()];
        data.toArray(strings);
        LogUtils.e(TAG, "需要申请的权限 = " + strings.length);

        //申请权限,其中RC_PERMISSION是权限申请码,用来标志权限申请的
        if (!data.isEmpty()) {
            ActivityCompat.requestPermissions(PermissionActivity.this, strings, 101);
        } else {
            start();
        }
    }

    private void start() {
        LogUtils.e(TAG, "--申请权限完成,调整界面--");
    }

    private void addView(String permission, String title) {
        TextView textView = new TextView(this);
        textView.setPadding(20, 20, 0, 0);
        String s = "失败";
        if (!title.contains(s)) {
            textView.setTextColor(Color.BLACK);
        } else {
            textView.setTextColor(Color.RED);
        }
        textView.setTextSize(16);
        textView.setText(permission + ":" + title);
        mLinearLayout.addView(textView);
    }

    private void startSystem() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", this.getPackageName(), null);
        intent.setData(uri);
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        int code = 101;
        if (requestCode == code) {
            int length = permissions.length;
            int start = 0;
            for (int i = 0; i < length; i++) {
                String permission = permissions[i];
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    //成功
                    LogUtils.e(TAG, "权限申请成功 = " + permission);
                    addView(permission, "权限申请成功");
                    start ++;

                } else {
                    //不成功
                    LogUtils.e(TAG, "权限申请失败 = " + permission);
                    addView(permission, "权限申请失败");
                }
            }

            if (start == length){
                start();
            }
        }
    }

}





【Base封装】
清单文件权限的申请,参考上面
布局代码,参考上面

import android.content.pm.PackageManager;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

public class BasePermissionActivity extends AppCompatActivity {
    public int requestCode = 101;

    public void showToast(String toast) {
        Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
    }


    /**
     * 权限检查
     *
     * @param neededPermissions 需要的权限
     * @return 是否全部被允许
     */
    public boolean checkPermissions(String[] neededPermissions) {
        if (neededPermissions == null) {
            return true;
        }
        boolean allGranted = true;
        for (String permission : neededPermissions) {
            boolean p = ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
            allGranted &= p;
        }
        return allGranted;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (this.requestCode == requestCode) {
            boolean isAllGranted = true;
            for (int grantResult : grantResults) {
                isAllGranted &= (grantResult == PackageManager.PERMISSION_GRANTED);
            }

            if (isAllGranted) {
                permissionsResult();
            } else {
                showToast("权限被拒绝");
            }
        }
    }

    public void permissionsResult() {

    }
}
import android.Manifest;
import android.os.Bundle;
import com.technology.myapplication.utils.LogUtils;


public class PermissionItemActivity extends BasePermissionActivity {
    private final String TAG = "PermissionItemActivity";

    private final String[] mStrings = {
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.WRITE_CALL_LOG,
            Manifest.permission.USE_SIP,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.BODY_SENSORS,
            Manifest.permission.CHANGE_WIFI_STATE
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        boolean p = checkPermissions(mStrings);
        if (p) {
            start();
        } else {
            requestPermissions(mStrings, requestCode);
        }
    }

    @Override
    public void permissionsResult() {
        start();
    }

    private void start() {
        LogUtils.e(TAG, "--申请权限完成,调整界面--");
    }
}



【Kotlin】
清单文件权限的申请,参考上面
布局代码,参考上面

import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.widget.Toast
import androidx.annotation.Nullable
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity

@SuppressLint("Registered")
abstract class BasePermissionActivity : FragmentActivity() {
    protected val requestCode: Int = 101

    fun showToast(@Nullable resId: Int) {
        showToast(getString(resId))
    }

    fun showToast(toast: String) {
        Toast.makeText(this, toast, Toast.LENGTH_LONG).show()
    }

    /**
     * 权限检查
     *
     * @param neededPermissions 需要的权限
     * @return 是否全部被允许
     */
    fun checkPermissions(neededPermissions: Array<String>): Boolean {
        if (neededPermissions.isEmpty()) {
            return true
        }
        var allGranted = true
        for (neededPermission in neededPermissions) {
            val n = ContextCompat.checkSelfPermission(
                this,
                neededPermission
            ) == PackageManager.PERMISSION_GRANTED
            allGranted = allGranted and n
        }
        return allGranted
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        var isAllGranted = true
        for (grantResult in grantResults) {
            isAllGranted = isAllGranted and (grantResult == PackageManager.PERMISSION_GRANTED)
        }
        if (this.requestCode == requestCode) {
            if (isAllGranted) {
                permissionsResult()
            } else {
                showToast("权限被拒绝")
            }
        }
    }

    open fun permissionsResult() {
    }

    companion object {
        private const val TAG = "BasePermissionActivity"
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,817评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,329评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,354评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,498评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,600评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,829评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,979评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,722评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,189评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,519评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,654评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,329评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,940评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,762评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,993评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,382评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,543评论 2 349