Android 关于推送通知还需要一些其他的设置问题
程序员文章站
2022-07-03 16:54:21
1.开启通知权限//开启通知权限 private void checkNotifySetting() { boolean isOpened = NotificationUtils.isNotificationEnabled(this); if (isOpened) { LogUtil.d(LogUtil.L, "通知权限已经被打开" + "\n手机型号:" + android.os.Build.MO...
1.开启通知权限
//开启通知权限
private void checkNotifySetting() {
boolean isOpened = NotificationUtils.isNotificationEnabled(this);
if (isOpened) {
LogUtil.d(LogUtil.L, "通知权限已经被打开" +
"\n手机型号:" + android.os.Build.MODEL +
"\nSDK版本:" + android.os.Build.VERSION.SDK +
"\n系统版本:" + android.os.Build.VERSION.RELEASE +
"\n软件包名:" + getPackageName());
} else {
LogUtil.d(LogUtil.L, "还没有开启通知权限,点击去开启");
SaveUtil.saveNotiyPression(false);
openNotifyDialog();
}
}
private void openNotifyDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity2.this);
LayoutInflater inflater = LayoutInflater.from(
MainActivity2.this);
View v = inflater.inflate(R.layout.layout_notif_dialog, null);
TextView tvMessage = v.findViewById(R.id.tv_message);
tvMessage.setText(R.string.label_notiy_message);
Button btnCancel = v.findViewById(R.id.btn_cancel);
Button btnSubmit = v.findViewById(R.id.btn_submit);
btnCancel.setText(R.string.label_notiy_cancel);
btnSubmit.setText(R.string.label_notiy_submit);
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getWindow().setContentView(v);
dialog.getWindow().setGravity(Gravity.CENTER);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
NotificationUtils.openPush(MainActivity2.this);
}
});
}
NotificationUtils 通知类
/**
* desc:通知生成类
*/
public class NotificationUtils extends ContextWrapper {
/**
* 通知管理对象
*/
private NotificationManager notificationManager;
/**
* channel的ID
*/
public static final String id = "channel_id";
/**
* channel的名称
*/
public static final String name = "channel_name";
/**
* notification id
*/
public static final int notification_id = 1;
//最多显示3条通知
public int NOTIFICATION_SHOW_SHOW_AT_MOST = 3;
/**
* 通知生成类的构造方法
*/
public NotificationUtils(Context context) {
super(context);
initWindowManager(context);
}
private WindowManager.LayoutParams mWindowParams;
private WindowManager mWindowManager;
private void initWindowManager(Context context) {
mWindowParams = new WindowManager.LayoutParams();
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (Build.VERSION.SDK_INT >= 26) {//8.0新特性
mWindowParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
mWindowParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
}
}
/**
* 模拟发送一个普通通知
*
* @param iconRes
* @param title
* @param content
* @param pendingIntent
*/
public void sendNotification(int iconRes, String title, String content, PendingIntent pendingIntent) {
// int num = SaveUtil.getNotiyNum();
// num++;
// SaveUtil.saveNotiyNum(num);
// //通知条数<10
// if (SaveUtil.getNotiyNum() > NOTIFICATION_SHOW_SHOW_AT_MOST) {
// SaveUtil.saveNotiyNum(1);
// }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//26及以上
createNotificationChannel();
Notification notification = getChannelNotification(iconRes, title, content, pendingIntent).build();
notificationManager.notify(notification_id, notification);
// notificationManager.notify(SaveUtil.getNotiyNum(), notification);
} else {
getNotificationManager();
Notification notification = getNotification(iconRes, title, content, pendingIntent).build();
notificationManager.notify(notification_id, notification);
// notificationManager.notify(SaveUtil.getNotiyNum(), notification);
}
}
/**
* 创建NotificationChannel
*/
public void createNotificationChannel() {
NotificationChannel notificationChannel = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// notificationChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);
// notificationChannel.canBypassDnd();//可否绕过请勿打扰模式
// notificationChannel.canShowBadge();//桌面lanchener显示角标
// notificationChannel.enableLights(true);//闪光
// notificationChannel.shouldShowLights();//闪光
// notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);//锁屏显示通知
// notificationChannel.enableVibration(true);//是否允许震动
// notificationChannel.setVibrationPattern(new long[]{100, 100, 200});//设置震动模式
// notificationChannel.getAudioAttributes();//获取系统响铃配置
// notificationChannel.getGroup();//获取消息渠道组
// notificationChannel.setBypassDnd(true);
// notificationChannel.setDescription("description");
// notificationChannel.setLightColor(Color.GREEN);//制定闪灯是灯光颜色
// notificationChannel.setShowBadge(true);
// getNotificationManager().createNotificationChannel(notificationChannel);
//第一个参数:channel_id
//第二个参数:channel_name
//第三个参数:设置通知重要性级别
//注意:该级别必须要在 NotificationChannel 的构造函数中指定,总共要五个级别;
//范围是从 NotificationManager.IMPORTANCE_NONE(0) ~ NotificationManager.IMPORTANCE_HIGH(4)
NotificationChannel channel = new NotificationChannel(id, name,
NotificationManager.IMPORTANCE_DEFAULT);
// channel.canBypassDnd();//是否绕过请勿打扰模式
channel.enableLights(true);//闪光灯
channel.setLockscreenVisibility(VISIBILITY_SECRET);//锁屏显示通知
channel.setLightColor(Color.RED);//闪关灯的灯光颜色
channel.canShowBadge();//桌面launcher的消息角标
channel.enableVibration(true);//是否允许震动
channel.getAudioAttributes();//获取系统通知响铃声音的配置
channel.getGroup();//获取通知取到组
channel.setBypassDnd(true);//设置可绕过 请勿打扰模式
channel.setVibrationPattern(new long[]{100, 100, 200});//设置震动模式
channel.shouldShowLights();//是否会有灯光
getNotificationManager().createNotificationChannel(channel);
}
}
/**
* 获取通知管理者对象
*
* @return
*/
public NotificationManager getNotificationManager() {
if (notificationManager == null) {
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
return notificationManager;
}
/**
* 对应Android8.0生成notification的方法,通过此方法获取notification
*/
public Notification.Builder getChannelNotification(int iconRes, String title, String content, PendingIntent pendingIntent) {
Notification.Builder builder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new Notification.Builder(getApplicationContext(), id);
builder.setSmallIcon(iconRes);
builder.setAutoCancel(true);
builder.setChannelId(id);
builder.setWhen(System.currentTimeMillis());
builder.setContentTitle(title);
//设置显示通知时间
builder.setShowWhen(true);
builder.setContentText(content);
builder.setNumber(3);
builder.setOnlyAlertOnce(false);
//悬停通知
builder.setTicker(content);
builder.setDefaults(~0);
builder.setPriority(Notification.PRIORITY_DEFAULT);
// builder.setVisibility(Notification.VISIBILITY_PUBLIC);
// builder.setFullScreenIntent(pendingIntent, true);
builder.setContentIntent(pendingIntent);
}
return builder;
}
private int priority = Notification.PRIORITY_DEFAULT;
/**
* 对应Android8.0以下的notification对象
*/
public NotificationCompat.Builder getNotification(int iconRes, String title, String content, PendingIntent pendingIntent) {
// NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), id);
builder.setPriority(NotificationCompat.PRIORITY_MAX);
builder.setSmallIcon(iconRes);
builder.setAutoCancel(true);
builder.setWhen(System.currentTimeMillis());
builder.setContentTitle(title); //设置标题
builder.setContentText(content);
builder.setDefaults(Notification.DEFAULT_VIBRATE);//设置振动声音等,需要振动权限
builder.setContentIntent(pendingIntent); //自定义打开的界面
//悬停通知
builder.setTicker(title);
builder.setDefaults(~0);
builder.setPriority(Notification.PRIORITY_HIGH);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//SDK版本>=21才能设置悬挂式通知栏
// builder.setCategory(String.valueOf(Notification.FLAG_ONGOING_EVENT))
// .setVisibility(Notification.VISIBILITY_PUBLIC);
// }
// builder.setVisibility(Notification.VISIBILITY_PUBLIC);
// builder.setFullScreenIntent(pendingIntent, true);
//点击自动删除通知
builder.setAutoCancel(true);
return builder;
}
// public static boolean isNotificationEnabled(Context context,String channelId) {
// return NotificationManagerCompat.from(context.getApplicationContext()).areNotificationsEnabled();
// }
// public static boolean isNotificationEnabled(Context context,String channelId) {
// NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
// NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// boolean returnValue = managerCompat.areNotificationsEnabled();
// if(manager == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
// return returnValue;
// }
// NotificationChannel channel = manager.getNotificationChannel(channelId);
// if(channel == null){
// channel = new NotificationChannel(channelId,"我的推送类别",NotificationManager.IMPORTANCE_HIGH);
// manager.createNotificationChannel(channel);
//
// //下面的获取操作必需,创建的channel和获取到的channel的IMPORTANCE可能不一样,OPPO默认IMPORTANCE_NONE。
// channel = manager.getNotificationChannel(channelId);
// }
// return returnValue && channel.getImportance() != NotificationManager.IMPORTANCE_NONE;
// }
areNotificationsEnabled方法的有效性官方只最低支持到API 19,
/// 低于19的仍可调用此方法不过只会返回true,即默认为用户已经开启了通知。
//查阅官方文档可知 NotificationManagerCompat 在 android.support.v4.app包中,
// 是API 22.1.0 中加入的。而 areNotificationsEnabled()则是在 API 24.1.0之后加入的
//areNotificationsEnabled 只对 API 19 及以上版本有效,低于API 19 会一直返回true
public static boolean isNotificationEnabled(Context context) {
return NotificationManagerCompat.from(context.getApplicationContext()).areNotificationsEnabled();
}
public static void openPush(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//这种方案适用于 API 26, 即8.0(含8.0)以上可以用
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, activity.getPackageName());
intent.putExtra(Settings.EXTRA_CHANNEL_ID, activity.getApplicationInfo().uid);
activity.startActivity(intent);
} else {
PermissionUtil.toPermissionSetting(activity);
}
}
2.后台运行设置
1.电池优化设置
2.后台运行设置
3.显示在上层设置
private EasyPopup mStartManagerPop;
private void showStartManagerPop() {
// 将对话框的大小按屏幕大小的百分比设置
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
mStartManagerPop = EasyPopup.create()
.setContentView(this, R.layout.layout_startmanager)
.setOnViewListener(new EasyPopup.OnViewListener() {
@Override
public void initViews(View view, final EasyPopup easyPopup) {
ImageView mIvStartBg = view.findViewById(R.id.iv_start_bg);
ImageView mIvCircle1 = view.findViewById(R.id.iv_circle1);
ImageView mIvCircle2 = view.findViewById(R.id.iv_circle2);
mIvStartBg.setImageResource(BuildConfig.FLAVOR.equals(Common.Constance.Smartlock) ?
R.drawable.ic_start_manager : R.drawable.ug_ic_start_manager);
mIvCircle1.setImageResource(BuildConfig.FLAVOR.equals(Common.Constance.Smartlock) ?
R.drawable.ic_start_circle : R.drawable.ug_ic_start_circle);
mIvCircle2.setImageResource(BuildConfig.FLAVOR.equals(Common.Constance.Smartlock) ?
R.drawable.ic_start_circle : R.drawable.ug_ic_start_circle);
TextView txvContent=view.findViewById(R.id.txv_content);
txvContent.setText(BuildConfig.FLAVOR.equals(Common.Constance.Smartlock) ?
"允许 “保仕盾” 始终在后台运行,可能会缩短电池的续航时间。" : "允许 “优果智能” 始终在后台运行,可能会缩短电池的续航时间。");
view.findViewById(R.id.tv_ok).setOnClickListener(v -> {
if (isIgnoringBatteryOptimizations()) {
BackStageKeepAliveUtil.getDeviceSetting(BackstageSetActivity.this);
} else {
requestIgnoreBatteryOptimizations();
}
mStartManagerPop.dismiss();
});
view.findViewById(R.id.tv_cancel).setOnClickListener(v -> mStartManagerPop.dismiss());
}
})
.setWidth((int) (display.getWidth() * 0.85))
.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
.setAnimationStyle(R.style.pop_privacy)
.setBackgroundDimEnable(true)
.setFocusAndOutsideEnable(true)
.setOnDismissListener(() -> {
mStartManagerPop.dismiss();
})
.apply();
mStartManagerPop.showAtLocation(mRootMain, Gravity.CENTER, 0, 0);
}
//判断是否在白名单中
private boolean isIgnoringBatteryOptimizations() {
boolean isIgnoring = false;
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (powerManager != null) {
isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
}
return isIgnoring;
}
public void requestIgnoreBatteryOptimizations() {
try {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
//判断是否在白名单中
if (isIgnoringBatteryOptimizations()) {
//已在白名单
ToastUtil.showLayoutToast(this,"电池优化已经设置成功");
}
}else if(requestCode==1){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !Settings.canDrawOverlays(this)) {
Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
}
}
}
public static boolean checkPermission(Activity activity){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !Settings.canDrawOverlays(activity)) {
// Toast.makeText(activity, "当前无权限,请授权", Toast.LENGTH_SHORT).show();
activity.startActivityForResult(
new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + activity.getPackageName())), 1);
return false;
}else{
Toast.makeText(activity, "您已经打开了应用上层设置", Toast.LENGTH_SHORT).show();
}
return true;
}
本文地址:https://blog.csdn.net/u014608640/article/details/109360309