0

I'm using firebase data base to create my chat applicaiton. Now that I have sucessfully completed my chat application, but when new message arrives I would like to notify user with sound and NOtification in Notification bar even when the app is not running.

I used the below code to do that

 NotificationCompat.Builder builder =  new NotificationCompat.Builder(this)  
    .setSmallIcon(R.drawable.ic_launcher)  
    .setContentTitle("Notifications Example")  
    .setContentText("This is a test notification");  


  Intent notificationIntent = new Intent(this, MenuScreen.class);  

  PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,   
    PendingIntent.FLAG_UPDATE_CURRENT);  

 builder.setContentIntent(contentIntent);  
 builder.setAutoCancel(true);
 builder.setLights(Color.BLUE, 500, 500);
 long[] pattern = {500,500,500,500,500,500,500,500,500};
 builder.setVibrate(pattern);
 builder.setStyle(new NotificationCompat.InboxStyle());
 builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
 NotificationManager manager = (NotificationManager) 
 getSystemService(Context.NOTIFICATION_SERVICE);  
 manager.notify(1, builder.build());  

But it only set alarm when i open the chat activity, then aftearwards when new message arrives it does nothing.

Here is my chat activity code

package com.nepalpolice.mnemonics.chat;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.media.ToneGenerator;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.firebase.database.ChildEventListener;
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.iid.FirebaseInstanceId;
import com.google.firebase.messaging.RemoteMessage;
import com.nepalpolice.mnemonics.R;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by filipp on 6/28/2016.
 */
public class Chat_Room  extends AppCompatActivity{
    private Button btn_send_msg;
    private EditText input_msg;
    private TextView chat_conversation;
    private Toolbar mainToolbar;
    private String user_name,room_name;
    private DatabaseReference root ;
    private String temp_key;

    @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();

        mainToolbar = (Toolbar) findViewById(R.id.main_chat);
        setSupportActionBar(mainToolbar);
        getSupportActionBar().setTitle(" Room - "+room_name);


        root = FirebaseDatabase.getInstance().getReference().child(room_name);





        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);
                input_msg.getText().clear();

            }
        });




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

            }
        });

    }

    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");
        }

        
    }
   
  
}

Here is my Firebase Data structure file

Firebase Data Structure

Any help is appreciated. Thanks in advance.

Community
  • 1
  • 1
Raj Lama
  • 23
  • 7

1 Answers1

0

If you are using FCM, you need to understand this part of the doc before proceeding:

The onMessageReceived is provided for most message types, with the following exceptions which are listed below:

  1. Notification messages delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default
  2. Messages with both notification and data payload, both background and foreground. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

So if you need to decide the type of payload you re sending to the android device. You may want to go for Message with both Notifications and data payload so that onMessageRecieved() is invoked at all times.

You can find more details Here

Jerry Okafor
  • 3,710
  • 3
  • 17
  • 26
  • @Po1ocio well that is good solution. Any tutorials where I can find how to send data payload with Notification so that it will sound or alert the users?? – Raj Lama Apr 13 '18 at 15:38
  • Ok, i will send a code snippet for you in nodejs so that you can use it in combination with firebase cloud functions or any other server of your choice. – Jerry Okafor Apr 13 '18 at 15:53
  • You can do that with [Firebase Messaging Admin SDK](https://firebase.google.com/docs/cloud-messaging/admin/send-messages) – Jerry Okafor Apr 13 '18 at 15:58