Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Activity to background without finishing

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.

like image 698
1HaKr Avatar asked Jan 11 '10 12:01

1HaKr


People also ask

Can activity run in background Android?

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.

What is restrict background activity?

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.

What is background activity in Android?

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.


2 Answers

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.

like image 195
mhsmith Avatar answered Oct 19 '22 23:10

mhsmith


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.

like image 37
stormin986 Avatar answered Oct 20 '22 00:10

stormin986