Sushant
Sushant

Reputation: 173

Android- Continuously check for a new record in the database and generate a notification providing the details of the new entry

I am trying to create an android application that continuously check for a new record in a remote database and provide a notification if a new record is added. i want to repeat this for every record that is added.

I have done the following till now Created a service that fetches data from the database. Can anyone suggest what's the best way to call the service again and again after a fixed interval or keep the service up and running and cal a method repeatedly. What would prove a better performance?

Upvotes: 0

Views: 3219

Answers (1)

Kirit  Vaghela
Kirit Vaghela

Reputation: 12664

Continuously checking for a new record in a remote database will create a load in your application.

You can use Google Cloud to device messaging service. This will send a notification message to device every time the remote database has new records.

Please check this : http://developer.android.com/google/gcm/index.html

Steps for GCM

1.Add following permission and receiver in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<permission android:name="com.example.test.permission.C2D_MESSAGE" 
    android:protectionLevel="signature" />
<uses-permission android:name="com.example.test.permission.C2D_MESSAGE" />

 <receiver
        android:name="com.example.test.MyBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="com.example.test" />
        </intent-filter>
    </receiver>

Note: find and replace com.example.test with your package name

  1. MyBroadcastReceiver.java

    public class MyBroadcastReceiver extends BroadcastReceiver{
    
        private static final String TAG = "GCM";
        MyPrefs myPrefs ;
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    myPrefs = new MyPrefs(context);
    
    Log.d(TAG,"inside onReceive");
    
    String action = intent.getAction();
    if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
    
        handleRegistration(context,intent);
    } else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
    
    
        handleMessage(context,intent);
    }
    }
    private void handleRegistration(Context context,Intent intent) {
    String registrationId = intent.getStringExtra("registration_id");
    String error = intent.getStringExtra("error");
    String unregistered = intent.getStringExtra("unregistered");       
    
    // registration succeeded
    if (registrationId != null) {
        Log.d(TAG, "Device_reg_id : "+registrationId);
    
        // store registration ID on shared preferences
        myPrefs.putString("DEVICE_REG_ID", registrationId);
    
        // notify 3rd-party server about the registered ID
        generateNotification(context, "Registration Sucessful", "Device register sucessfully!");
    }
    
    // unregistration succeeded
    if (unregistered != null) {
        // get old registration ID from shared preferences
        // notify 3rd-party server about the unregistered ID
    } 
    
    // last operation (registration or unregistration) returned an error;
    if (error != null) {
        if ("SERVICE_NOT_AVAILABLE".equals(error)) {
            // optionally retry using exponential back-off
            // (see Advanced Topics)
        } else {
            // Unrecoverable error, log it
            Log.i(TAG, "Received error: " + error);
        }
    }
    }
    private void handleMessage(Context context, Intent intent) {
    
    String data = intent.getExtras().getString("data");
    generateNotification(context, "New Message is received", data);
    }
    
    private void generateNotification(Context context,String title,String text) {
    
    NotificationCompat.Builder mBuilder = 
            new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(title)
            .setContentText(text);
    
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, MainActivity.class);
    
    PendingIntent resultPendingIntent = PendingIntent.getBroadcast(context,0,resultIntent, 0);     
    mBuilder.setContentIntent(resultPendingIntent);
    
    NotificationManager mNotificationManager =
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify(0, mBuilder.build());
     }
    
  2. MainActivity.java

    public class MainActivity extends Activity {
    
     String device_reg_id;
    
     @Override
     public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    MyPrefs prefs = new MyPrefs(this);
    device_reg_id = prefs.getString("DEVICE_REG_ID"); 
    
    if (device_reg_id == null )
    {
        Log.d("GCM", "Registration start");
        // registration 
        Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
        // sets the app name in the intent
        registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
        registrationIntent.putExtra("sender", "1850XXXX2785");
        startService(registrationIntent);
    }else
    {
        // send a message to device its self
    
            String api_key = "AIzaSyBXSJHPqFiYeYdAoYfN1XlI20Es";
    
            Sender sender = new Sender(api_key);
    
            Message message = new Message.Builder()
            .collapseKey("1")
            .timeToLive(3)
            .delayWhileIdle(true)
            .addData("data", "Welcome!")
            .build();
    
            Result result;
            try {
                result = sender.send(message, device_reg_id, 5);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          }
        }
      }
    
  3. MyPrefs.java

    public class MyPrefs {
    
     private SharedPreferences sp;
     private Editor editor;
    
     public MyPrefs(Context context){
            sp = PreferenceManager.getDefaultSharedPreferences(context);
            editor = sp.edit();
     }
    public void putString(String key,String Value){
              editor.putString(key,Value);
              editor.commit();
    }
    public String getString(String key){
           return sp.getString(key,null);
     }
    }
    

Note don't forget to import gcm-server.jar from sdk\extras\google\gcm\gcm-server\dist. if you don't find the path in sdk than install Google Cloud Messaging for Android Libaray under Extras in Android SDk Manager

Upvotes: 1

Related Questions