我创建了一个简单的 android Activity ,它充当拨号盘。 它有一个电话号码的编辑文本和一个调用按钮 这是代码:(android 6.0 棉花糖)
public class Main2Activity extends AppCompatActivity {
EditText num;
Button call;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
num = (EditText) findViewById(R.id.num);
call = (Button) findViewById(R.id.call);
call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
// request permission if not granted
if (ActivityCompat.checkSelfPermission(Main2Activity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Main2Activity.this, new String[]{Manifest.permission.CALL_PHONE}, 123);
// i suppose that the user has granted the permission
Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + num.getText().toString()));
startActivity(in);
// if the permission is granted then ok
} else {
Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + num.getText().toString()));
startActivity(in);
}
}
// catch the exception if I try to make a call and the permission is not granted
catch (Exception e){
}
}
});
}
当我运行我的应用程序时,我遇到了这些问题
如果我单击调用按钮并授予权限,则在我再次单击之前不会调用 Intent
我不知道如何检查权限是否被授予
最佳答案
使用 onRequestPermissionResult,如果用户按下 ALLOW 和 DENY,它会处理操作,只需在“如果用户按下允许”的条件下调用 Intent :
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 123: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//If user presses allow
Toast.makeText(Main2Activity.this, "Permission granted!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + num.getText().toString()));
startActivity(in);
} else {
//If user presses deny
Toast.makeText(Main2Activity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
希望这对您有所帮助。
关于android - 如何检查用户是否在运行时在 Android 上授予了权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42762308/