Friday, 21 April 2017

Android broadcast event to trigger function when push notification recieved

In your activity add the below code:

@Override
public void onResume() {
    super.onResume();
    context.registerReceiver(mMessageReceiver, new IntentFilter("any_key"));
}

//Must unregister onPause()
@Override
protected void onPause() {
    super.onPause();
    context.unregisterReceiver(mMessageReceiver);
}

//this method will handle the broadcast call
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
//get data from intend
        String text = intent.getStringExtra("text");
    }
};

Call the below method in any class to trigger the above broadcast event:

static void refreshActivity(Context context, String text) {
    Intent intent = new Intent("any_key");
    //add any text, if any
    intent.putExtra("text", message);
    //send to broadcast
    context.sendBroadcast(intent);
}

OR you can use Otto library to achive this.

No comments:

Post a Comment