Zeeshan Tariq Zeeshan Tariq - 1 month ago 7
Java Question

How to close an Activity using push Notification in Firebase?

I am working on Firebase Push Notification and i want to close

MainActivity
. Application should finish when
onMessageReceived()
is called. I am also passing the
Context
but its not working. In this case, I'll send notification when application is opend. My code:

MainActivity.java

public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

new FirebaseMessagingService(MainActivity.this);
}
}


FirebaseMessagingService.java

public class FirebaseMessagingService extends
com.google.firebase.messaging.FirebaseMessagingService {

Context context;
public FirebaseMessagingService(Context ctx) {
this.context = ctx;
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
context.finish();
}
}

Answer

You could define a BroadcastReceiver in MainActivity, that calls finish() when triggered:

private final BroadcastReceiver finishReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        finish();
    }
};

Register/unregister it when appropriate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // ...

    LocalBroadcastManager.getInstance(getApplicationContext())
        .registerReceiver(finishReceiver,
            new IntentFilter(FirebaseMessagingService.ACTION_FINISH));
}

@Override
protected void onDestroy() {
    LocalBroadcastManager.getInstance(getApplicationContext())
        .unregisterReceiver(finishReceiver);
    super.onDestroy();
}

And then you just simply have to send a local broadcast from onMessageReceived():

public static final String ACTION_FINISH = "yourpackagename.ACTION_FINISH";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    LocalBroadcastManager.getInstance(getApplicationContext())
        .sendBroadcast(new Intent(ACTION_FINISH));
}

(FirebaseMessagingService is a Context subclass, there is no need to pass another Context instance to it)