问题
in my android application i am trying to implement childEventListener of firebase database even when the app is not active. means whenever the firebase db particular child has a new entry it should notify the user.. so till now i have done with this,
i have declared service in manifest file as
<service android:name=".ChildEventListener"/>
then my ChildEventListener class is as follows
public class ChildEventListener extends Service {
FirebaseAuth auth;
NotificationCompat.Builder builder;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
retrivemsg();
return START_STICKY;
}
public void retrivemsg()
{
DatabaseReference mdb= FirebaseDatabase.getInstance().getReference("messages/"+auth.getCurrentUser().getUid());
builder=new NotificationCompat.Builder(this,"onchildadded");
mdb.addChildEventListener(new com.google.firebase.database.ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String msg=dataSnapshot.child("msg").getKey();
builder.setSmallIcon(R.drawable.send);
builder.setContentTitle("child added");
builder.setContentText(msg);
NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
but i tried, but no luck... even the new child is added, i am not getting any notification.... not even when the app is in foreground...
回答1:
actually we can start a service in manifest fie. but in my case my mistake was i didnt added start service statement where i actually want to start it. so just by adding
startService(new Intent(this, ChildEventListener.class));
i a class where i want to start it. solved my problem.
-Thanx @ merterpam, for pointing out my mistake
来源:https://stackoverflow.com/questions/46618432/android-firebase-childeventlistener-in-service