Android 6.0加入了动态权限,权限有普通权限和危险权限两种,其中危险权限在6.0以上的手机是需要动态添加权限的,举例:拨打10086
//-----------------布局文件---------------
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="拨打10086"
android:onClick="button"/>
//-----------清单文件中添加权限----------------------------
<uses-permission android:name="android.permission.CALL_PHONE" />
//-----------------Activity中----------------------------------------
package dongtaiquanxian.bwie.com.dongtaiquanxian;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void button(View view){
// 判断环境兼容,检查自己的权限,是否被同意
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){
//如果不同意,就去请求权限 参数1:上下文,2:权限,3:请求码
ActivityCompat.requestPermissions(MainActivity.this,new String []{Manifest.permission.CALL_PHONE},1);
}else {
//同意就拨打
call();
}
}
private void call() {
Intent intent=new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:10086"));
try {
startActivity(intent);
} catch (Exception 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]==PackageManager.PERMISSION_GRANTED){
call();
}else{
Toast.makeText(this,"哈哈哈",Toast.LENGTH_SHORT).show();
}
break;
}
}
}
//------------就这么简单-----------------