简体   繁体   English

收到新消息Firebase Android时获取通知

[英]Get notification when there is a new message Firebase Android

I'm making a chat app. 我正在做一个聊天应用。 I use this code to detect new messages (on Firebase database) and then notify users: 我使用此代码检测新消息(在Firebase数据库上),然后通知用户:

package com.tungvuong.dangeralarm;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.firebase.client.Firebase;
import com.google.firebase.FirebaseError;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import static com.facebook.login.widget.ProfilePictureView.TAG;

public class receive extends IntentService {
    public receive() {
        super("receive");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String tinmoi = dataSnapshot.child("messageText").getValue(String.class);
                Intent intent = new Intent(receive.this, chat.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                PendingIntent pendingIntent = PendingIntent.getActivity(receive.this, 0, intent, 0);
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(receive.this, "M_CH_ID");

                notificationBuilder.setAutoCancel(true)
                        .setDefaults(Notification.DEFAULT_ALL)
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.drawable.emergency_icon)
                        .setContentTitle("Có tin mới!")
                        .setContentText(tinmoi)
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true);
                NotificationManager notificationManager = (NotificationManager) receive.this.getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(1, notificationBuilder.build());
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d(TAG, databaseError.getMessage()); //Log errors
            }
        };

        rootRef.addValueEventListener(valueEventListener);

    }
}

But when I test it by downloading the database from the Firebase console then added a new entry into the json file using Notepad++ and then finally I uploaded it to the console (I don't have 2 phones to test this so I have to change the json file), the app didn't notify users or anything. 但是当我通过从Firebase控制台下载数据库进行测试时,然后使用Notepad ++将新条目添加到json文件中,然后最终将其上传到控制台(我没有2部手机可以对此进行测试,因此我必须更改json文件),则该应用未通知用户或其他任何信息。

Here are my Firebase database: 这是我的Firebase数据库:

My Firebase database 我的Firebase数据库

在此处输入图片说明

As you can see, the MessageText is what the listener listens to. 如您所见, MessageText是侦听器侦听的内容。 This app is a group chat app, and it only allows users to sign in anonymously. 该应用程序是一个群聊应用程序,仅允许用户匿名登录。

FirebaseDatabase.getInstance().getReference()
                .child("danger-alram")
                .orderByChild("messageTime")
                .startAt(timeStampInMill) // last message time stamp goes here for first time it is zero
                .addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                        // You will get newly added child (messages) here...

                    }

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

                    }

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) {

                    }

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

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

While you are uploading message to firebase you will get onComplete() method 当您将消息上传到Firebase时,您将获得onComplete()方法

FirebaseDatabase.getInstance().getReference()
            .child("danger-alram")
            .push().setValue(newMessage, new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
            // send push notification to other group member using their firebase device id.
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM