,#情景:
Android 6.0之后。
普通权限在清单文件中添加,危险权限需要动态申请权限。
比如开发中的,SD卡权限的申请,电话的权限,以及读取联系人等方面的权限申请。
如:
Intent.ACTION_DIAL,表示开拨号界面,不需要声明权限。
Intent.ACTION_CALL,是系统内置直接打电话动作,需要声明权限。
代码如下(清单文件也要注明权限CALL_PHONE):
/*
* Copyright (C) 2016, TP-LINK TECHNOLOGIES CO., LTD.
*
* MainCallActivity.java
*
* Description
*
* Author nongzhanfei
*
* Ver 1.0, 12/25/16, NongZhanfei, Create file
*/
package com.tplink.callphone;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainCallActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnMakeCall = (Button) findViewById(R.id.make_call);
btnMakeCall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//进来就检查请求的权限是否被授权了,还未被授权就请求权限。
if (ActivityCompat.checkSelfPermission(MainCallActivity.this,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
requestCallPermission();
} else {
//同意则拨打电话
makeCall();
}
}
private void requestCallPermission() {
//请求的权限的数量(可多个),请求码,(便于区分不同时机的不同的权限请求)。
requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 1);
}
});
}
private void makeCall() {
try {
//普通模式-直接拨打
Intent intent = new Intent(Intent.ACTION_CALL);
//普通电话
intent.setData(Uri.parse("tel:10086"));//如果想直接拨打110需要紧急模式,否这弹出拨号键盘
startActivity(intent);
} catch (SecurityException e) {
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1:
//返回的内容中,我们请求的权限如果经过同意,就可以拨打电话
if (grantResults.length > 0 && grantResults[0] == getPackageManager().PERMISSION_GRANTED) {
makeCall();
} else {
Toast.makeText(this, "yout denied the permission", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
}
如果把10086改成110,那么就不会自动拨号了,只会弹出拨号界面,因为ACTION_CALL代表普通拨号。
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
ACTION_CALL(普通),
ACTION_CALL_EMERGENCY (紧急电话),
ACTION_CALL_PRIVILEGED(系统专属),
而普通应用要拨打电话只能调用ACTION_CALL。
因篇幅问题不能全部显示,请点此查看更多更全内容