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.
CodePudding user response:
use a transparent splash screen to hide loading time from the user.
CodePudding user response:
Your service needs to be a foreground service. Here is how.
First in your Manifest.xml
file.
Request for permission
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
......
<!-- Your Service-->
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:permission="android.permission.FOREGROUND_SERVICE"/>
Start your service with:
startForegroundService(Intent(this, MyService::class.java))
Then in your service display the foreground notification(usually in the onStartCommand):
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val ncCompat = NotificationChannelCompat.Builder("your.own.id.here", NotificationManagerCompat.IMPORTANCE_DEFAULT).setName("Important").build()
NotificationManagerCompat.from(baseContext).createNotificationChannel(ncCompat)
startForeground("your.notification.id.goes.here".hashCode(), NotificationCompat.Builder(baseContext, nmCompat.id).setContentTitle("My Foreground Service").setContentText("Running Service").build())
return super.onStartCommand(intent, flags, startId)
}
Then your can start an activity(for example: see below)
val intent = Intent(application, MainActivity2::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME)
intent.addFlags(Intent.FLAG_FROM_BACKGROUND)
startActivity(intent)
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.