Android 8.0通知欄許可權開啟適配
阿新 • • 發佈:2018-11-14
使用手機時,我們經常會碰到各種通知,例如微信,QQ,瀏覽器等等,不厭其煩的給你各種推送,本文將演示通知的大致流程
首先,我們在一個適當的時機檢查我們App的通知欄許可權
boolean Jurisdiction = NotificationManagerCompat.from(AppApplication.getContext()).areNotificationsEnabled();
通過這個方法,我們能夠獲取到我們App是否有通知欄的推送許可權,如果我們沒有許可權就使用引導的方式來告訴使用者我們需要一個這樣的許可權,並提供設定的方式,這裡我使用了第三方material-dialogs開源彈窗框架。最後在彈窗的確認監聽中根據系統版本號使用對應的方式彈出系統許可權管理視窗。當然,你也可以使用你自己的彈窗來提示使用者
依賴如下:
api "com.afollestad.material-dialogs:core:0.9.4.5"
api "com.afollestad.material-dialogs:commons:0.9.4.5"
if (!NotificationManagerCompat.from(AppApplication.getContext()).areNotificationsEnabled()) {
MaterialDialog.Builder builder = new MaterialDialog.Builder(mContext)
.title("請手動將通知開啟" )
.positiveText("確定")
.negativeText("取消");
.onAny(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
if (which == DialogAction.NEUTRAL) {
Log.e("onClick" , "更多資訊: ");
} else if (which == DialogAction.POSITIVE) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
Intent intent = new Intent();
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", MainActivity.this.getPackageName());
intent.putExtra("app_uid", MainActivity.this.getApplicationInfo().uid);
startActivity(intent);
} else if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
startActivity(intent);
} else {
Intent localIntent = new Intent();
localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
localIntent.setData(Uri.fromParts("package", MainActivity.this.getPackageName(), null));
startActivity(localIntent);
}
Log.e("onClick", "同意: ");
} else if (which == DialogAction.NEGATIVE) {
Log.e("onClick", "不同意: ");
}
}
}).show();
}
到此,我們的許可權已經可以保證開啟了。下一篇:發起推送