'android-firebase childEventListener in service
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...
Solution 1:[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));
in a class where i want to start it. solved my problem.
-Thanx @ merterpam, for pointing out my mistake
Solution 2:[2]
There is another issue. You have not given the permission in the manifest. add this:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sambhav. K |
Solution 2 | Sambhav. K |