不创建新的前台 Android 服务通知

3

问题是有一个通知已创建,但其他通知没有创建并更新最后一个通知。我想获得新的通知。

调用通知方法:

 private void NotificationLoop() {

  // one notification
        G.HANDLER.postDelayed(new Runnable() {
            @Override
            public void run() {
                populateNotification(1, "task id : " + 1, 20);
            }
        }, 2000);
 // two notification
        G.HANDLER.postDelayed(new Runnable() {
            @Override
            public void run() {
                populateNotification(2, "task id : " + 2, 40);
            }
        }, 2000);
// three notification
        G.HANDLER.postDelayed(new Runnable() {
            @Override
            public void run() {
                populateNotification(3, "task id : " + 3, 80);
            }
        }, 3000);


    }

从服务中填充通知的方法:populateNotification

 private void populateNotification(int id, String title, int percent) {

        Notification notification;
        Intent CancelIntent = new Intent(this, ServiceDownload.class);
        CancelIntent.setAction(Constant.ACTION.CANCEL_DOANLOAD_ACTION);
        CancelIntent.putExtra("ID", id);
        PendingIntent CCancelIntent = PendingIntent.getService(this, 0, CancelIntent, 0);

        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setAction(Intent.ACTION_MAIN);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        notification = new NotificationCompat.Builder(this)
                .setContentTitle(title)
                .setTicker(title)
                .setContentText(title)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
                .setContentIntent(pendingIntent)
                .setAutoCancel(false)
                .setOngoing(false)
                .addAction(android.R.drawable.ic_menu_close_clear_cancel, this.getResources().getString(R.string.Cancel), CCancelIntent)
                .setProgress(100, percent, false)
                .setStyle((new NotificationCompat.BigTextStyle().bigText(title)))
                .build();
        startForeground(id, notification);
    }

你可以使用startForeground方法来启动同一个服务。但是,每个服务只能使用一个通知进行startForeground操作。如果需要显示第二个或第三个通知,请在服务中使用NotificationManager来实现。 - Vladyslav Matviienko
1个回答

0

前台服务只有一个通知。

因此,当您调用startForeground(id, notification);时,您只需替换它。

您没有太多选择来解决您的问题

  1. 创建新的通知,与服务无关
  2. 停止前台服务并重新启动它,这样通知将是全新的,但有可能用户不会注意到它是新通知而不是更新的旧通知。
  3. 使用新通知启动新的前台服务。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接