简体   繁体   中英

Send an alert to an Activity from Broadcast Receiver

I'm building an app that registers a Broadcast Receiver for Connectivity Changes. When connectivity is available, the app performs a GET request and display the data in a ListView.

I registered the Broadcast Reciver (Connetivity Changes) and it works as expected. But I have a huge dilemma. I want to notify the MainActivity when Connectivity is available.

My first approach was using a class that extends from Observable and implement the Observer interface in the MainACtivity. I stopped that solution because I started using static variables and static methods. My other solution was using a Custom Broadcast registered in the , the idea is sent a broadcast from the Broadcast Receiver and catch it in the MainActivity.

I read several suggestions and a can't get a recommended solution. What is the best approach to this situation?

Do you need to notify the Activity only if it's currently running? Or the next time it's run?

For the first case, you can create a second BroadcastReceiver in the activity, register/unregister it in onResume() / onPause() , then notify it via an intent sent from the Service (all this using a LocalBroadcastManager ). However, is that was your intent (heh) then you might as well have a second receiver in the activity for the original broadcast, so I guess it's not likely.

The other way (notify the Activity the next time it's accessed) is even simpler, just use SharedPreferences to record a boolean flag indicating that the task is pending. When the activity is resumed, check for this flag, do the needed work (make sure the connection is still available) and then clear it.

A third possible scenario (which I would think more probable, even though it doesn't match your description of the problem) is that you want to download and store the data at the moment the connection becomes available, then just have the activity load it when it starts. In this case the service would perform the download, then either notify or use the flag trick so that the activity knows new data is available.

Depending on the scenario, you might also want to take a look at Sync Adapters .

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