我想自动打开应用程序时,收到推送通知。我试过了,但还是没有像我预期的那样起作用。当应用程序处于活动状态或在MainActivity中时,下面的代码是工作的,但是当应用程序在后台或者仅仅在托盘上显示通知时,它就不能工作了。我错过了什么吗?
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getNotification() != null) {
        if (PreferencesUtil.getInstance(this).isLoggedIn()) {
            sendNotification(remoteMessage.getData().get("order_id"));
        }
    }
}
public void sendNotification(String messageBody) {
    NotificationManager notificationManager = null;
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder notificationBuilder;
    notificationBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("Notification")
            .setSmallIcon(R.mipmap.icon_notif)
            .setContentText(messageBody)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_LIGHTS );
    //add sound
    try {
        Uri sound = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.siren);
        Ringtone ringtone = RingtoneManager.getRingtone(this, sound);
        ringtone.play();
        notificationBuilder.setSound(sound);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //vibrate
    long[] v = {1000, 1000, 1000, 1000, 1000};
    notificationBuilder.setVibrate(v);
    notificationManager.notify(0, notificationBuilder.build());
    Intent i = new Intent(this, NotificationActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
}
}发布于 2018-05-16 11:45:48
首先,Android中的“应用程序”概念是一个稍微扩展的概念。
一个应用程序--从技术上讲是一个进程--可以有多个活动、服务、内容提供者和/或广播侦听器。如果其中至少有一个正在运行,则应用程序已启动并正在运行(进程)。
因此,您需要识别的是如何“启动应用程序”。
好的..。以下是您可以尝试的内容:
action=MAIN和category=LAUNCHER创建意图PackageManager从当前上下文获取context.getPackageManagerpackageManager.queryIntentActivity(<intent>, 0),其中意图是使用main/launcher获取第一个活动的category=LAUNCHER, action=MAIN或packageManager.resolveActivity(<intent>, 0)ActivityInfoActivityInfo中获取packageName和名称category=LAUNCHER, action=MAIN, componentName = new ComponentName(packageName, name)和setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)创建另一个意图context.startActivity(newIntent)https://stackoverflow.com/questions/50368716
复制相似问题