Android动态申请权限(打电话)
android 高版本有些权限除了在manifest文件中静态添加,还需要动态请求 具体请求方法如下(以拨打电话为例):
方法1:
这种方法是直接呼出电话
- 在manifest文件中添加权限
<uses-permission android:name="android.permission.CALL_PHONE"/>
- Java代码动态请求【xml代码就只有一个Button,所以就不列出了】
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MoreInfoActivity extends AppCompatActivity {
private static final String TAG = "MoreInfoActivity";
private Button mBtnPhone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_more_info);
initView();
mBtnPhone.setOnClickListener(v -> {
request_permission();
});
}
private void request_permission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CALL_PHONE},10010);
Log.d(TAG, "request_permission():正在申请权限!");
}else {
Log.d(TAG, "request_permission():已经拥有权限!");
callUp();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 10010:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
callUp();
Log.d(TAG, "onRequestPermissionsResult(): 获取权限,可以拨打电话!");
}else {
Log.d(TAG, "onRequestPermissionsResult(): 权限已拒绝!");
}
break;
}
}
private void callUp() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + "10010"));
startActivity(intent);
}
private void initView() {
mBtnPhone = findViewById(R.id.btn_phone);
}
}
方法2:
这种方法只是调用拨打电话,输入电话号,并不呼出
- 在manifest文件中添加权限
<uses-permission android:name="android.permission.CALL_PHONE" />
- java代码
直接在按钮的点击事件中添加即可
private void callUp(String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + phoneNumber));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
|