Update a currently running BroadcastReceiver (pass it new values) from and Activity
Is it possible to update a currently running Broadcastreceiver from an Activity? For example:
Say the user enters a string...and then hits submit...I want the broadcast receiver to be updated with the new string and use that string instead of an older one that the receiver may have. Is this possible? Or can I somehow stop the old receiver when the user clicks submit and then restart it with the new 开发者_运维知识库string?
Maybe I misunderstood your question but why not storing your string in a SharedPreference?
Whenever you Activity will need to update that string, it will save it as preference and on the onReceive
method of your broadcastreceiver, you just get it back from the preference.
I don't think you can. If you look at the Receiver Lifecycle documentation you'll see that the lifecycle is limited to onReceive.
If the receiver's lifecycle is long enough for the user to interact with it, I'd simply use the BroadcastReceiver to start a service. The service could do two things:
- start a background thread to perform your long-running task
- register a (different) BroadcastRecevier with an IntentFilter for updates to the string (as updated by the User in an Activity). When the Service receives the Intent it will update the string value. Note you'll have to synchronization between the service and the background thread (left as an exercise to the interested reader).
Then have your Activity code fire an Intent whenever the user modifies the value in question.
The nice thing about this solution is if the service isn't running then the Intent gets dropped on the floor and you don't have to start the Service at all. If the Service is running, then your update occurs.
精彩评论