public void onClick(View view) {
if (view.getId() == R.id.button && ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
Log.d("STATE", "Call Button DOES NOT WORK");
return;
}
Log.d("STATE", "Call Button DOES WORK");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:480-240-9255"));
startActivity(callIntent);
上面的这段代码不断在控制台中记录它不起作用,但清单文件中有CALL_PHONE的使用权限。我不确定是否需要其他权限,或者代码是否正确?请帮忙,谢谢。
因此,如果存在许可,那没关系,但是如果没有许可,该怎么办?
然后,您需要使用requestPermissions()来请求权限>
类似:-
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, requestCode)
然后,重写onRequestPermissionsResult()方法,在授予权限后执行所需的操作(在这里您可以使用意图拨打电话来开始活动)。
所以您可以执行类似:-
的操作int requestCode = 0;
public void onClick(View view)
{
if (view.getId() == R.id.button && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED)
{
Log.d("STATE", "Call Button DOES NOT WORK");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, requestCode);
return;
}
Log.d("STATE", "Call Button DOES WORK");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:480-240-9255"));
startActivity(callIntent);
}
然后,
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == requestCode)
{
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:480-240-9255"));
startActivity(callIntent);
}
}
因此,此代码将为用户提供一个弹出窗口,说明该设备是否有权拨打或接听电话。如果您授予许可,则将启动呼叫管理器活动。