Android前台服务为同一服务提供多个通知



我有一个RecyclerView,它在每个支架上都有一个启动按钮来启动倒计时计时器,我在前台服务中启动倒计时定时器,这样用户就可以离开应用程序或做任何他想做的事,并知道计时器,每次我启动计时器时,都会调用onStartCommand,我知道该服务只能在一个实例中运行,问题是通知上的文本混乱,并随机更新所有启动的倒计时!当我呼叫该服务时,我为每个呼叫额外设置一个通知通道id,但这是一样的,我只收到一个通知。我需要为每个倒计时定时器单独通知,这样用户就可以单独查看/控制每个倒计时计时器。

@Override
public void onCreate() {
super.onCreate();
timerServiceInstance = this;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//  startForeground(requestCode, getMyActivityNotification("",completedParts,totalSize));
startForeground(NOTIFICATION_ID, getNotification());
}
}, 1);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
NOTIFICATION_ID = intent.getIntExtra("foreGroundID", 1);
CHANNEL_ID = "channel_" + NOTIFICATION_ID;
long millisInput = intent.getLongExtra("time", 0);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.app_name);
NotificationChannel mChannel =
new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);
mChannel.setSound(null, null);
mChannel.enableVibration(false);

notificationManager.createNotificationChannel(mChannel);
}
setTime(millisInput);
startTimer();

return START_NOT_STICKY;
}

private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
serviceChannel.setSound(null, null);
serviceChannel.enableVibration(false);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
private void setTime(long milliseconds) {
startTimeInMillis = milliseconds;
resetTimer();
}
private void startTimer() {
endTime = System.currentTimeMillis() + timeLeftInMillis;
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
@Override
public void onFinish() {
timerRunning = false;
updateWatchInterface();
}
}.start();
timerRunning = true;
updateWatchInterface();
}
private void pauseTimer() {
countDownTimer.cancel();
timerRunning = false;
Paper.book().write("timerTimeLeft", timeLeftInMillis);
pauseResumeButtonText = "Resume";
updateWatchInterface();
}
private void resetTimer() {
timeLeftInMillis = startTimeInMillis;
updateCountDownText();
updateWatchInterface();
}
private void updateCountDownText() {
int hours = (int) (timeLeftInMillis / 1000) / 3600;
int minutes = (int) ((timeLeftInMillis / 1000) % 3600) / 60;
int seconds = (int) (timeLeftInMillis / 1000) % 60;
timeLeftFormatted = String.format(Locale.getDefault(),
"%02d:%02d:%02d", hours, minutes, seconds);
// startForeground(NOTIFICATION_ID, getNotification());
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null) {
//Update the notification bar progress
mNotificationManager.notify(NOTIFICATION_ID, getNotification());
}
}
private void updateWatchInterface() {
if (timerRunning) {
pauseResumeButtonText = "Pause";
} else {
pauseResumeButtonText = "Resume";
if (timeLeftInMillis == 0) {
pauseResumeButtonText = "Done";
}
// startForeground(NOTIFICATION_ID, getNotification());
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null) {
//Update the notification bar progress
mNotificationManager.notify(NOTIFICATION_ID, getNotification());
}
}
}
static public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra("action");
System.out.println("ACTION CLICKED IS " + action);
switch (action) {
case PAUSE_RESUME_TIMER:
if (timerServiceInstance.timerRunning) {
timerServiceInstance.pauseTimer();
} else {
long millisInput = Paper.book().read("timerTimeLeft");
timerServiceInstance.setTime(millisInput);
timerServiceInstance.startTimer();
}
break;
case STOP_TIMER:
Paper.book().write("timerTimeLeft", 0);
timerServiceInstance.stopSelf();
break;
}
}
}

这就是你可以做到的:

