Alright, so here’s what I would try first, if you want an optional foreground service.
Setup a boolean preference.
I would set up a Service, call it TagTimeService.java. Remember to declare it in the AndroidManifest.xml. While you’re in there, don’t forget to ask for the FOREGROUND_SERVICE
permission.
Then, in the onCreate of your launch activity, I would do something like the following, after loading preferences, and checking that the preference is set to launch the foreground service:
Intent launch = new Intent( sContext, TagTimeService.class );
ContextCompat.startForegroundService(this, launch);
For newer Androids, you have to use notification channels, so set that up. You can set that up idempotently, so let’s do that, in the onCreate of your TagTimeService:
NotificationChannel fgChannel = new NotificationChannel(FOREGROUND_CHANNEL_ID,
"Foreground Service",
NotificationManager.IMPORTANCE_LOW);
fgChannel.setDescription("A persistent notification helping remind both you and Android about TagTime. Feel free to hide, it will still do its job hidden :)");
NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
notificationManager.createNotificationChannel(fgChannel);
And then actually show the notification…
Intent notificationIntent = new Intent(fooContext, WhereShouldTheNotificationGoIfTappedBytheUser.class);
PendingIntent pendingIntent = PendingIntent.getActivity(fooContext,
0,
notificationIntent,
0);
Notification notification = new NotificationCompat.Builder(this, FOREGROUND_CHANNEL_ID)
.setSmallIcon(R.drawable.tagTimeIconOrSomething)
.setPriority(NotificationManager.IMPORTANCE_LOW)
.setContentIntent(pendingIntent).build();
startForeground(PERSISTENT_NOTIFICATION_ID, notification);
if (LOCAL_LOGV) Log.v(TAG, "runAsForeground: created persistent notification.");
I am experimenting launching this as a collapsed notification, but I haven’t gotten to that quite yet.
You may want to wrap that all in a “If on O or newer” conditional.
Let me know how it goes, but I am still wrapping up a large offline project and will have limited availability. This should get you most of the way!