Reputation: 890
In my android app I start a service when the user exits the app:
ArrayList<String> eventKeys = new ArrayList<>();
...
Intent intent = new Intent(this, MyService.class);
intent.putExtra("eventKeys", eventKeys);
startService(intent);
Then in my service:
public class MyService extends Service {
(fields)...
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
if (intent == null) {
System.out.println("ERROR");
return START_REDELIVER_INTENT;
}
eventKeys = (ArrayList<String>) intent.getExtras().get("eventKeys");
//here I attach listeners to firebase database
firebase();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (notifyMessage) {
sendNotification("You have a new message.");
stopSelf();
return;
}
try {
System.out.println("Sleeping...");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return START_STICKY;
}
And the following produces prints out Sleeping... just one time and after that ERROR. If I remove the null check I get a null pointer. If I remove the firebase method It works.
private void firebase(List<String> eventKeys) {
System.out.println("Set database listener");
mDataBase = FirebaseDatabase.getInstance().getReference().child("events");
for (String eventKey : eventKeys){
mDataBase.child(eventKey).child("chat").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//new message received
notifyMessage = true;
sendNotification("You have a new message.");
stopSelf();
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
}
}
This does not work and I don't have any idea what to do.
Upvotes: 0
Views: 223
Reputation: 5148
Did you declared your service in manifest?
<manifest ... >
...
<application ... >
<service android:name=".MyService " />
...
</application>
</manifest>
You don't need to create new Thread in service class, because Service by itself is an background operation. Check documentation.
Upvotes: 1