对不起这个noob问题,我是android开发的新手.我目前正在开发一个项目,需要向安装了我的应用程序的Android设备发送推送通知.我已经按照firebase的快速入门教程完成了这项工作,并在我的设备上成功收到了通知.
问题:如何检索服务器发送的消息并将该消息显示给我的AndroID Activity?提前致谢.
继承我的代码. MainActivity.java
public class MainActivity extends AppCompatActivity {TextVIEw textVIEw;@OverrIDeprotected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); TextVIEw tv = (TextVIEw) findVIEwByID(R.ID.tv); /* * Get the data from push notification and display it in TextVIEw * */ tv.setText("Message retrIEve from Push Notification");}
这是我的MyFirebaseMessagingService.java
@OverrIDepublic voID onMessageReceived(RemoteMessage remoteMessage) { sendNotification(remoteMessage.getNotification().getbody());}//This method is only generating push notification//It is same as we dID in earlIEr postspublic voID sendNotification(String messageBody) { Intent intent = new Intent(this,MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_top); PendingIntent pendingIntent = PendingIntent.getActivity(this,intent,PendingIntent.FLAG_ONE_SHOT); Intent notificationIntent = new Intent(this,MainActivity.class); notificationIntent.putExtra("message",messageBody); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_top | Intent.FLAG_ACTIVITY_SINGLE_top); Uri defaultSoundUri = ringtoneManager.getDefaultUri(ringtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallicon(R.mipmap.ic_launcher) .setContentTitle("Peoplelink Push Notification") .setContentText(messageBody) .setautoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); notificationmanager notificationmanager = (notificationmanager) getSystemService(Context.NOTIFICATION_SERVICE); notificationmanager.notify(0,notificationBuilder.build());}
最佳答案如果您想为您的AndroID活动发送消息,请使用FirebaseMessagingService.你可以使用EventBus.一个androID优化的事件总线que简化了活动,碎片,线程,服务等之间的通信.更少的代码,更好的质量.将EventBus添加到build.gradle文件中
compile 'org.greenrobot:eventbus:3.0.0'
注册MainActivity.java并创建onMessageEvent方法.
public class MainActivity extends AppCompatActivity {TextVIEw textVIEw;@OverrIDeprotected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); textVIEw = (TextVIEw) findVIEwByID(R.ID.tv); EventBus.getDefault().register(this);}@Subscribe(threadMode = ThreadMode.MAIN) public voID onMessageEvent(String message) { textVIEw.setText(message);};
并在MyFirebaseMessagingService.java中使用EventBus.getDefault().post()
@OverrIDepublic voID onMessageReceived(RemoteMessage remoteMessage) { EventBus.getDefault().post(remoteMessage.getNotification().getbody());}
总结 以上是内存溢出为你收集整理的java – 如何从Firebase推送通知中获取数据并将其显示在Android Activity中?全部内容,希望文章能够帮你解决java – 如何从Firebase推送通知中获取数据并将其显示在Android Activity中?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)