I have an app with multiple users, each user can start multiple counters for each activity they do ( run, sleep, reading...) to count how many seconds passed. Each counter will show time passed with a notification. This is sample code
Service class :
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;
}
}
Main activity: Call startService() to start the service and the notification Call stopService() to stop the service and the notification
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);
}
Each notification work independently, the user can stop one activity by clicking on the stop button on a notification while the other notifications are still running.
If I use one Service class for each activity, it works, but it is impossible to add more service classes when I add a new user. **
If I use only one Service class for all notifications, when I call stopService(), all the notifications will be destroyed.
**
Is there any solution to use ONLY ONE Service class for ALL NOTIFICATIONS and users can control each notification INDEPENDENTLY???