How can I make an activity go to background without calling its finish()
method and return to the Parent activity that started this? I tried so much but I could not find a solution. So if you guys could help I would be very thankful.
However, activity can't be run unless it's on foreground. In order to achieve what you want, in onPause(), you should start a service to continue the work in activity. onPause() will be called when you click the back button. In onPause, just save the current state, and transfer the job to a service.
Android 10 (API level 29) and higher place restrictions on when apps can start activities when the app is running in the background. These restrictions help minimize interruptions for the user and keep the user more in control of what's shown on their screen.
Definition of background work. An app is running in the background when both the following conditions are satisfied: None of the app's activities are currently visible to the user. The app isn't running any foreground services that started while an activity from the app was visible to the user.
The following will work if the Activity is running in a different task to its parent. To achieve this, see http://developer.android.com/guide/topics/manifest/activity-element.html#lmode.
public void onBackPressed () {
moveTaskToBack (true);
}
The current task will be hidden, but its state will remain untouched, and when it is reactivated it will appear just as it was when you left it.
If you have data you want to cache / store / process in the background, you can use an AsyncTask or a Thread.
When you are ready to cache / transition to parent, you would do something like the following in one of your child Activity methods (assuming you started child with startActivityForResult() )
Thread Approach:
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// PUT YOUR CACHING CODE HERE
}
});
t1.start();
setResult( whatever );
finish();
You can also use a Handler if you need to communicate anything back from your new thread.
AsyncTask Approach:
new CacheDataTask().execute( data params );
set_result( whatever );
finish();
The AsyncTask is for situations in which you need to process something in a new thread, but be able to communicate back with the UI process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With