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

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

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

public class ExampleService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //String CHANNEL_ID="abc123";
        String input = intent.getStringExtra("inputExtra");
        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Example Service")
                .setContentText(input)
                .setSmallIcon(R.drawable.icon_play)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(100, notification);
        //do heavy work on a background thread
        //stopSelf();
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

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

public void startService(View v) {
    String input = editTextInput.getText().toString();
    Intent serviceIntent = new Intent(this, ExampleService.class);
    serviceIntent.putExtra("inputExtra", input);
    ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService(View v) {
    Intent serviceIntent = new Intent(this, ExampleService.class);
    stopService(serviceIntent);
}

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

**

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

brc7rcf0

brc7rcf01#

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

相关问题