0

I have a background Service which updates the database in an Android App. In the App this data is displayed, but I am having trouble finding a good way to trigger a refresh of the data.

Initially I just refreshed each time a view resumed, but that doesn't work obviously if the data is updated while the view is shown.

On iOS I use notifications, which I register in the view, and is triggered by the update process when completed. Is there a way to do something similar in Android to trigger an update on the UI thread from a background thread?

Luuk D. Jansen
  • 4,402
  • 8
  • 47
  • 90

2 Answers2

3

BroadcastReciever in your Activity is the best way to update Activity from the Service.

Activity:

 BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
}

After that, all you need is to register some action for it in Activity:

 public final static String BROADCAST_ACTION = "com.example.action";

 IntentFilter intFilt = new IntentFilter(BROADCAST_ACTION);
registerReceiver(br, intFilt);

In your service you should build an intent and call sendBroadcast.

Service:

Intent intent = new Intent(MainActivity.BROADCAST_ACTION);
sendBroadcast(intent);
OFFmind
  • 597
  • 1
  • 5
  • 13
2

There's no need to use a BroadCastReceiver if you update your database and you're using a ContentProvider to saving your data to the db then whenever data change on the ContentProvider it should notify that data has changed and in your on your activity you use a CursorLoader then the Loader is notified and UI updated, this is very easy to do and has the advantage that a CursorLoader will run the thread on background see more here and here

Community
  • 1
  • 1
forcewill
  • 1,637
  • 2
  • 16
  • 31