开发者

Detect that an activity has closed in Android

In my application I need to launch a SelectionActivity to select one of the options. Once the option has been selected I need to refresh another list on the MainActivity.

This is the code that I use to launch the SelectionActivity:

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

In SelectionActivity this is the code that receives the selected option an closes the activity:

selectedValue 开发者_如何学C= adapter.getItem(position);
finish();

Now the application comes back to MainActivity but I don't know how to receive an event that the SelectionActivity has closed.

Thanks


Quick snippet showing use of startActivityForResult:

private static final int MY_REQUEST_CODE = 0xe110; // Or whatever number you want
// ensure it's unique compared to other activity request codes you use

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

    if (requestCode == MY_REQUEST_CODE)
        ActiviyFinishedNowDoSomethingAmazing();
}

public void onClickStartMyActivity(View view)
{
    startActivityForResult(new Intent(this, GameActivity.class), MY_REQUEST_CODE);
}

More reading on getting a result from an activity.


Depending on your application's design you can refresh the list each time the Main activity is returned to by watching the onResume() or onRestart() events. In addition there is startActivityForResult(). All of these methods are in Activity.


Solution 1 :

  1. Make selectedValue a static public variable.
  2. In your MainActivity :

    void onResume() {
            result = SelectionActivity.selectedValue;
    }
    

Solution 2 :

If the SelectionActivity's job is simply a selection from multiple options, Consider using Dialogs


Look into startActivityForResult()


startActivityForResult(), then override the onActivityResult() method. There are a lot of examples one can google for just using the key word startactivityforresult.


Use onActivityResult() or make selectedValue static. In MainActivity use the onResume method:

protected void onResume() {
    if(SelectionActivity.selectedValue != 0)
          newValue = SelectionActivity.selectedValue;
}


Use onDestroy:

public void onDestroy() {
    super.onDestroy();

    Log.w("test", "active");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