Intent intent = new Intent(getApplicationContext(), xyz.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = Constant.CHANNEL_NAME_ALL;
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(expandedTitle))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
try{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
Constant.CHANNEL_DISTRICT_DATA,
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
Random rand = new Random();
notificationManager.notify(rand.nextInt(10000) /* ID of notification */, notificationBuilder.build());
} catch (Exception e){
e.printStackTrace();
}

这里的关键是使用这个代码:

Random rand = new Random();
notificationManager.notify(rand.nextInt(10000) /* ID of notification */, notificationBuilder.build());

使用不同的ID发送通知会导致更新不同的通知,而不是相同的通知。

[编辑]

@Override
public void onCreate() {
super.onCreate();
timerServiceInstance = this;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//  startForeground(requestCode, getMyActivityNotification("",completedParts,totalSize));
startForeground(NOTIFICATION_ID, getNotification());
}
}, 1);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
NOTIFICATION_ID = intent.getIntExtra("foreGroundID", 1);
CHANNEL_ID = "channel_" + NOTIFICATION_ID;
long millisInput = intent.getLongExtra("time", 0);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.app_name);
NotificationChannel mChannel =
new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);
mChannel.setSound(null, null);
mChannel.enableVibration(false);

notificationManager.createNotificationChannel(mChannel);
}
setTime(millisInput);
startTimer(NOTIFICATION_ID);

return START_NOT_STICKY;
}

private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
serviceChannel.setSound(null, null);
serviceChannel.enableVibration(false);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
private void setTime(long milliseconds) {
startTimeInMillis = milliseconds;
resetTimer();
}
private void startTimer(int N_ID) {
endTime = System.currentTimeMillis() + timeLeftInMillis;
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText(N_ID);
}
@Override
public void onFinish() {
timerRunning = false;
updateWatchInterface(N_ID);
}
}.start();
timerRunning = true;
updateWatchInterface(N_ID);
}
private void pauseTimer(int N_ID) {
countDownTimer.cancel();
timerRunning = false;
Paper.book().write("timerTimeLeft", timeLeftInMillis);
pauseResumeButtonText = "Resume";
updateWatchInterface(N_ID);
}
private void resetTimer(int N_ID) {
timeLeftInMillis = startTimeInMillis;
updateCountDownText(N_ID);
updateWatchInterface(N_ID);
}
private void updateCountDownText(int N_ID) {
int hours = (int) (timeLeftInMillis / 1000) / 3600;
int minutes = (int) ((timeLeftInMillis / 1000) % 3600) / 60;
int seconds = (int) (timeLeftInMillis / 1000) % 60;
timeLeftFormatted = String.format(Locale.getDefault(),
"%02d:%02d:%02d", hours, minutes, seconds);
// startForeground(NOTIFICATION_ID, getNotification());
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null) {
//Update the notification bar progress
mNotificationManager.notify(N_ID, getNotification());
}
}
private void updateWatchInterface(int N_ID) {
if (timerRunning) {
pauseResumeButtonText = "Pause";
} else {
pauseResumeButtonText = "Resume";
if (timeLeftInMillis == 0) {
pauseResumeButtonText = "Done";
}
// startForeground(NOTIFICATION_ID, getNotification());
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null) {
//Update the notification bar progress
mNotificationManager.notify(N_ID, getNotification());
}
}
}
static public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra("action");
System.out.println("ACTION CLICKED IS " + action);
switch (action) {
case PAUSE_RESUME_TIMER:
if (timerServiceInstance.timerRunning) {
timerServiceInstance.pauseTimer();
} else {
long millisInput = Paper.book().read("timerTimeLeft");
timerServiceInstance.setTime(millisInput);
timerServiceInstance.startTimer();
}
break;
case STOP_TIMER:
Paper.book().write("timerTimeLeft", 0);
timerServiceInstance.stopSelf();
break;
}
}
}

要显示多个通知,应该使用多个通知ID。而不是信道ID。

即。你在这里定义的:

notificationManager.notify(NOTIFICATION_ID, notification)

最新更新