Elizabeth Courpalis
Elizabeth Courpalis

Reputation: 121

How to get notification like facebook in android code?

In my Activity I keep on polling the server to get the updates and I store that data in database and from there I display that. My question is when I get updates then how do I display on that activity screen without refreshing it ( JUST LIKE FACEBOOK DOES ) Please help me out.


In Login activity I call this function,

    public void PollingViaAlarm() {
try {
        Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(System.currentTimeMillis());
 Intent intent = new Intent(getApplicationContext(),PollingAlarm.class);
 intent.putExtra("title", "Polling Via Server");
 PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,  intent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + 5 * 60  * 1000, 5 * 60 * 1000,pendingIntent);
} catch (Exception e) {

}}

In PollingAlarm Class, I call the functions to poll the server.

 cnstnt.getUserMessagesPollingAlarm(patient_id,username,password, "123");
 cntxt.startService(new Intent(cntxt, NotificationService.class));

In Notifications class,

 package com.vcare.cnstnt;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
 import android.util.Log;

public class NotificationService extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
}

@Override
public void onStart(Intent intent, int startId) {
    // TODO Auto-generated method stub
    super.onStart(intent, startId);
    SharedPref shrd = new SharedPref(getApplicationContext());
    Intent i = new Intent("android.intent.action.MAIN").putExtra(
            "msg_count", "" + shrd.getMsgCount());
    Log.e("msg_count in notification service", "" + shrd.getMsgCount());
    if (shrd.getMsgCount() > 0) {
        Log.e("starting broadcasting","");
        this.sendBroadcast(i);
        this.stopSelf();
    }
}

 }

If possible can you check out the stuff that I am trying to do. I need to achieve facebook kind of notification.

Upvotes: 0

Views: 3568

Answers (1)

Niklas Ekman
Niklas Ekman

Reputation: 961

  1. Use a BroadcastReciever and start a Service to poll the server.
  2. In the Service create an interface and a function called something like

    public void setOnListener(Listener listener) {...}

  3. Implement that interface in the Activity and override functions.

  4. To bind to the interface:

    private ServiceConnection mConnection = new ServiceConnection() {
    
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            final MyService mBoundService = ((MyService.LocalBinder) service)
                    .getService();
            mBoundService.setOnListener(MyActivity.this);
        }
    
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    
    };
    
  5. Bind the Activity to the Service:

    @Override
    public void onStart() {
        super.onStart();
        final Intent intent = new Intent(this, MyService.class);
        bindService(intent, mConnection, 0);
    }
    
  6. Now just call an interface function from the Service whenever a server update is downloaded.

  7. Make sure to unbind the Service aswell:

    @Override
    public void onStop() {
        super.onStop();
        unbindService(mConnection);
    }
    

NOTE! I have not tested the code below.

In response to the updated code: Your alarm seem alright but you are not binding to the service at all. To be able to bind to a service, that service needs to look something like this:

public class NotificationService extends Service {

    private final IBinder mBinder = new LocalBinder();
    private NotificationListener listener;

    public void setListener(NotificationListener listener) {
        this.listener = listener;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        SharedPref shrd = new SharedPref(getApplicationContext());
        Log.e("msg_count in notification service", "" + shrd.getMsgCount());
        if (listener != null && shrd.getMsgCount() > 0) {
            Log.e("starting broadcasting", "");
            listener.onMessageRecieved(shrd.getMsgCount());
        }
        this.stopSelf();
    }

    public interface NotificationListener {
        public void onMessageRecieved(int messageCount);
    }

    public class LocalBinder extends Binder {
        public NotificationService getService() {
            return NotificationService.this;
        }
    }
}

All activities, that should recieve the update must, implement the NotificationListener. Then bind to the service and in the proccess of connecting the service to the activity, bind the listener. It should look something like this.

public class TestActivity extends Activity implements NotificationService.NotificationListener {

    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            final NotificationService mBoundService = ((NotificationService.LocalBinder) service).getService();
            mBoundService.setListener(TestActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

    };

    @Override
    public void onMessageRecieved(int messageCount) {
        // DO WHATEVER YOU'D LIKE HERE,
        // LIKE UPDATE YOUR UI!
    }

    @Override
    public void onResume() {
        super.onResume();
        // Bind service
        final Intent serviceIntent = new Intent(this, NotificationService.class);
        // 0 means do not create service if it doesnt exist
        bindService(serviceIntent, mConnection, 0);
    }

    @Override
    public void onPause() {
        super.onPause();
        unbindService(mConnection);
    }
}

Now, whenever that alarm is executed, if there are any activies bound to the service (meaning if the user has the app open), that activity will receive the update. Now implement whatever code you'd like to process the update.

I really suggest you read up on Bound Services in Android Developers. That's where I learned to bind to service, and my code is heavily influenced by that link.

Upvotes: 1

Related Questions