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

时间:2017-11-08 01:30:44

标签: android firebase service notifications

所以我创建了一个消息应用程序,允许用户相互通信。我正在使用Firebase来执行此操作。现在问题是我想在后台创建通知(当应用程序在后台或关闭时)。类似于messenger / whatsapp,你会收到未读消息的通知。

我该如何创建呢?

chat-room.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();





    }



}

}

1 个答案:

答案 0 :(得分:0)

要向客户发送推送通知,您需要运行应用服务实例(例如在Google App Engine上),或者通过功能更轻松地实现Firebase功能。简单来说,您需要在服务器上运行一段代码,以响应您的请求并发送通知。

由于您已经在使用Firebase数据库,因此我发现Firebase功能是最简单的方法。您需要编写函数然后进行部署。

--> firebase deploy --only functions

只要写入新数据(onCreate()),更新甚至从数据库中删除,就可以触发您的函数。 (想象一下,您编写的函数使得只要在“messages”节点将新消息写入数据库时​​它就会触发)。

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

//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功能发送通知的示例,请参阅Here。有关Firebase功能样本,请参阅Here。有关Firebase功能和触发器的更多信息,请参阅here

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