Kiran
Kiran

Reputation: 757

Unexpected behavior in Activities in Android

I have two activities Activity 1 and Activity 2. I am starting Activity 2 from Activity 1 and when Activity 2 finishes, Activity 1 will be resumed. But sometimes Activity 2 finishes unexpectedly(it is not throwing any exceptions) and Activity 1 is started again. Should I specify any FLAGS for intent when starting Activity 2?
I am creating Activity 2 by using below code:

 Intent intent=new Intent(MainActivity.this, SyncService.class);   
 startActivity(intent);

I am using many threads in Activity 2. Will it create any problems?

Upvotes: 0

Views: 352

Answers (1)

Melquiades
Melquiades

Reputation: 8598

Start Activity2 with:

Intent intent = new Intent(MainActivity.this, SyncService.class);
startActivityForResult(intent);

And in Activity1, override:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //do your thing here
    //this is called when Activity2 finishes
    //see below
    if (resultCode == RESULT_OK) {
    }
    else if (resultCode == RESULT_CANCELED) {
    }
}

In Activity2, when you're ready to finish, call:

Intent resultIntent = new Intent();
//if you want, you can pass some data back to Activity1
resultIntent.putExtra("key", "value");
setResult(RESULT_OK, resultIntent);
finish();

which will get you back to Activity2.

Read more here.

Upvotes: 1

Related Questions