android:使用一个服务类来处理多个通知?

pb3s4cty  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(426)

我有一个有多个用户的应用程序,每个用户可以为他们做的每个活动(运行、睡眠、阅读…)启动多个计数器来计算经过的秒数。每个计数器将显示经过的时间和通知。这是示例代码
服务等级:

  1. public class ExampleService extends Service {
  2. @Override
  3. public void onCreate() {
  4. super.onCreate();
  5. }
  6. @Override
  7. public int onStartCommand(Intent intent, int flags, int startId) {
  8. //String CHANNEL_ID="abc123";
  9. String input = intent.getStringExtra("inputExtra");
  10. Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
  11. PendingIntent pendingIntent = PendingIntent.getActivity(this,
  12. 0, notificationIntent, 0);
  13. Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
  14. .setContentTitle("Example Service")
  15. .setContentText(input)
  16. .setSmallIcon(R.drawable.icon_play)
  17. .setContentIntent(pendingIntent)
  18. .build();
  19. startForeground(100, notification);
  20. //do heavy work on a background thread
  21. //stopSelf();
  22. return START_STICKY;
  23. }
  24. @Override
  25. public void onDestroy() {
  26. super.onDestroy();
  27. }
  28. @Nullable
  29. @Override
  30. public IBinder onBind(Intent intent) {
  31. return null;
  32. }
  33. }

主要活动:调用startservice()启动服务,调用stopservice()通知停止服务和通知

  1. public void startService(View v) {
  2. String input = editTextInput.getText().toString();
  3. Intent serviceIntent = new Intent(this, ExampleService.class);
  4. serviceIntent.putExtra("inputExtra", input);
  5. ContextCompat.startForegroundService(this, serviceIntent);
  6. }
  7. public void stopService(View v) {
  8. Intent serviceIntent = new Intent(this, ExampleService.class);
  9. stopService(serviceIntent);
  10. }

每个通知都是独立工作的,当其他通知仍在运行时,用户可以通过单击通知上的停止按钮来停止一个活动。
如果我为每个活动使用一个服务类,它就可以工作,但是在添加新用户时不可能添加更多的服务类**
如果我只对所有通知使用一个服务类,那么当我调用stopservice()时,所有通知都将被销毁。

**

是否有任何解决方案可以只对所有通知使用一个服务类,并且用户可以独立地控制每个通知???

brc7rcf0

brc7rcf01#

不要停止服务。绑定到它并向其发送消息以停止特定通知。然后,服务应该只停止请求结束的通知。当没有要停止的通知时,服务可以自行结束。

相关问题