0

나는 서비스를 시작중포 기지 데이터베이스 알림

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; 
    } 

을 그리고 다음은 잠자는 인쇄물을 생산 ... 한 번만 그 후에 오류. null 체크를 제거하면 null 포인터가 생깁니다. 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, Thread : 신호 3에 반응 중' – Nikola

+0

Firebase에서 데이터를 검색하는 것은 비동기식이므로 'firebase()'메소드 호출은 코드 실행을 계속합니다. 알림을 표시하려면'onChildChanged()'메소드 안에 스레드 작업을 수행해야합니다. 왜냐하면 그 aproach를 사용하면'notifyMessage '값을 변경할 수 있기 때문입니다. 그리고 각 키에 대해 새로운'childEventListener'를 시작하고 동일한 부울 값을 사용하는 것을 볼 수 있습니다. –

관련 문제