在我的Android應用我啓動服務,當用戶退出應用程序:火力地堡數據庫通知
ArrayList<String> eventKeys = new ArrayList<>();
...
Intent intent = new Intent(this, MyService.class);
intent.putExtra("eventKeys", eventKeys);
startService(intent);
然後在我的服務:
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;
}
及以下生產打印出睡...只是一次,之後錯誤。如果我刪除空檢查,我得到一個空指針。如果我刪除了firebase方法,它的工作原理。
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) {}
});
}
}
這不起作用,我也不知道該怎麼做。
你得到的錯誤是什麼? –
我沒有得到任何具體的錯誤。但是,當我更換孩子時,通知不會被髮送。我沒有提到在關閉應用程序時執行此代碼。 – Nikola
附加偵聽器時,您會忽略潛在的錯誤。實現'onCancelled'就像我在這裏寫的:http://stackoverflow.com/documentation/firebase/5548/how-do-i-listen-for-errors-when-accessing-the-database#t=201609121647524851802 –