Mahmoud Hashim
Mahmoud Hashim

Reputation: 550

How to detect database new updates in the background and notify user

I am working on an Android application, it is a news app, the issue is how could I detect that a new news has arrived to the database to notify the user ? I am retrieving data as JSON Objects.

Upvotes: 3

Views: 5127

Answers (2)

Ali Behzadian Nejad
Ali Behzadian Nejad

Reputation: 9044

Create an Android Service (that works in background), fetch data from web and update database inside Service. After updating database send a broadcast message to the Activity. If activity is up and running, its broadcast receiver will receive broadcast, then update UI based on the data inside Intent. So simple!

EDIT:

1- Create a Service

1-1- Create a class that extends Service class. You can do this with new android object wizard.

1-2- Define new Service class in your AndroidManifest.xml as below:

<service android:name="com.example.MyService"/>

1-3- In onStartCommand write a code to read server periodically.

1-4- Read this blog post to get familiar with Android Service.

2- When there is a new data, update database. Then send a broadcast message as below:

Intent i = new Intent("com.example.action.NEW_DATA_RECEIVED_FROM_SERVER");
i.putExtra("KEY1","VALUE1");
i.putExtra("KEY2","VALUE2");
i.putExtra("KEY3","VALUE3");
sendBroadcast(i);

3- Inside your Activity, create a BroadcastReceiver as below:

BroadcastReceiver updateReceiver;

3-1- Inside onCreate method define your broadcastReceiver:

updateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(String action, Intent data) {
        if( action.equals("com.example.action.NEW_DATA_RECEIVED_FROM_SERVER") ) {
           // DO update app
        }
    }

3-2- Then in onResume method register this receiver to get "com.example.action.NEW_DATA_RECEIVED_FROM_SERVER" actions as below:

registerReceiver(updateReceiver, new IntentFilter("com.example.action.NEW_DATA_RECEIVED_FROM_SERVER");

3-3- inside onPause method:

unregisterReceiver(updateReceiver);

Also read this blog post.

I hope this help!

Upvotes: 12

eVoxmusic
eVoxmusic

Reputation: 684

There is no single way to achieve it. But if you want to push directly the news to the user you can consider to use direct GCM (Google Cloud Messaging) which is replacing C2DM.

Upvotes: 3

Related Questions