xsc*_*der 3 java android push-notification android-notifications firebase-cloud-messaging
FirebaseMessagingService当我收到推送通知并且应用程序位于前台时,我有以下工作正常:
public class _FCMService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
// Log.i(TAG, "PUSH PAYLOAD: " + remoteMessage.getData());
JSONObject pushData = new JSONObject(remoteMessage.getData());
pushType = pushData.optString("pushType");
pushMessage = pushData.optString("body");
Log.i(TAG, "ON PUSH RECEIVED - pushType: " + pushType);
Log.i(TAG, "ON PUSH RECEIVED - pushMessage: " + pushMessage);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentText(pushMessage)
.setStyle(new NotificationCompat.BigTextStyle())
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(defaultSoundUri);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(0 , notificationBuilder.build());
}
}
@Override
public void onNewToken(@NotNull String token) {
Log.i(TAG, "Refreshed token: " + token);
ANDROID_DEVICE_TOKEN = token;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,如果我收到推送,Logcat 会打印出通知的正文和(如果存在)字符串pushType。
我需要做的是在收到推送时使我的其他活动更新数据,并获取pushMessage和pushType字符串。
我知道如何在 iOS Swift 中做到这一点 - 通过使用NotificationCenter- 但不知道 Android,我尝试过LocalBroadcaster,但没有成功。
小智 5
LocalBroadcastManager现已弃用!
LiveData您可以在静态引用中使用实现并在Activity或中观察它Fragment
public class NotificationService extends FirebaseMessagingService {
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Notification.
getInstance().
addOrder(remoteMessage.getData().get("id"));
}
public static class Notification {
private static Notification instance;
private MutableLiveData<String> newOrder;
private Notification() {
newOrder = new MutableLiveData<>();
}
public static Notification getInstance() {
if(instance == null){
instance = new Notification();
}
return instance;
}
public LiveData<String> getNewOrder() {
return newOrder;
}
public void addOrder(String orderID){
newOrder.postValue(orderID);
}
}
}
Run Code Online (Sandbox Code Playgroud)
并在Activity或中Fragment:
NotificationService.
Notification.
getInstance().
getNewOrder().
observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(String s) {
//TODO: update your ui here...
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2056 次 |
| 最近记录: |