2016-08-21 79 views
1

我正在为推送通知实施FCM(Firebase云消息传递)。我可以成功地使用服务类从服务器获取推送通知。但是,如何将数据(消息)从服务类发送到活动?如何将数据从班级发送到Android中的活动

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

想要将“messageBody”发送到我的活动中。 –

回答

0

你应该在你的活动中使用你的服务IBinderServiceConnection

3

有几种选择,其中那些是:

  1. 注册一个BroadcastReceiver你的活动中有IntentFilter自定义操作(行动仅仅是一个广播消息类型的String标识符),并使用LocalBroadcastManager.getInstance().sendBroadcast(Intent intent)方法

  2. 使用从服务发送广播活动巴士,例如非常受欢迎的GreenRobot EventBus图书馆。有关说明,请参阅https://github.com/greenrobot/EventBus#eventbus-in-3-steps

这些选项都需要注册和注销您的活动,这是最好的onResume/为应触发用户界面的变化事件进行内部监听器/接收器。

此外,您可以bind to the service from your Activity

+0

如果决定使用BroadcastReceiver,最好的选择是在onResume()/ onPause()中注册/取消注册,否则它会抛出“IllegalStateException:在onSaveInstanceState后无法执行此操作”。这也将减少不必要的系统开销。 – heloisasim

相关问题