安卓本地推送 - GameKong/restaurant GitHub Wiki
实现本地推送所需组件及其作用
组件名 |
用途 |
Service |
应用进入失去焦点或进程被杀死后,仍然可以在后台运行一个服务。 |
BroadcastReceiver |
在Service中创建广播接收器,收到定时器发送的广播后发出一个推送。 |
AlarmManager |
指定发送广播的时间以及距离下次触发的时间间隔。 |
在游戏的启动Activity中创建通知渠道并且启动一个服务,
protected void onCreate(Bundle savedInstanceState) {
...
...
// 创建通知渠道
createNotificationChannels();
// 注册服务用于离线推送
startMyService();
}
// 创建通知渠道
private void createNotificationChannels()
{
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
// 只有安卓8.0以上的版本才支持通知渠道
// 当应用的API level 小于26时,则不用注册通知渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// 通知渠道的重要性, 在安卓8.0以下版本,没有通知渠道的功能,使用通知的 setPriority()代替
int importance = NotificationManager.IMPORTANCE_DEFAULT;
// 创建通知渠道
NotificationChannel channel = new NotificationChannel("渠道名", "定时离线推送渠道", importance);
// 设置渠道描述
channel.setDescription("每日固定时间提醒用户上线领奖");
// 创建通知渠道之后,将无法通过编程的方式改变通知渠道的属性,例如重要性。 只有用户可以更改
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public void startMyService()
{
Intent it = new Intent(this, NotificationService.class);
startService(it);
}
Service和AlarmManager
NotificationService.java
BroadcastReceiver
NotificationReceiver.java