实际上,没有办法以编程方式打开/关闭通知,我们可以使用以下代码执行此操作的唯一方法这将在 oreo 版本以下工作,因为 android 已限制以编程方式控制显示通知
public class CustomNotificationcontroller {
private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
public static void makeText(Context mContext, String message, int time) {
if (isNotificationEnabled(mContext)) {
Toast.makeText(mContext, message, time).show();
} else {
showCustomAlertDialog(mContext, message);
}
}
private static boolean isNotificationEnabled(Context mContext) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
AppOpsManager mAppOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
ApplicationInfo appInfo = mContext.getApplicationInfo();
String pkg = mContext.getApplicationContext().getPackageName();
int uid = appInfo.uid;
Class appOpsClass;
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 (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException
| InvocationTargetException | IllegalAccessException ex) {
}
return false;
} else {
return false;
}
}
private static void showCustomAlertDialog(Context mContext, String message) {
if (!(mContext instanceof Activity && ((Activity)mContext).isFinishing())) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(mContext);
mBuilder.setMessage(message);
mBuilder.setPositiveButton(mContext.getString(R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mBuilder.setCancelable(true);
AlertDialog alertDialog = mBuilder.create();
alertDialog.show();
}
}}
对于奥利奥,您可以直接 为此使用隐式意图
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null);
startActivityForResult(intent, 5);