Android Notification 通过增加addAction 跳转回Service重新执行逻辑
1.场景描述
在App内升级过程中,apk下载过程中网络波动导致连接超时,下载失败后Service生命周期结束。前台通知也被清除。
2.解决思路
在通知栏中增加重试按钮重启下载服务。
3.代码
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);Builder mBuilder = new Builder(this);if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);mNotificationManager.createNotificationChannel(channel);mBuilder.setSmallIcon(R.mipmap.ic_launcher).setContentTitle(title).setContentText(text).setChannelId(CHANNEL_ID).setTicker(ticker);} else {mBuilder.setSmallIcon(R.mipmap.ic_launcher).setContentTitle(title).setContentText(text).setTicker(ticker);}Intent intentService = new Intent(this, ApkDownloadService.class);intentService.putExtra("updateInfo", mAppUpdateResponse);intentService.putExtra("updateType", 1);PendingIntent pendingIntent = PendingIntent.getService( this, 0, intentService, PendingIntent.FLAG_IMMUTABLE);mBuilder.addAction(R.mipmap.ic_launcher, getString(R.string.retry), pendingIntent);mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
4.效果图