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.效果圖