欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android--权限机制

程序员文章站 2022-05-14 21:13:46
...

本人最近坠入小米,置得一枚红米note5,这手机啊,家家都有难念的经,小米要想调试,就得需要在开发者选项中,开启开发者权限、开启USB调试模式、开启USB安装

调试Run开发遇到的错误提示:
Unknown failure (at android.os.Binder.execTransact(Binder.java:565))Error while Installing APKs
解决:在Android Studio中File–>Settings–>Instant Run 取消勾选Enable Instant Run to hot…..

动态权限思路:
在使用某些需要权限的业务时,判断是否有权限,有则进行,无则进行动态权限选择

package com.study.test.testapplication.acty;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.study.test.testapplication.R;

public class PermissionActivity extends AppCompatActivity {

    private Button callBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);

        init();
        callBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(PermissionActivity.this, "Call Phone", Toast.LENGTH_SHORT).show();

//              需要权限的地方 需要判断 如果没有则进行动态获取权限,有就进行事务
                if (ActivityCompat.checkSelfPermission(PermissionActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    ActivityCompat.requestPermissions(PermissionActivity.this,new String[]{Manifest.permission.CALL_PHONE},1);
                    return;
                }else{
                    callPhone();
                }

            }
        });

    }

    private void init() {

        callBtn = findViewById(R.id.make_call);

    }

//  事务方法
    private void callPhone(){
        try {
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:10010"));
            startActivity(intent);
        }catch (SecurityException e){
            e.printStackTrace();
        }
    }

//  动态获取
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    callPhone();
                }else{
                    Toast.makeText(PermissionActivity.this, "you need access callphone permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
}
相关标签: Android Permission