3

Hy everyone, I am developing an app where I am using Firebase Cloud Messaging. But I have situation where I don't want to user see when notification with data messages is received. I have solved that with deleting function sendNotification from myFirebaseMessagingService, but that works only when my app is in the foreground. My question is: When app is in the background and notification comes to the system tray, how to set the code so that notification icon would not be displayed?

Here is my MainActivity:

public class MainActivity extends AppCompatActivity {
Button dugme, dugme2, dugmeBaza, dugmeToken;
DataBaseHelper db;
Cursor c;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("onCreate", "ONCREATE");
    db=new DataBaseHelper(this);
    final Intent intent=getIntent();
    setContentView(R.layout.activity_main);
    String msg = getIntent().getStringExtra("click_action");
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    if (msg != null)
    {
        Log.d("MSG", msg);
        if (msg.equals("goToFragment1")) {
            Fragment1 fragment1 = new Fragment1();
            fragmentTransaction.replace(R.id.myFragment, fragment1);
            Log.d("FragmentTransaction", "Fragment je promenjen u onCreate!");
            fragmentTransaction.commit();
            Log.d("Create", "Kraj onCreatea");

        }
    }

    dugme = (Button) findViewById(R.id.dugme1);
    dugme2 = (Button) findViewById(R.id.subscribe);
    dugme.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Fragment fragment = null;
            if (view == dugme) {
                fragment = new Fragment1();
            }
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.myFragment, fragment);
            transaction.addToBackStack(null);
            transaction.setTransition(FragmentTransaction.TRANSIT_NONE);
            transaction.commit();
        }
    });


    dugme2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FirebaseMessaging.getInstance().subscribeToTopic("android");
            Log.d("Log", "Uspesno ste se pretplatili");
        }
    });
    dugmeBaza=(Button)findViewById(R.id.dugmeZabazu);
    viewAll();
    dugmeToken=(Button)findViewById(R.id.TokenButton);
    dugmeToken.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            Log.d("TOKEN", "Refreshed token: " + refreshedToken);
        }
    });


@Override
protected void onPause() {
    super.onPause();  // Always call the superclass method first

    Log.d("onPause", "Pauza");
}
public void viewAll(){

    dugmeBaza.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           Cursor res= db.getAlldata();
            if(res.getCount()==0) {
                //show message
                showMessage("Error", "Nothing found");


                return;

            }
            StringBuffer buffer=new StringBuffer();
            while (res.moveToNext()){
                buffer.append("Id: " + res.getString(0) + "\n");
                buffer.append("poruka: " + res.getString(1));

            }
            showMessage("Data", buffer.toString());
        }
    });
}
public void showMessage(String title, String message){
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();
}
public void Ubaci(){
    String msg=getIntent().getStringExtra("poruka");
    db.insertMsg(msg);
}

And here is myFirebaseMessagingService:

public class myFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG="MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    Log.d("onMessageReceived", "Pozvana funkcija onMessageReceived");
    Log.d(TAG, "From " + remoteMessage.getFrom());
    Log.d(TAG, "Body " + remoteMessage.getNotification().getBody());
    Log.d(TAG, "Location " + remoteMessage.getNotification().getClickAction());
    Log.d(TAG, "Value " + remoteMessage.getData().get("click_action"));

3 Answers3

9

This is actually controllable by the Sender of push notification. As per current documentation:

Notification: GCM automatically displays the message to end user devices on behalf of the client app. Notifications have a pre-defined set of user-visible keys. Set notification payload. May have optional data payload. Always collapsible.

Data: Client app is responsible for processing data messages. Data messages have only custom key/value pairs. Set data payload only. Can be either collapsible or non-collapsible.

To disable auto display of notifications when app is in background, make the sender not send "notification" part of payload and send everything in "data" part of the payload. That way the app code will always handle incoming message. Then it may chose to display a notification for it or not.

S.D.
  • 29,290
  • 3
  • 79
  • 130
  • So, if I understand correctly, sender (in my case app server) decides if notification icon will be shown, not me on Android (My task is to provide connection for FCM on android device)? –  Jun 22 '16 at 11:39
  • That's it how it is for now. It's an additional feature they are giving to the sender server. You can make server send only "data" , then you can decide in app whether to show notification or not. – S.D. Jun 22 '16 at 11:48
  • Okay, but how I could to decide in app if I want to show notification if server sends only data? –  Jun 22 '16 at 11:56
  • "data" object can have any form of data inside. For example `data.eventType:NEW_COMMENT`, `data.from:user02` etc. App side code can decide for which events the notification is to be shown, what text should be shown and which Activity to be opened when it is clicked. – S.D. Jun 22 '16 at 12:00
  • I don't understand what you are asking. When you receive a push message you can read the data from the `data` tag and then do with it whatever you like. Doing something in the background, showing a notification etc. The `notification` tag is basically useless in most situations, just use the `data` tag instead. As you rightly assumed it should be the mobile developers responsibility to show notifications on the device. – Xaver Kapeller Jun 22 '16 at 12:01
  • Well I want to send from server request for location on android with cloud messaging. I want to send that request in form of message from cloud, but when that request is received I dont want to notification is shown on system tray . I don't know If I was understandable..... –  Jun 22 '16 at 12:10
2

You can achieve this by overriding handleIntent method and commenting/removing super.handleIntent(intent) in FirebaseMessagingService;

Which basically will be called if the app is in background and notification tag is present in the payload.

Extend FirebaseMessagingService class and you will have

@Override public void handleIntent(Intent intent) { // your code should be here }

once it comes here u can customize your own NoificationManager

this method can only be overridden before fcm 11.0.6

-1

I disable the notification in the system tray. I changed the sctructure of the message.

I used python to send notification in the server side. So I changed the message_body by data_message(It's a dictonary in python), that's all that I changed, It's work fine!!

user1812668
  • 83
  • 1
  • 5