1. 程式人生 > >Android 6.0許可權問題之Dexter庫的使用

Android 6.0許可權問題之Dexter庫的使用

1.build.gradle中新增

dependencies{
    compile 'com.karumi:dexter:2.2.2'
}

2.application中初始化
public MyApplication extends Application {

    @Override public void onCreate() {
        super.onCreate(); 
        Context context=getApplicationContext();
        Dexter.initialize(context);
    }
}
3.判斷是否為6.0及其以上系統,是則先請求獲取許可權,不是則直接操作

Dexter.isRequestOngoing()   判斷是否之前有許可權請求的操作沒被處理

Dexter.checkPermission(PermissionListener listener, String permission)   請求許可權方法

PermissionListener listener為處理許可權請求的回撥介面,String permission為請求的許可權

if(Build.VERSION.SDK_INT >= 23){
	if (Dexter.isRequestOngoing()) {
             return;
    	}
    	Dexter.checkPermission(ForumFragment.this, Manifest.permission.READ_EXTERNAL_STORAGE);
}else{
	startActivity(new Intent(getActivity(),SendPhotoActivity.class));
}

4.在需要請求許可權操作的類中實現PermissionListener的介面,實現三個方法

使用者允許許可權

    @Override
    public void onPermissionGranted(PermissionGrantedResponse response) {
       
    }
使用者不允許許可權
    @Override
    public void onPermissionDenied(PermissionDeniedResponse response) {
        
    }
 

使用者不允許許可權,向用戶解釋許可權左右

    @Override
    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
    	
    }

完整程式碼:
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.administrator.myannotation.R;
import com.example.administrator.myannotation.activity.SendPhotoActivity;
import com.example.administrator.myannotation.base.BaseFragment;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;

/**
 * Created by admin on 2016/6/22.
 */
public class ForumFragment extends BaseFragment implements PermissionListener{

    FloatingActionButton fab;


    public static ForumFragment getInstance(int s){
        ForumFragment fragment = new ForumFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_forum, container, false);
        setImmerseLayoutColor(view);
        initdata(view);
        return view;
    }

    private void initdata(View view){

        fab=(FloatingActionButton)view.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(getActivity(),SendPhotoActivity.class));
                if(Build.VERSION.SDK_INT >= 23) {
                    //判斷是否有許可權請求沒被處理
                    if (Dexter.isRequestOngoing()) {
                        return;
                    }
                    //請求許可權
                    Dexter.checkPermission(ForumFragment.this, Manifest.permission.READ_EXTERNAL_STORAGE);
                }else{
                    startActivity(new Intent(getActivity(),SendPhotoActivity.class));
                }
            }
        });
    }

    @Override
    public void onPermissionGranted(PermissionGrantedResponse response) {
        startActivity(new Intent(getActivity(),SendPhotoActivity.class));
    }

    @Override
    public void onPermissionDenied(PermissionDeniedResponse response) {
        showDeniedDialog();
    }

    @Override
    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
        showRationaleShouldBeShownDialog(token);
    }

    /**
     * 使用者不允許許可權,向用戶說明許可權的重要性,並支援使用者去設定中開啟許可權
     */
    private void showDeniedDialog(){
        new AlertDialog.Builder(getActivity()).setTitle("請允許獲取儲存空間")
                .setMessage("無法獲取此許可權,不能正常工作")
                .setNegativeButton("拒絕", new DialogInterface.OnClickListener() {
                    @Override public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("去設定", new DialogInterface.OnClickListener() {
                    @Override public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent();
                        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                        intent.setData(Uri.parse("package:"+getActivity().getPackageName()));
                        intent.putExtra("cmp", "com.android.settings/.applications.InstalledAppDetails");
                        intent.addCategory("android.intent.category.DEFAULT");
                        getContext().startActivity(intent);
                        dialog.dismiss();
                    }
                })
                .show();
    }

    /**
     * 使用者不允許許可權,向用戶說明許可權的重要性
     * @param token
     */
    private void showRationaleShouldBeShownDialog(final PermissionToken token){
        new AlertDialog.Builder(getActivity()).setTitle("提示")
                .setMessage("獲取相簿需要儲存空間的許可權,不開啟將無法正常工作!")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        token.cancelPermissionRequest();
                    }
                })
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        token.continuePermissionRequest();
                    }
                })
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override public void onDismiss(DialogInterface dialog) {
                        token.cancelPermissionRequest();
                    }
                })
                .show();
    }
} }

在小米6.0上測試結果:

請求許可權時,彈出系統的請求許可權dialog

1.使用者允許,進入方法onPermissionGranted()

2.使用者不允許,進入方法onPermissionDenied()

   使用者->拒絕,下次請求許可權時直接進入方法onPermissionDenied()

   使用者->去設定,進入該應用的應用資訊,使用者自己開啟許可權

3.使用者允許,之後去應用資訊中關閉許可權,下次請求許可權時進入方法onPermissionRationaleShouldBeShown()

   使用者->確定,彈出系統的請求許可權dialog

   使用者->取消,進入方法onPermissionDenied()