总是产生异常

时间:2016-05-21 16:34:39

标签: java android android-studio android-6.0-marshmallow

private void call() 
{
    intent in=new Intent(Intent.ACTION_CALL,Uri.parse("9424863135"));
    try
    {
        startActivity(in);
    }
    catch (android.content.ActivityNotFoundException ex)
    {
        Toast.makeText(getApplicationContext(),"yourActivity is not founded",Toast.LENGTH_SHORT).show();
    }
}

每当我在模拟器(任何版本)或实际设备中运行此代码时,它总是抛出异常并显示消息。 经过一些研究后,似乎需要api 23中的运行时权限,所以我在api 22和api 15设备中运行代码仍然问题仍在继续。 任何解决方案?

2 个答案:

答案 0 :(得分:1)

您似乎正在尝试拨打电话号码。 如果是这样,你的意图是错误的。

URI应以tel:为前缀,

intent in=new Intent(Intent.ACTION_CALL,Uri.parse("tel:9424863135"));

答案 1 :(得分:0)

是的,在api 23中,您需要获得运行时许可才能拨打电话。 要知道如何询问运行时权限,请检查此链接Android developer page

点击按钮点击拨打此代码:

 if (!(Build.VERSION.SDK_INT < Build.VERSION_CODES.M)) {
                checkCallingPermission();
            } else {
                //call your method to make call
                call();
            }

检查Android M +权限的方法:

private void checkCallingPermission() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CALL_PHONE)) {
            Toast.makeText(ContactUsActivity.this, "Permission is needed for proper working of this app", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE_CALL);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE_CALL);
        }

    } else {
        call();
    }
}

并像这样处理回调结果:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_CODE_CALL) {
        if (grantResults.length == 1
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            call();
        } else {
            Toast.makeText(ContactUsActivity.this, "Permission is needed for proper working of this app", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE_CALL);
        }
    }
}

这将是拨打电话的方法

private void call() {
    String url = "tel:" + "12234455";
    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
    startActivity(intent);
}