Android—檢測許可權並申請
阿新 • • 發佈:2018-12-13
private Button btn_enter; private final static int REQUEST_CODE_STORAGE = 1; private SharedPreferences sp; private String[] PERMISSIONS_STORAGE = { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_index); btn_enter = findViewById(R.id.btn_enter); btn_enter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Enter(); } }); //ButterKnife.bind(this); sp = getSharedPreferences("myStore", Context.MODE_PRIVATE); boolean isFirst = sp.getBoolean("isFirst",true); if(!isFirst){ Enter(); } verifyStoragePermission(this); } // @OnClick(R.id.btn_enter) public void Enter(){ Toast.makeText(this,"Enter方法",Toast.LENGTH_LONG).show(); sp.edit().putBoolean("isFirst",false).commit(); startActivity(new Intent(this,MainActivity.class)); finish(); } private void verifyStoragePermission(Activity activity) { //1.檢測許可權 int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PermissionChecker.PERMISSION_GRANTED) { //2.沒有許可權,彈出對話方塊申請 ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_CODE_STORAGE); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults[0] == PermissionChecker.PERMISSION_GRANTED) { //許可權申請成功 Toast.makeText(this, "授權SD卡許可權成功", Toast.LENGTH_SHORT).show(); } else { //許可權申請失敗 Toast.makeText(this, "授權SD卡許可權失敗,可能會影響使用", Toast.LENGTH_SHORT).show(); } }