Firebase数据库通知

时间:2016-09-12 14:23:25

标签: android firebase firebase-realtime-database android-notifications

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

这不起作用,我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

您是否在清单中声明了您的服务?

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

您不需要在服务类中创建新的Thread,因为Service本身就是一个后台操作。检查documentation