Adam Katz Adam Katz - 4 months ago 29
Android Question

Change activity gui from service

I have an android chat app, and in the one fragment called taskfragment there is a list of your chats with a notification counter.

I have a class called chatService that deals with notifications, whenever a notification comes through the chatservice updates the db to increment the notification number on the particular task.

When taskfragment opens it calls a function called refreshTasks(), which updates the gui from the db.

My problem is, if the user is in taskfragment and they get a notification, I need to call refreshtasks from the chatservice, how do I do that?

Thanks.

Answer

You can use LocalBroadcastManager for your purpose.
The idea is to send broadcast from service when new message is received and receive it on your fragment

class YourService extends GcmListenerService{
@Override
public void onMessageReceived(String from, Bundle bundle) {
    ...
    Intent pushNotification = new Intent("pushNotification");
    //put any extra data using Intent.putExtra() method         
    LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
    ...
    }
}  

Now receive it on your fragment:

class TaskFragment extends Fragment{
private BroadcastReceiver mBroadcastReceiver;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ...
        mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("pushNotification")) {
                // new push message is received
                //update UI
                handlePushNotification(intent);
            }
        }
    };
    ...
}

@Override
protected void onResume() {
    super.onResume();
    // registering the receiver for new notification
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mBroadcastReceiver,
            new IntentFilter("pushNotification"));
}

@Override
protected void onDestroy() {
    //unregister receiver here
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mBroadcastReceiver);
    super.onDestroy();
    }
}  

You can refer to this gist or find tutorial about it on web.