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.
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.
Simply
protected void minimizeApp() { Intent startMain = new Intent(Intent.ACTION_MAIN); startMain.addCategory(Intent.CATEGORY_HOME); startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(startMain); }
Moving the task backward is NOT going to insure that you will maintain any state, unless you do that manually by responding to the Activity
lifecycle events.
You should just start the second Activity
via Intent
using startActivity()
, or, if you need to receive a result back from the second Activity
, use startActivityForResult()
. This allows you to receive a callback when the user finishes the Activity
and returns to your first Activity
.
Starting an Activity
and getting results: http://developer.android.com/reference/android/app/Activity.html#StartingActivities
Try:
Intent toNextActivity = new Intent(CurrentActivity.this,
NextActivity.class);
CurrentActivity.startActivity(toNextActivity);
If you use this way, the method onPause() from CurrentActivity will be called and if you have a static variable (like a MediaPlayer object) in CurrentActivity it will continue to exist (or play if it is playing)..
I'm using that in my application but I found a better way to do that with services.
Hope this will help you!
精彩评论