呼叫权限不工作-如何在Android Studio应用中拨打电话?

4ioopgfo  于 2022-11-27  发布在  Android
关注(0)|答案(1)|浏览(219)
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的使用权限。我不确定我需要的任何其他权限,或者代码不正确?

4smxwvx5

4smxwvx51#

所以,如果有权限,那就没问题,但如果没有权限呢?
然后,您需要使用requestPermissions()请求权限
类似于:

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, requestCode)

然后,重写方法onRequestPermissionsResult(),以在授予权限后执行所需的操作(在这里,您可以使用Intent启动Activity以拨打电话)。
所以你可以这样做:-

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);
}
 }

因此,此代码将向用户提供一个弹出窗口,说明该设备是否具有拨打或接听电话的权限。如果您授予权限,则将启动呼叫管理器活动。

相关问题