Android通知相关

有些手机默认不开启通知权限,需要我们自己来检测和提示用户开启。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private void enableNotificationPermission(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
if (Uapp.isNotificationEnabled(context)) {
return;
}

final String KEY_SP_CLOSE_NOTIFICATION = "KEY_SP_CLOSE_NOTIFICATION";
if (Usp.init(context).getBoolean(KEY_SP_CLOSE_NOTIFICATION, false)) {
return;
}
new AlertDialog.Builder(context,
android.R.style.Theme_DeviceDefault_Light_Dialog)
.setTitle("友情提示").setMessage("为了给您提供更好的服务,请开启应用通知权限")
.setNegativeButton("不用了", (dialog, which) -> Usp.init(context)
.putBoolean(KEY_SP_CLOSE_NOTIFICATION, true)
.commit())
.setNeutralButton("下次再说", (dialog, which) -> {
// do nothing
})
.setPositiveButton("去开启", (dialog, which) -> {
Uapp.openAppDetailSettings(context);
})
.setCancelable(false)
.create()
.show();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class Uapp {
/**
* 判断是否开启通知权限
* (https://blog.csdn.net/reglog/article/details/79863751)
*
* @param context
* @return
*/
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@SuppressWarnings("unchecked")
public static boolean isNotificationEnabled(Context context) {
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;

/* Context.APP_OPS_MANAGER */
try {
Class 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设置界面
public static void openAppDetailSettings(Context context) {
//跳转设置界面
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= 9) {
intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.fromParts("package", context.getPackageName(), null));
} else if (Build.VERSION.SDK_INT <= 8) {
intent.setAction(Intent.ACTION_VIEW);
intent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
}

context.startActivity(intent);
}
}