Skip to content

Instantly share code, notes, and snippets.

@tangblack
Last active May 8, 2018 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangblack/54c6e6e3ee31640861308e453614e18f to your computer and use it in GitHub Desktop.
Save tangblack/54c6e6e3ee31640861308e453614e18f to your computer and use it in GitHub Desktop.
rxpermissions_template
public class FooActivity extends AppCompatActivity
{
private static final String TAG = FooActivity.class.getSimpleName();
private static final int REQUEST_PERMISSION_SETTING = 109;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// 省略...
// 每次建立都會要求取得權限。
requestPermissions();
}
private void requestPermissions()
{
RxPermissions rxPermission = new RxPermissions(FooActivity.this);
rxPermission
.requestEachCombined(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO) // 加入你需要的 Runtime 權限。如果沒權限會自動跳出要求權限的對話框。
.subscribe(new Consumer < Permission > () // 只會發射一次結果。
{
@Override
public void accept(Permission permission) throws Exception
{
if (permission.granted)
{
Log.d(TAG, "Path 1: 取得所有權限");
// 確定有權限之後就可以執行需要權限的方法。
doSomeThing();
}
else if (permission.shouldShowRequestPermissionRationale)
{
Log.d(TAG, "Path 2: 其中一個權限被拒絕(沒有勾選不再詢問)");
// 重新要求取得權限。
requestPermissions();
}
else
{
Log.d(TAG, "Path 3: 其中一個權限被拒絕(曾經在對話框勾選不再詢問)");
// 被勾選不再詢問就不會跳出要求權限的對話框,這邊要引導至設定頁面請使用者手動打開權限。
// 如果流程不想哪麼粗糙,也可以自己做一個對話框顯示詳細資訊,並提供一個按鈕跳到設定頁面。
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// Path 3.1: 處理設定頁面跳轉回來的流程,這就就是再檢查一次權限。
if (requestCode == REQUEST_PERMISSION_SETTING)
{
// 重新要求取得權限。
requestPermissions();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment