我正在为推送通知实施FCM(Firebase云消息传递)。我可以成功地使用我的服务类从服务器获得推送通知。但是,如何将数据(消息)从服务类发送到活动?
Service.java
public class Service extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, FCMActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri =RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.RED, 1000, 300);
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
FCMActivity.java
public class FCMActivity extends AppCompatActivity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fcm);
mTextView = (TextView) findViewById(R.id.txt);
}
}
答案 0 :(得分:3)
有几种选择,其中包括:
在您的活动中注册BroadcastReceiver
,IntentFilter
用于自定义操作(操作只是广播消息类型的String
标识符),并从中发送广播使用LocalBroadcastManager.getInstance().sendBroadcast(Intent intent)
方法
使用事件总线,例如非常受欢迎的GreenRobot EventBus库。有关说明,请参阅https://github.com/greenrobot/EventBus#eventbus-in-3-steps。
这两个选项都需要在Activity中注册和取消注册侦听器/接收器,最好在onResume
/ onPause
中针对应该触发UI更改的事件进行。
答案 1 :(得分:0)
您应该在服务中使用IBinder
,在活动中使用ServiceConnection