安卓8.0後通知欄Notification【判斷APP通知欄許可權是否開啟,以及關閉了通知許可權後設置或者自定義通...
前言
當APP有推送功能時,需要判斷當前app在手機中是否開啟了允許訊息推送,否則即使添加了推送程式碼仍然收不到通知,所以需要要麼跳轉至設定介面設定,要麼自定義訊息通知。
效果圖

方法一:跳轉到應用程式設定介面
1、將NotificationSetUtil.java類複製到專案中
package com.php.project.notificationsetutildemo.utils; import android.app.AppOpsManager; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.net.Uri; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v4.app.NotificationManagerCompat; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Created by peihp * Used 判斷是否開啟訊息通知,沒有開啟的話跳轉到手機系統設定介面 */ public class NotificationSetUtil { //判斷是否需要開啟設定介面 @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static void OpenNotificationSetting(Context context, OnNextLitener mOnNextLitener) { if (!isNotificationEnabled(context)) { gotoSet(context); } else { if (mOnNextLitener != null) { mOnNextLitener.onNext(); } } } //判斷該app是否打開了通知 /** * 可以通過NotificationManagerCompat 中的 areNotificationsEnabled()來判斷是否開啟通知許可權。NotificationManagerCompat 在 android.support.v4.app包中,是API 22.1.0 中加入的。而 areNotificationsEnabled()則是在 API 24.1.0之後加入的。 * areNotificationsEnabled 只對 API 19 及以上版本有效,低於API 19 會一直返回true * */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static boolean isNotificationEnabled(Context context) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context); boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled(); return areNotificationsEnabled; } String CHECK_OP_NO_THROW = "checkOpNoThrow"; String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION"; AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); ApplicationInfo appInfo = context.getApplicationInfo(); String pkg = context.getApplicationContext().getPackageName(); int uid = appInfo.uid; Class appOpsClass = null; /* Context.APP_OPS_MANAGER */ try { appOpsClass = Class.forName(AppOpsManager.class.getName()); Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class); Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION); int value = (Integer) opPostNotificationValue.get(Integer.class); return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED); } catch (Exception e) { e.printStackTrace(); } return false; } //開啟手機設定頁面 /** * 假設沒有開啟通知許可權,點選之後就需要跳轉到 APP的通知設定介面,對應的Action是:Settings.ACTION_APP_NOTIFICATION_SETTINGS, 這個Action是 API 26 後增加的 * 如果在部分手機中無法精確的跳轉到 APP對應的通知設定介面,那麼我們就考慮直接跳轉到 APP資訊介面,對應的Action是:Settings.ACTION_APPLICATION_DETAILS_SETTINGS*/ private static void gotoSet(Context context) { Intent intent = new Intent(); if (Build.VERSION.SDK_INT >= 26) { // android 8.0引導 intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS"); intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName()); } else if (Build.VERSION.SDK_INT >= 21) { // android 5.0-7.0 intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS"); intent.putExtra("app_package", context.getPackageName()); intent.putExtra("app_uid", context.getApplicationInfo().uid); } else { // 其他 intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); intent.setData(Uri.fromParts("package", context.getPackageName(), null)); } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } /*=====================新增Listener回撥================================*/ public interface OnNextLitener { /** * 不需要設定通知的下一步 */ void onNext(); } private OnNextLitener mOnNextLitener; public void setOnNextLitener(OnNextLitener mOnNextLitener) { this.mOnNextLitener = mOnNextLitener; } }
使用方法:
package com.php.project.notificationsetutildemo; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import com.php.project.notificationsetutildemo.utils.NotificationSetUtil; public class MainActivity extends AppCompatActivity { private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //判斷是否需要開啟通知欄功能 NotificationSetUtil.OpenNotificationSetting(mContext, new NotificationSetUtil.OnNextLitener() { @Override public void onNext() { Toast.makeText(mContext,"已開啟通知許可權",Toast.LENGTH_SHORT).show(); } }); } } }
新建Toast.java
package com.php.utils.ui.toast; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AppOpsManager; import android.app.Application; import android.content.Context; import android.content.pm.ApplicationInfo; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v4.app.NotificationManagerCompat; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import java.lang.reflect.Field; import java.lang.reflect.Method; import com.php.notification.R; public class Toast { private static final String CHECK_OP_NO_THROW = "checkOpNoThrow"; private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION"; private static int checkNotification = 0; private static Object mToast; private static boolean flag = true; private Toast(Context context, String message, int duration) { if(context instanceof Application) checkNotification = 0; else checkNotification = isNotificationEnabled(context) ? 0 : 1; if (checkNotification == 1) { try { mToast = EToast2.makeText(context, message, duration); } catch (Exception e) { e.printStackTrace(); synchronized (CHECK_OP_NO_THROW) { if(flag){ flag = false; View toastRoot = LayoutInflater.from(context).inflate(R.layout.toast, null); TextView tv = (TextView) toastRoot.findViewById(R.id.toast_notice); tv.setText(message); mToast = android.widget.Toast.makeText(context,"",duration); ((android.widget.Toast) mToast).setView(toastRoot); ((android.widget.Toast) mToast).setGravity(Gravity.BOTTOM, 0, 200); } } ((TextView)((android.widget.Toast) mToast).getView().findViewById(R.id.toast_notice)).setText(message); } } else { // mToast = android.widget.Toast.makeText(context, message, duration); synchronized (CHECK_OP_NO_THROW) { if(flag){ flag = false; View toastRoot = LayoutInflater.from(context).inflate(R.layout.toast, null); TextView tv = (TextView) toastRoot.findViewById(R.id.toast_notice); tv.setText(message); mToast = android.widget.Toast.makeText(context,"",duration); ((android.widget.Toast) mToast).setView(toastRoot); ((android.widget.Toast) mToast).setGravity(Gravity.BOTTOM, 0, 200); } } ((TextView)((android.widget.Toast) mToast).getView().findViewById(R.id.toast_notice)).setText(message); } } private Toast(Context context, int resId, int duration) { if(context instanceof Application) checkNotification = 0; else checkNotification = isNotificationEnabled(context) ? 0 : 1; if (checkNotification == 1 && context instanceof Activity) { mToast = EToast2.makeText(context, resId, duration); } else { mToast = android.widget.Toast.makeText(context, resId, duration); } } public static Toast makeText(Context context, String message, int duration) { return new Toast(context,message,duration); } public static Toast makeText(Context context, int resId, int duration) { return new Toast(context,resId,duration); } public void show() { if(mToast instanceof EToast2){ ((EToast2) mToast).show(); }else if(mToast instanceof android.widget.Toast){ ((android.widget.Toast) mToast).show(); } } public void cancel(){ if(mToast instanceof EToast2){ ((EToast2) mToast).cancel(); }else if(mToast instanceof android.widget.Toast){ ((android.widget.Toast) mToast).cancel(); } } //判斷該app是否打開了通知 /** * 可以通過NotificationManagerCompat 中的 areNotificationsEnabled()來判斷是否開啟通知許可權。NotificationManagerCompat 在 android.support.v4.app包中,是API 22.1.0 中加入的。而 areNotificationsEnabled()則是在 API 24.1.0之後加入的。 * areNotificationsEnabled 只對 API 19 及以上版本有效,低於API 19 會一直返回true * */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) @SuppressLint("NewApi") private static boolean isNotificationEnabled(Context context){ if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT){ NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context); boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled(); return areNotificationsEnabled; } AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); ApplicationInfo appInfo = context.getApplicationInfo(); String pkg = context.getApplicationContext().getPackageName(); int uid = appInfo.uid; Class appOpsClass = null; //* Context.APP_OPS_MANAGER *//* try { appOpsClass = Class.forName(AppOpsManager.class.getName()); Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class); Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION); int value = (int)opPostNotificationValue.get(Integer.class); return ((int)checkOpNoThrowMethod.invoke(mAppOps,value, uid, pkg) == AppOpsManager.MODE_ALLOWED); } catch (Exception e) { e.printStackTrace(); } return false; } }
新建EToast2.java檔案:
package com.php.utils.ui.toast; import android.content.Context; import android.graphics.PixelFormat; import android.os.Handler; import android.os.Message; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import java.util.Timer; import java.util.TimerTask; import com.php.notification.R; public class EToast2 { private WindowManager manger; private Long time = 2000L; private View contentView; private WindowManager.LayoutParams params; private static Timer timer; private Toast toast; private static Toast oldToast; private static Context context; public static final int LENGTH_SHORT = 0; public static final int LENGTH_LONG = 1; private static Handler handler; private CharSequence text; private View toastRoot; private EToast2(Context context, CharSequence text, int HIDE_DELAY){ this.text = text; if(HIDE_DELAY == EToast2.LENGTH_SHORT) this.time = 2000L; else if(HIDE_DELAY == EToast2.LENGTH_LONG) this.time = 3500L; if(oldToast != null && EToast2.context != null && EToast2.context != context){ EToast2.context = context; oldToast.cancel(); oldToast = null; } if(oldToast == null){ LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); toastRoot = inflate.inflate(R.layout.toast, null); TextView tv = (TextView) toastRoot.findViewById(R.id.toast_notice); tv.setText(text); toast = Toast.makeText(context,"",HIDE_DELAY); toast.setView(toastRoot); toast.setGravity(Gravity.BOTTOM, 0, 200); contentView = toastRoot; params = new WindowManager.LayoutParams(); params.height = WindowManager.LayoutParams.WRAP_CONTENT; params.width = WindowManager.LayoutParams.WRAP_CONTENT; params.format = PixelFormat.TRANSLUCENT; params.windowAnimations = context.getResources().getIdentifier("android:style/Animation.Toast", null, null); params.type = WindowManager.LayoutParams.TYPE_TOAST; params.setTitle("EToast2"); params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM; params.y = 200; } if(handler == null){ handler = new Handler(){ @Override public void handleMessage(Message msg) { EToast2.this.cancel(); } }; } } public static EToast2 makeText(Context context, String text, int HIDE_DELAY){ EToast2 toast = new EToast2(context, text, HIDE_DELAY); return toast; } public static EToast2 makeText(Context context, int resId, int HIDE_DELAY) { return makeText(context,context.getText(resId).toString(),HIDE_DELAY); } public void show(){ if(oldToast == null){ oldToast = toast; Context context = contentView.getContext().getApplicationContext(); if (context == null) { context = contentView.getContext(); } manger = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); manger.addView(contentView, params); }else{ if(timer != null){ timer.cancel(); } ((TextView)(oldToast).getView().findViewById(R.id.toast_notice)).setText(text); } timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { handler.sendEmptyMessage(1); } }, time); } public void cancel(){ try { manger.removeView(contentView); } catch (IllegalArgumentException e) { //這邊由於上下文被銷燬後removeView可能會丟擲IllegalArgumentException //暫時這麼處理,因為EToast2是輕量級的,不想和Context上下文的生命週期繫結在一塊兒 //其實如果真的想這麼做,可以參考博文2的第一種實現方式,新增一個空的fragment來做生命週期繫結 } timer.cancel(); oldToast.cancel(); timer = null; toast = null; oldToast = null; contentView = null; handler = null; } }
toast.xml檔案:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/toast_bg"> <TextView android:id="@+id/toast_notice" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:gravity="center_vertical" android:background="@color/transparent" android:textSize="18sp" android:padding="7dp" android:textColor="@color/white"> </TextView> </LinearLayout>
使用方法:
/** * 提示窗 * * @param context * @param mes */ public static void promptMes(Context context, String mes) { com.php.utils.ui.toast.Toast.makeText(context, mes, Toast.LENGTH_SHORT).show(); }
歡迎大家關注本人公眾號,一起學習進步,謝謝!
