我正在处理Firebase推送通知,我想关闭MainActivity。调用onMessageReceived()时,应用程序应完成。我也通过了Context,但是它不起作用。在这种情况下,我将在打开应用程序时发送通知。我的代码:

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();
    }
}

最佳答案

您可以在BroadcastReceiver中定义一个MainActivity,在触发时调用finish()

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


在适当的时候注册/注销它:

@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();
}


然后,您只需要从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是一个Context子类,无需将另一个Context实例传递给它)

关于java - 如何在Firebase中使用推送通知关闭 Activity ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40339070/

10-12 02:36