how to create Notification SERVICE for my chat app

2019-08-22 04:17发布

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.

how can i create this?

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条回答
smile是对你的礼貌
2楼-- · 2019-08-22 04:34

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.

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

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).

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

}); 

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

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.

查看更多
登录 后发表回答