Basically I've got an application that runs a foreground service.
When I start the application I need to do session specific initialization in the Application's onCreate method.
When I close the app, the service keeps running (desired behaviour), however, when I reopen the app from the launcher / from my notification, the Application onCreate isn't getting called again.
My question are:
- How do I enforce the Application
onCreatebe called again even though there's a service running? (The service is probably keeping a reference to the application object, right?) - Is there a way to get indication inside the Application class that the app has been started again but from a service?
- What other solutions can you think about?
MyService in AndroidManifest.xml:
<service android:name=".MyService"
android:exported="false"/>
My service's onStartCommand:
createNotificationChannel();
Intent notificationIntent = new Intent(this, MyActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("My Service")
.setContentText("Service")
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
The event onCreate is fired during the creation of the object. After there is onStart. If the app has been closed, the object is still active in memory and will be destroyed if the device require more free resources. So, if you reopen the app, only the onStart event is fired. Try to move the initialization in onStart, or put a check or similar in onStart.
Lifecycle of on activity https://developer.android.com/guide/components/activities/activity-lifecycle