如何在收到推送通知时自动打开应用程序?

问题描述 投票:0回答:4

我想在收到推送通知时自动打开应用程序。 我已经尝试过,但它仍然无法按我的预期工作。 下面的代码在应用程序处于活动状态或处于 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);
}
}
android firebase push-notification firebase-cloud-messaging
4个回答
4
投票

这是需要从后端处理的事情,

这是您现在正在使用的示例有效负载,

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    }
  }
}

当您的应用程序位于前台时,这只会让您控制操作并执行某些操作,否则只需发出通知。

详细信息您可以查看这里

现在,为了始终控制您的通知,您需要如下所示的有效负载,

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "data":{
      "Nick" : "Mario",
      "body" : "great match!",
      "Room" : "PortugalVSDenmark"
    }
  }
}

不同之处在于您需要发送数据负载而不是来自后端的通知负载。


1
投票
int requestID = (int) System.currentTimeMillis();
Intent notificationIntent = new Intent(getApplicationContext(), NotificationActivity.class);

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 

PendingIntent contentIntent = PendingIntent.getActivity(this, requestID,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

并像这样添加 PendingIntent

notificationBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("Notification")
            .setSmallIcon(R.mipmap.icon_notif)
            .setContentText(messageBody)
            .setContentIntent(contentIntent);
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_LIGHTS );

0
投票

首先,Android中的“应用程序”概念是稍微延伸的。

应用程序(技术上是一个流程)可以具有多个活动、服务、内容提供商和/或广播侦听器。如果其中至少一个正在运行,则应用程序已启动并正在运行(进程)。

因此,您必须确定的是您要如何“启动应用程序”。

好的...这是您可以尝试的:

  1. 使用
    action=MAIN
    category=LAUNCHER
  2. 创建意图
  3. 使用
    PackageManager
     从当前上下文中获取 
    context.getPackageManager
  4. packageManager.queryIntentActivity(<intent>, 0)
    其中意图具有
    category=LAUNCHER, action=MAIN
    packageManager.resolveActivity(<intent>, 0)
    以获得主/启动器的第一个活动
  5. 获取您感兴趣的
    ActivityInfo
  6. ActivityInfo
    获取
    packageName
    和名称
  7. 最后,使用
    category=LAUNCHER, action=MAIN, componentName = new ComponentName(packageName, name)
    和 setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 创建另一个意图
  8. 最后
    context.startActivity(newIntent)

0
投票

我将为您提供此类情况的完整示例。我将根据收到的数据有效负载向某个号码发送一条消息(无论我的应用程序被完全杀死还是在后台或在前台)

{
"registration_ids":["cMcyU3CaSlCkjPh8C0qo-n:APA91bFwOhNAwYp5vEEztv_yD_vo1fWt7TsiKZQ8ZvIWx8CUKZa8CNVLAalxmV0FK-zwYgZnwdAnnVaHjUHYpqC89raTLXxAfUWc2wZu94QWCnv14zW4b_DwDUMBpDo3ybP3qf5Y5KM2"],
"data": {
    "number": "6299018534",
    "msg": "Hii i am sidharth"
}

}

当您从服务器发送此类数据通知时,无论您的应用程序是在后台还是前台,该通知都会在 onMessageReceived 中收到。 所以,Android 代码如下所示:

 public class NotificationServices extends FirebaseMessagingService {


 @Override
 public void onMessageReceived(@NonNull RemoteMessage message) {
    super.onMessageReceived(message);

    if(message.getData().size()>0){
        String number = null,msg = null;
        if(message.getData().get("number") !=null){
            number= message.getData().get("number");

        }
        if(message.getData().get("msg") !=null){
            msg= message.getData().get("msg");

        }
        sendSms(number,msg);



    }

}

@Override
public void onNewToken(@NonNull String token) {
    super.onNewToken(token);
}

private void sendSms(String phone,String sms){
    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage(phone,null,sms,null,null);

}
}

快乐编码:)

© www.soinside.com 2019 - 2024. All rights reserved.