How can I start an activity when my app is in background? I mean, when it has not been destroyed? I have tried with IntentService and nothing, I just want to make a StartActivity to launch my MainActivity in the background.
Question posted in Android Studio
The official documentation can be found here.
The official documentation can be found here.
2
Answers
Right-click on the project, Select New >> Service >> Service and add the following to MyServices.java
Add the following code to res/layout/activity_main.xml
Add the following code to src/MainActivity.java
Add the following code to androidManifest.xml
Let’s try to run your application.
Click on the Click here button to start background services.
Your service needs to be a foreground service.
Here is how.
First in your
Manifest.xml
file.Request for permission
Start your service with:
startForegroundService(Intent(this, MyService::class.java))
Then in your service display the foreground notification(usually in the onStartCommand):
Then your can start an activity(for example: see below)
Android may complain that your activity needs to inherit theme from
Theme.AppCompat
and you may also have difficulties loading an xml layout.I believe your can work around those. Apart from that your are good to go.
And also note that i only tested it on Android 10 and below.