繁体   English   中英

Android 前台服务同一服务的多个通知

[英]Android foreground service multiple notifications for same service

我有一个 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM