Ahm*_*mir 1 java permissions android 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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
}
raf*_*007 17
在您的onClick()方法中尝试此代码
if(isPermissionGranted()){
call_action();
}
Run Code Online (Sandbox Code Playgroud)
现在,要调用创建一个单独的方法:
public void call_action(){
String phnum = etPhoneno.getText().toString();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + phnum));
startActivity(callIntent);
}
Run Code Online (Sandbox Code Playgroud)
为运行时权限检查添加以下两种方法:
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
}
}
Run Code Online (Sandbox Code Playgroud)
还要确保将其添加到清单中:
<uses-permission android:name="android.permission.CALL_PHONE" />
Run Code Online (Sandbox Code Playgroud)
对于碎片
如果您在a中尝试此代码fragment,请更改
checkSelfPermission()
至
ActivityCompat.checkSelfPermission()
并且也改变了
ActivityCompat.requestPermissions()
至
requestPermissions()