应用程序打开时推送通知不起作用?
Posted
技术标签:
【中文标题】应用程序打开时推送通知不起作用?【英文标题】:Push notifications is not working when the application is open? 【发布时间】:2019-03-28 10:43:37 【问题描述】:我正在尝试使用 FCM,但通知仅在我不使用应用程序时有效。
当我从设备 A 向设备 B 发送通知时,设备 B 收到消息并“以默认声音显示通知弹出”,一切都很好......(当设备 B 不使用应用程序时会发生这种情况)。
当我从设备 A 向设备 B 发送通知时,设备 B 在 onMessageReceived() 方法中收到消息,但“不显示默认声音的通知弹出”..(当设备 B 使用应用程序,我的意思是当应用程序打开并正在使用时)。
这是我的代码 FireIDService.java
public class FireIDService extends FirebaseInstanceIdService
private final String TAG = "FireIDService";
@Override
public void onTokenRefresh()
String tkn = FirebaseInstanceId.getInstance().getToken();
Log.d("Not","Token ["+tkn+"]");
sendRegistrationToServer(tkn);
private void sendRegistrationToServer(String token)
saveDeviceToken(token);
private void saveDeviceToken(String deviceToken)
//some code..
if(response.body().getStatus() == 1)
doStuff();
//some code...
@Override
public void onFailure(Call<SaveDeviceTokenResponse> call, Throwable t)
//code...
);
private void doStuff()
Intent intent = new Intent(this, SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("FCM Message")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1410 /* ID of notification */, notificationBuilder.build());
FireBaseMsgService.java
public class FireBaseMsgService extends FirebaseMessagingService
private final String TAG = "FireBaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage)
super.onMessageReceived(remoteMessage);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "test")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background))
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setColor(0xffff7700)
.setVibrate(new long[]100, 100, 100, 100)
.setPriority(Notification.PRIORITY_MAX)
.setSound(defaultSoundUri);
Intent resultIntent = new Intent(this, SplashActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(SplashActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
notificationBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notificationBuilder.build());
这是添加到 androidManifest.xml 文件中的内容
<service android:name=".FireIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".FireBaseMsgService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
这是要执行的通知类
public class Notify extends AsyncTask<Void,Void,Void>
private String tkn;
private String title;
private String body;
public Notify(String tkn, String title, String body)
this.tkn = tkn;
this.title = title;
this.body = body;
@Override
protected Void doInBackground(Void... voids)
Log.e("Token: ", tkn);
Log.e("Title: ", title);
Log.e("Body: ", body);
try
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key=KEY_HERE");
conn.setRequestProperty("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("to", tkn);
JSONObject info = new JSONObject();
info.put("title", title); // Notification title
info.put("body", body); // Notification body
info.put("priority", "high");
info.put("show_in_foreground", "true");
json.put("notification", info);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();
catch (Exception e)
Log.d("Error",""+e);
return null;
【问题讨论】:
【参考方案1】:如果您使用的是 android 8.0+。您需要为通知指定 channelId。 当您的应用程序处于后台时(如您在第一个案例中提到的),推送通知在系统通知托盘中收到,而不是在 FireBaseMsgService 中,并且它由系统自动处理,由系统本身生成的 channelId 。 当您的应用程序处于前台(第二种情况)时,您的 FireBaseMsgService 将被执行并且必须创建通知 channelId
【讨论】:
您的回答似乎是正确的,但是您能否告诉我应该在何处以及在什么条件下添加此通知渠道,在我的情况下代码可能是什么样的!你能帮忙吗? 通知通道在android 8.0以后使用。 developer.android.com/training/notify-user/… 感谢 Saurav Kumar,您的回答正是我想要的,它现在完美运行,两种情况下都收到了消息。 很高兴你喜欢。以上是关于应用程序打开时推送通知不起作用?的主要内容,如果未能解决你的问题,请参考以下文章