android请求运行时调用操作的权限

时间:2017-02-05 20:40:11

标签: java android permissions runtime

我有调用操作的代码,我需要最好的方式来声明运行时权限我尝试了很多代码,但我总是得到错误

这是我的基本代码,任何使其适用于运行时权限的建议 提前谢谢

public class MainActivity extends Activity {

private Button button;
private EditText etPhoneno;

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.buttonCall);
    etPhoneno = (EditText) findViewById(R.id.editText1);
    // add button listener
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
                String phnum = etPhoneno.getText().toString();
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:" + phnum));
                startActivity(callIntent);
        }
    });
}

}

1 个答案:

答案 0 :(得分:15)

onClick()方法

中试用此代码
if(isPermissionGranted()){
     call_action();
}

现在,要调用创建一个单独的方法:

public void call_action(){
    String phnum = etPhoneno.getText().toString();
    Intent callIntent = new Intent(Intent.ACTION_CALL);
    callIntent.setData(Uri.parse("tel:" + phnum));
    startActivity(callIntent);
   }

为运行时权限检查添加以下两种方法:

 public  boolean isPermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.CALL_PHONE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("TAG","Permission is granted");
            return true;
        } else {

            Log.v("TAG","Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v("TAG","Permission is granted");
        return true;
    }
}


 @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {

        case 1: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
                call_action();
            } else {
                Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
 }

还要确保将其添加到清单中:

<uses-permission android:name="android.permission.CALL_PHONE" />

FOR FRAGMENT

如果您在 fragment 中尝试此代码,请更改

checkSelfPermission()

ActivityCompat.checkSelfPermission()

并且还要改变

ActivityCompat.requestPermissions()

<强> requestPermissions()