如何为我的聊天应用程序创建通知服务?

如何为我的聊天应用程序创建通知服务?

问题描述:

所以我创建了一个消息应用程序,它允许用户相互通信.我正在使用 Firebase 来做到这一点.现在的问题是我想在后台创建一个通知(当应用程序在后台或关闭时).类似于 Messenger/whatsapp,您会在其中收到未读消息的通知.

So I have created a message application which allows users to communicate with each other. I am using Firebase to do this. now the problem is I want create a notification in the background (when the app is in the background or closed). similar to messenger/whatsapp where you get a notification for unread messages.

我该如何创建它?

聊天室.java

public class Chat_Room  extends AppCompatActivity{

private Button btn_send_msg;
private EditText input_msg;
private TextView chat_conversation;

private String user_name,room_name;
private DatabaseReference root ;
private DatabaseReference Mnotification;
private String temp_key;


NotificationCompat.Builder notification;
private static final int  uniqueID = 1995;

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

    btn_send_msg = (Button) findViewById(R.id.btn_send);
    input_msg = (EditText) findViewById(R.id.msg_input);
    chat_conversation = (TextView) findViewById(R.id.textView);







    user_name = getIntent().getExtras().get("user_name").toString();
    room_name = getIntent().getExtras().get("room_name").toString();
    setTitle(" Room - "+room_name);

    root = FirebaseDatabase.getInstance().getReference().child(room_name);
    Mnotification = FirebaseDatabase.getInstance().getReference().child("notifications");

    btn_send_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Map<String,Object> map = new HashMap<String, Object>();
            temp_key = root.push().getKey();
            root.updateChildren(map);

            DatabaseReference message_root = root.child(temp_key);
            Map<String,Object> map2 = new HashMap<String, Object>();
            map2.put("name",user_name);
            map2.put("msg",input_msg.getText().toString());

            message_root.updateChildren(map2);
            //not();
            //test();

        }
    });

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

            append_chat_conversation(dataSnapshot);

        }

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

            append_chat_conversation(dataSnapshot);

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

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

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });




}


public void test() {

    String tkn = FirebaseInstanceId.getInstance().getToken();
    String text = chat_msg;
   not();
    Log.d("App", "Token[" + tkn + "]");





}


public void not(){



    notification = new NotificationCompat.Builder(this);
    notification.setAutoCancel(true);

    notification.setSmallIcon(R.drawable.downloadfile);
    notification.setTicker("This is the tocken");
    notification.setWhen(System.currentTimeMillis());
    notification.setContentTitle(user_name);
    notification.setContentText(chat_msg);


    Intent intent = new Intent(Chat_Room.this, Message.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setContentIntent(pendingIntent);


    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.notify(uniqueID, notification.build());





}

private String chat_msg,chat_user_name;

private void append_chat_conversation(DataSnapshot dataSnapshot) {

    Iterator i = dataSnapshot.getChildren().iterator();

    while (i.hasNext()){

        chat_msg = (String) ((DataSnapshot)i.next()).getValue();
        chat_user_name = (String) ((DataSnapshot)i.next()).getValue();












        chat_conversation.append(chat_user_name +" : "+chat_msg +" \n");
        input_msg.setText("");
        test();





    }



}

}

要向客户端发送推送通知,您需要运行应用服务实例(例如在 Google App Engine 上),或者现在有了 Firebase 函数就更容易了,通过函数.简而言之,您需要在服务器上运行一段代码来响应您的请求并发送通知.

For sending push notifications to clients you would need to either run an app serve instance (for example on Google App Engine) or even easier now that there is Firebase functions, via a function. In simple words you need to have a piece of code running on a server which reacts to your requests and sends the notification.

我发现 Firebase 函数是最简单的方法,因为您已经在使用 Firebase 数据库.您需要编写函数,然后部署它们.

I have found Firebase functions to be the easiest way to do that since you are already using Firebase Database. You need to write your functions and then deploy them.

--> firebase deploy --only functions

每当写入新数据(onCreate())、更新甚至从数据库中删除新数据时,都可以触发您的函数.(想象一下,您编写的函数会在消息"节点处将新消息写入数据库时​​触发).

Your functions can be triggered whenever new data is written (onCreate()), updated or even removed from database. (Imagine, you write your functions such that it triggers whenever a new message is written to your database at "messages" node).

此外,您需要在您的数据库中存储用户唯一消息令牌"生成的客户端,因为您稍后需要在您的函数中使用它来发送通知.在您的函数中,您需要从数据库中检索该令牌并通过 SDK 发送通知.这是我解释的简化代码:

Also, you need to store users unique messaging "token"s generated client side in your database because you need it later in your function to send the notification. In your function, you need to retrieve that token from database and send the notification via SDK. Here is a simplified code of what I explained:

//your imports ; see sample linked below for a complete example
//imagine your functions is triggered by any new write in "messages" node in your database
exports.sendNotification = functions.database.ref('/messages/{keyId}').onWrite(

      //get the token that is already saved in db then ; 
      const payload = {
      notification: {
        title: 'You have a new follower!',
        body: `${follower.displayName} is now following you.`,
        icon: follower.photoURL
      }
      };

      admin.messaging().sendToDevice(tokens, payload); //which is a promise to handle

}); 

有关通过 Firebase 函数发送通知的示例,请参阅此处.有关 Firebase 函数示例,请参阅此处.有关 Firebase 函数和触发器的更多信息,请参阅此处.

For sample on sending notification via Firebase functions see Here. For Firebase function samples see Here. More on Firebase functions and triggers see here.

有关更多说明,请参阅此处(请记住,这是在 Firebase 函数之前编写的),因此它假设您将其部署到应用服务器实例.此外,此处是有关使用云函数(Firebase 函数)的更多信息用于发送通知.

For some more explanation see here (keep in mind this was written before Firebase functions) and so it assumes you are deploying it to an app server instance. Also, here is more information on using cloud functions (Firebase functions) for sending notifications.