我正在尝试使用实时消息应用程序(不像WhatsApp这样的聊天应用程序,我有一个发布者和许多订阅者)。
我希望它在收到新消息时发送通知。
这是我的代码(有错误):
mRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
Message message = postSnapshot.getValue(Message.class);
messages.add(0, message.getTitle() + '\n' + message.getMessage(), NotificationCompat.Builder mBuilder = //cannot resolve symbol 'mBuilder'
new NotificationCompat.Builder(this) //builder (android.content.Context) in Builder cannot be applied to (anonymous com.firebase.client.ChildEventListener)
.setSmallIcon(R.drawable.logo_he_digita_homepage)
.setContentTitle(message.getTitle())
.setContentText(message.getMessage()); //')' expected
Intent resultIntent = new Intent(this, updates.class); //Cannot resolve constructor 'Intent(anonymous com.firebase.client.ChildEventListener, java.lang.Class<com.inbar.amit.ksharet>)'
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); //create (android.content.Context) in TaskStackBuilder cannot be applied to (anonymous com.firebase.client.ChildEventListener)
stackBuilder.addParentStack(updates.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(124453245, mBuilder.build()););
}
adapter.notifyDataSetChanged();
}
我正在使用Android Studio。
感谢您的回答。
答案 0 :(得分:0)
首先,请注意,将为数据库中已有的每个子项调用onChildAdded
,并在您开始侦听后添加每个子项,因此您最终会收到数据库中每条消息的通知。
<强>更新强>
因此,您需要为此代码创建一个新函数,因为它在侦听器类中不起作用。以下代码应该适合您:
mRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
Message message = postSnapshot.getValue(Message.class);
messages.add(0, message.getTitle() + '\n' + message.getMessage());
sendNotification(message);
}
adapter.notifyDataSetChanged();
}
在其他方法之外,添加此方法:
public void sendNotification(Message message) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo_he_digita_homepage)
.setContentTitle(message.getTitle())
.setContentText(message.getMessage());
Intent resultIntent = new Intent(this, updates.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(updates.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(124453245, mBuilder.build());
}