0

The aim is to make a notification show up as a notification and the contents of the notification also show on the main activity using firebase. I have tried using intents but it doesn't work. Any help will be much appreciated.

Here is the sender code (MyfirebaseMessagingService)

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import android.os.Bundle;
import android.widget.TextView ;
 import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
     


    super.onMessageReceived(remoteMessage);
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        String dodo = "Kwifo";
        String message = "Wan Ma bu";
         /*  String title = remoteMessage.getData().get("message").toString() ;
           String message = remoteMessage.getData().get("data").toString() ;*/
        //   String title1 = remoteMessage.getData().get("title").toString();

        Intent intent = new Intent(this, MyFirebaseMessagingService.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("data",dodo);   //i will love to send data to the MainActivity
        intent.putExtra("message",message);
        startActivity(intent);




    }
      if (remoteMessage.getNotification() != null) {

    Log.d(TAG, "Message Body: " + remoteMessage.getNotification().getBody());
          String msg = remoteMessage.getNotification().getBody();
         Toast.makeText(MyFirebaseMessagingService.this, msg, Toast.LENGTH_SHORT).show();



    }
    Notification notification = new NotificationCompat.Builder(this)

            .setContentTitle(remoteMessage.getNotification().getTitle())
            .setContentText(remoteMessage.getNotification().getBody())
            .setSmallIcon(R.mipmap.ic_launcher)
            .build();




 NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
    manager.notify(123, notification);

}


}

and here is the receiver code (MainActivity)

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.TextView ;
import android.app.PendingIntent ;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.gson.Gson;

import retrofit2.Call;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {


private static final String TAG = "MainActivity";
public static final String TOPIC = "/topics/deals";

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


    




    if (getIntent().getExtras() != null) {
                 for (String data : getIntent().getExtras().keySet()) {
 String title = getIntent().getExtras().getString("data"); //from MyFirebaseMessagingService
         // String content = getIntent().getExtras().getString("message","Default message");
                                    //Log.d(TAG, "Key: " + Message + " Value: " + title);

                                 //   String  title =getIntent().getStringExtra("data");
                                    String  content =getIntent().getStringExtra("message");

                                    TextView tvNotify = findViewById(R.id.tradeidea) ;
                                    tvNotify.setText(title) ;
                     // tvNotify.setText( "Key: " + title + " Value: " + content) ;
              Toast.makeText(MainActivity.this,   content,Toast.LENGTH_SHORT).show();


                                }
                            } 



    FirebaseMessaging.getInstance().subscribeToTopic(TOPIC)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    String msg = ("Ready to recieve Trading Data");
                    if (!task.isSuccessful()) {
                        msg = getString(R.string.msg_subscribe_failed);
                    }
                    Log.d(TAG, msg);
                    Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
            });





         }





 }
  • Try to use a BroadcastReceiver like in [here](https://stackoverflow.com/questions/41925692/how-to-communicate-between-firebase-messaging-service-and-activity-android) – Zain Jul 10 '21 at 23:25
  • Why `Intent intent = new Intent(this, MyFirebaseMessagingService.class);` , isn't suppose to go the your desire activity ? – Ticherhaz FreePalestine Jul 11 '21 at 02:53

2 Answers2

0

Try using a bundle.

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    ...
    Intent intent = new Intent(this, MyFirebaseMessagingService.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //Important.
    Bundle bundle = new Bundle();
    bundle.putString("data", doto);
    bundle.putString("message", message);
    //intent.putExtras(bundle);
    intent.putExtra(getPackageName() + ".MyBundle", bundle);
    startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Bundle bundle = getIntent().getExtras();
    Bundle bundle = getIntent().getBundleExtra(getPackageName() + ".MyBundle");
    String dodo = bundle.getString("data");
    String message = bundle.getString("message");
    
    //Do something...
    Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
Darkman
  • 2,941
  • 2
  • 9
  • 14
  • I tried this but it didnt work. It fires up main activity but it doesn't send data to tvNotify.setText() – Nde Kong Jul 12 '21 at 11:16
  • I tried the solutions provided in the comments there but to no avail.. I still get null values. some solutions dont even compile... I feel like shooting myself in the head. – Nde Kong Jul 14 '21 at 09:18
  • The toast is empty. – Nde Kong Jul 15 '21 at 10:59
  • I just did and it crashed the app. – Nde Kong Jul 15 '21 at 13:16
  • @NdeKong you should never feel like shooting yourself. patience is top skill for a developer. you sometimes have to unassume all your assumptions and proof them one by one. Usually this is done with breakpoints and debugger tool and using logcat. – Njuacha Hubert Jul 25 '21 at 15:10
  • Sorry but this solution is not working – Eddie Brock Aug 26 '22 at 13:01
  • @EddieBrock Here is another alternative: https://stackoverflow.com/questions/72550870/can-a-broadcast-receiver-send-information-to-an-activity-only-if-it-is-active-wi/72553085#72553085 – Darkman Aug 26 '22 at 16:48
0

MainActivity.java -- Activity

PhoneStateReceiver.java -- Background Service

MainActivity.java

public class MainActivity extends Activity {

Context context;
BroadcastReceiver updateUIReciver;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = this;

    IntentFilter filter = new IntentFilter();
    filter.addAction("service.to.activity.transfer");
    updateUIReciver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //UI update here
            if (intent != null)
                Toast.makeText(context, intent.getStringExtra("number").toString(), Toast.LENGTH_LONG).show();
        }
    };
    registerReceiver(updateUIReciver, filter);
}}

PhoneStateReceiver.java

public class PhoneStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    try {
        System.out.println("Receiver start");
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            Intent local = new Intent();
            local.setAction("service.to.activity.transfer");
            local.putExtra("number", incomingNumber);
            context.sendBroadcast(local);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}}

I hope this post is useful to you