2016-09-12 162 views
0

在我的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) {} 
     }); 
    } 
} 

這不起作用,我也不知道該怎麼做。

+0

你得到的錯誤是什麼? –

+0

我沒有得到任何具體的錯誤。但是,當我更換孩子時,通知不會被髮送。我沒有提到在關閉應用程序時執行此代碼。 – Nikola

+0

附加偵聽器時,您會忽略潛在的錯誤。實現'onCancelled'就像我在這裏寫的:http://stackoverflow.com/documentation/firebase/5548/how-do-i-listen-for-errors-when-accessing-the-database#t=201609121647524851802 –

回答

1

您是否在清單中聲明瞭您的服務?

<manifest ... > 
  ... 
  <application ... > 
      <service android:name=".MyService " /> 
      ... 
  </application> 
</manifest> 

您不需要在服務類中創建新的線程,因爲服務本身是後臺操作。檢查documentation

+0

是的,我的清單裏有這個。 – Nikola

+0

當我刪除線程,代碼工作了一段時間後,我得到:'線程[3,tid = 29740,WaitingInMainSignalCatcherLoop,線程:對信號3作出反應' – Nikola

+0

從Firebase中檢索數據是一種異步方法,因此在'firebase()'方法調用,代碼執行仍在繼續。你應該在'onChildChanged()'方法內部執行線程作業,以確保顯示你的通知,因爲使用該方法可以改變'notifyMessage'的值。我可以看到你正在爲每個鍵啓動新的'childEventListener'並使用相同的布爾值。 –