Android 动态权限封装

PermissionActivity
package com.example.appdemo;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;


public class  PermissionActivity extends AppCompatActivity  {
    private OnPermissionListener permissionListener = null;
   
    /**
     * 权限的封装
     *
     *
     */

    public boolean hasPemsiom(String[] strings) {
        if (Build.VERSION.SDK_INT <23) {
            return true;
        }
        for (String string : strings) {
            if (ContextCompat.checkSelfPermission(this, string) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }else {
                return true;
            }

        }
        return true;
    }

    /**
     * 请求权限
     */

    public void request(int code,OnPermissionListener onPermissionListener,String...strings){
        if (strings == null || onPermissionListener == null) {
            return;
        }
        this.permissionListener = onPermissionListener;
        if (Build.VERSION.SDK_INT < 23 || strings.length == 0) {
            onPermissionListener.onGranted();
        }else {
            if(hasPemsiom(strings)){
                onPermissionListener.onGranted();
            }else {
                ActivityCompat.requestPermissions(this,strings,code);
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode != 1) {
            return;
        }
        if (grantResults.length == 0) {
            return;
        }
        int length = permissions.length;
        //循环判断授权结果
        for (int i = 0; i < length; i++) {
            //授权成功
            if (grantResults[i] == getPackageManager().PERMISSION_GRANTED) {
                continue;
            }
            //用户勾选了"不再提醒",会返回false,需引导用户手动开启权限
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                showReqPermissionDialog();
            } else {
                //request(1, permissionListener,permissions);
                permissionListener.onDenied();
            }
            return;
        }
        permissionListener.onGranted();
    }

    /**
     * 提示用户手动开启权限
     */
    private void showReqPermissionDialog() {
        new AlertDialog.Builder(this)
                .setMessage("需要开启权限才能使用此功能")
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        goToAppInfo();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.cancel();
                       // permissionListener.onDenied();
                    }
                })
                .create()
                .show();
    }

    /**
     * 跳转系统的App应用信息页面
     */
    protected void goToAppInfo() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        startActivity(localIntent);
    }


}

测试类

package com.example.appdemo;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Main2Activity extends RoomActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button btnPic = new Button(this);
        btnPic.setText("拍照");
        Button btnCall = new Button(this);
        btnCall.setText("打电话");
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.addView(btnPic);
        ll.addView(btnCall);
        setContentView(ll);
        btnPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                request(1, new OnPermissionListener() {
                    @Override
                    public void onGranted() {
                        tackPic();
                    }

                    @Override
                    public void onDenied() {

                        Toast.makeText(Main2Activity.this, "请允许添加权限", Toast.LENGTH_SHORT).show();
                    }
                }, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA});

            }
        });




    }



    private void tackPic() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void call() {
        try {
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri uri = Uri.parse("tel:" + "10010");
            intent.setData(uri);
            startActivity(intent);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }
}

 

你可能感兴趣的:(Android 动态权限封装)