用于侦听Firebase数据更改的服务

时间:2017-06-17 11:12:09

标签: android firebase service firebase-realtime-database

基本上我想要做的是设置一个服务来监听Firebase数据库中的更改,并在发生更改时显示通知。 我已经找到了解决方案,我试图从那里开始,但每当我想进入启动服务的活动时,我的活动就不会显示,所以我不知道我的服务是否有效

这就是我的Manifest文件的外观:

 <receiver android:name=".ReceiverCall"
            android:enabled="true">
            <intent-filter>
                <action android:name="RESTART_SERVICE" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

这是我的ReceiverCall类:

public class ReceiverCall extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        context.startService(new Intent(context, PopupService.class));;
    }

}

我启动服务的活动:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        startService(new   Intent(MainActivity.this, PopupService.class));
        finish();

似乎没有出现在屏幕上。

这是我的服务类:

public class PopupService extends Service {
    FirebaseDatabase database;
    public static DatabaseReference RequestRef;

    @Override
    public void onCreate()
    {
        super.onCreate();
        android.os.Debug.waitForDebugger();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        database = FirebaseDatabase.getInstance();
        RequestRef = database.getReference("counties").child("0").child("name");
        ListenerForRequestDone();
        return START_STICKY;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent("RESTART_SERVICE");
        sendBroadcast(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void ListenerForRequestDone(){
        RequestRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                Log.d("DEBUG", "Database change");
                 //here I want to call the method that opens the notification that some data has changed
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }


}

0 个答案:

没有答案