Zeeshan Tariq Zeeshan Tariq - 1 month ago 20
Java Question

How to close MainActivity using push notification in Firebase?

I am working on Firebase Push Notification and i want to close MainActivity. Application should finish when onMessageReceived is call. I am also passing the Context but its not working. In this case, I'll send notification when application is opend. My code:

MainActivity.class

public class MainActivity extends FragmentActivity {

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

new FirebaseMessagingService(MainActivity.this);
}
}


FirebaseMessagingService.class

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 just define a BroadcastReceiver in MainActivity, that finishes the Activity 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("action_finish"));
}

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

After that, you just simply have to send a local broadcast from onMessageReceived():

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

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