我不能在android api23中调用一个数字

时间:2017-06-19 16:33:15

标签: android android-activity permissions

我试图拨打一个号码,但是许可检查是假的,所以该方法返回,我什么都没得到。

代码方法:

public void call(String s) {
    Intent callIntent = new Intent(Intent.ACTION_CALL);
    callIntent.setData(Uri.parse("tel:"+s));
    if (ActivityCompat.checkSelfPermission(getBaseContext(),     Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        System.out.println("fout bellen");
        return;
    }
    startActivity(callIntent);
}

每次我点击我的相对布局(点击听众)时,它都会给我system.out.println“fout bellen”

欢迎所有帮助。

1 个答案:

答案 0 :(得分:1)

您必须像这样请求运行时权限。

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

所以你的代码就像这样

private static final int REQUEST_PHONE_CALL = 1;
public void call(String s) {       
    if (ActivityCompat.checkSelfPermission(getBaseContext(),     
        Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
                        this,
                        new String[]{Manifest.permission.CALL_PHONE},
                        REQUEST_PHONE_CALL);
                 return;
    }
    Intent callIntent = new Intent(Intent.ACTION_CALL);
    callIntent.setData(Uri.parse("tel:"+s));
    startActivity(callIntent);
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_PHONE_CALL : {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:"+s));
                startActivity(callIntent);
            }
        }
    }
}