Java-Android day09

Android Day06

by 木石溪
dev 1.0

border="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=420400344&auto=1&height=66">

Abstract:

  • This article record a simple demo, which is used for request permission to access sensitive user data( photo, contacts, etc), as well as certain feature of system(camera, photo, etc.).
  • In the Android version under 6.0, you only should add the permission to your AndroidManifest.xml file as below:
		// The example is a permission for send sms.
 	<uses-permission android:name="android.permission.SEND_SMS"/>
  • however, in the version 6.0 (API level 23) or higher, and the app’s targetSdkVersion 23 or higher, carefully, you also should add the run-time permission in your MainActivity.java file.

run-time permission demo

package cn.angry.rabbit;

import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class BaseActivity extends AppCompatActivity {
    /* ************ Android M Permission ************ */
    private int permissionRequestCode = 88;
    private PermissionCallback permissionRunnable;

	// the permission-requested-call-back interface
    public interface PermissionCallback {
        void hasPermission();
        void noPermission();
    }

    /**
     * Android M run-timr permission demo
     *
     * @param permissionDes 	permission description
     * @param runnable      	request permission call back
     * @param permissions   	permission you request,you can get from manifest(such as Manifest.permission.WRITE_CONTACTS)
     */
     
     // This is the core of the request-permission demo, it is used both for version < 6.0 and run-time permission
    public void performCodeWithPermission(@NonNull String permissionDes, PermissionCallback runnable, @NonNull String... permissions) {
        if (permissions == null || permissions.length == 0)
            return;
            
        this.permissionRunnable = runnable;
        
        // this is used for android version < 6.0(API < 23), and targetSdkVersion < 23
        
        if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.M) || checkPermissionGranted(permissions)) {
            if (permissionRunnable != null) {
                permissionRunnable.hasPermission();
                permissionRunnable = null;
            }
        } 
        
		// this is used for call the function of requesting permission, when the permission has not been granted
		else {
            requestPermission(permissionDes, permissionRequestCode, permissions);
        }
    }

	// this function is used for checking the permission the app requested.
    private boolean checkPermissionGranted(String[] permissions) {
        boolean flag = true;
        for (String p : permissions) {
            if (ActivityCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED) {
                flag = false;
                break;
            }
        }
        return flag;
    }

	// this function is used for requesting the permission
    /*
     *Provide an additional rationale to the user if the permission was not granted 
    	and the user would benefit from additional context for the use of the permission.
	 * In the first time,if user chosed the "deny", the function of "shouldShowRequestPermissionRationale()"  will return a "true";
     * In the second time,if user chosed the "deny" and "Never ask again", the "shouldShowRequestPermissionRationale()" will return a "false";
     * The user declined the permission app requested, "shouldShowRequestPermissionRationale()" will return a "false";
     */
  
    private void requestPermission(String permissionDes, final int requestCode, final String[] permissions) {
        if (shouldShowRequestPermissionRationale(permissions)) {
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage(permissionDes)
                    .setPositiveButton("授权", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(BaseActivity.this, permissions, requestCode);
                        }
                    }).show();

        } else {
            // requested permissions have not been granted yet. Request them directly.
            ActivityCompat.requestPermissions(BaseActivity.this, permissions, requestCode);
        }
    }

    private boolean shouldShowRequestPermissionRationale(String[] permissions) {
        boolean flag = false;
        for (String p : permissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, p)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == permissionRequestCode) {
            if (verifyPermissions(grantResults)) {
                if (permissionRunnable != null) {
                    permissionRunnable.hasPermission();
                    permissionRunnable = null;
                }
            } else {
                Toast.makeText(this, "暂无权限执行相关操作!", Toast.LENGTH_SHORT).show();
                if (permissionRunnable != null) {
                    permissionRunnable.noPermission();
                    permissionRunnable = null;
                }
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

	// this is function for verifing the permission app requested.
    public boolean verifyPermissions(int[] grantResults) {
        // At least one result must be checked.
        if (grantResults.length < 1) {
            return false;
        }

        // Verify that each required permission has been granted, otherwise return false.
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    //********************** END Android M Permission ****************************************
}

Usage

You only need add the Baseactivity.java to the package of project, and add following sentence to AndroidManifest.xml

		<activity android:name=".BaseActivity"></activity>

12


A simple example

This is a simple example of sending SMS, and in it, you will get the following points:

  • How to use the demo of request permission

the demo of request-permission and example

permission request demo

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值