我正在尝试首次构建聊天应用程序,我想在将新消息添加到数据库时(使用Android Studio)通知用户。
因此,与其使用云功能(因为它是如此困难),不如说我将使用在后台运行并触发对Firebase数据库的onChildadded()通知的服务。
如何编写一个服务类,该服务类将从数据库中获取引用并触发通知?
我正在使用
字符串NOTIFICATION_CHANNEL_ID =“ my_channel_id_01”;
private FirebaseDatabase database;
private DatabaseReference mFirebaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosReference;
private NotificationManager mNotificationManager ;
public NotificationCompat.Builder mBuilder ;
int some = 0;
public PushNotification() {
database = FirebaseDatabase.getInstance();
mAuth = FirebaseAuth.getInstance();
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseReference = database.getReference().child("list");
attachDatabaseReadListener();
}
protected void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mnotificationBuilder = new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("new Notification")
.setContentText("notification example")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
notificationManager.notify(0, mnotificationBuilder.build());
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
mNotificationManager.notify(some, mBuilder.build());
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
mNotificationManager.notify(some, mBuilder.build());
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
mNotificationManager.notify(some, mBuilder.build());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mFirebaseReference.addChildEventListener(mChildEventListener);
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}