简体   繁体   中英

How to send message to paused activity in Android

Consider scenario 1:

I have activity and launch another activity to do something. After 2nd activity done (action complete) - I need to update 1st activity. I understand this can be done using "launch for result"

Scenario #2:

I have service that runs on background, fetches data, etc. This also can update 1st activity. In this case activity can be live or it can be paused too.

In iOS I just use NotificationCenter and it works. How can I "register" to receive events in Activity and make sure it is updated even if activity sleeps at that moment? I was thinking about creating global flags and check them onResume , but not sure what is the proper way to handle this scenarios most proper and "loose" way?

There are two common options.

LocalBroadcastManager is provided by the compatibility library and will allow Android components in the same app to send and receive messages in the form of Intents. It's a lot like normal broadcasts.

You can also find a third party "event bus" library, which will be a little more flexible.

You are correct, you would use startActivityForResult() when starting your second activity. Then, in your first activity, override onActivityResult() which you will put logic in to receive the result from the second activity. For example:

First Activity

int REQUEST_CODE = 1;

Intent newActivityIntent = new Intent(this, SecondActivity.class);
startActivityForResult(newActivityIntent, REQUEST_CODE);

then override onActivityResult()

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
    // Make sure the result is OK.
    if (resultCode == RESULT_OK) { 
        // Make sure this result is from the corresponding request.
        if (requestCode == REQUEST_CODE) { 
            // Extract your data from the intent.
            MyData myResultData = data.getExtra("my_extra"); // Generic example.
        }
    }
}

In the second activity you simply gather the information needed to send back when the user is finished, and put it in the return intent.

Second Activity

Intent returnIntent = new Intent();
returnIntent.putExtra("my_extra", data);

// Now set the result.
setResult(RESULT_OK, returnIntent);

// Call finish, and the return intent is passed back.
finish();

This is probably the easiest and least complex way to achieve what you want. This way, you know the activity receiving the result will always be unpaused when it gets the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM