2016-09-12 145 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'并使用相同的布尔值。 –