Home » Android » service – In Android how to get current Activity context when extend FirebaseMessagingService calling on onMessageReceived?

service – In Android how to get current Activity context when extend FirebaseMessagingService calling on onMessageReceived?

Posted by: admin June 16, 2020 Leave a comment

Questions:

My Code for integrate FCM..
I want to get current activity context when push arrives.
Purpose for casting listener with context.

Snippet code here…

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFMService";
private NotificationListener notificationListener;
private Context context;
private int count=0;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "FCM Message Id: " + remoteMessage.getMessageId());

    RemoteMessage.Notification notification = remoteMessage.getNotification();
    Map<String, String> data = remoteMessage.getData();
    Log.e("FROM", remoteMessage.getFrom());

    count++;

    //sendNotification(notification, data);

    setNotificationCount();
}


private void setNotificationCount(AlertList alertList) {
    notificationListener = (NotificationListener) context;
    notificationListener.onNotificationMessage(count);
}

private void sendNotification(RemoteMessage.Notification notification, Map<String, String> data) {
    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

    Intent intent = new Intent(this, AlertOnMap.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("AlertDetails", (Serializable) alertList);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
            .setContentTitle(notification.getTitle())
            .setContentText(notification.getBody())
            .setAutoCancel(true)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setContentIntent(pendingIntent)
            .setContentInfo(notification.getTitle())
            .setLargeIcon(icon)
            .setColor(Color.RED)
            .setSmallIcon(R.mipmap.ic_launcher);

    try {
        String picture_url = data.get("picture_url");
        if (picture_url != null && !"".equals(picture_url)) {
            URL url = new URL(picture_url);
            Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            notificationBuilder.setStyle(
                    new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(notification.getBody())
            );
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
}

}

created Interface

public interface NotificationListener {

public void onNotificationMessage(AlertList alertList, int i);

}

calling on another class..like

public class Header extends AppCompatActivity implements NotificationListener{

 /*--------------- OnNotification ----------------------*/

@Override
public void onNotificationMessage(final int count) {

    Log.d("Notification count", "--->   In Header Count = " + count);

}

}

i’want to get current activity context in service without any context reference from another class.

How to&Answers:

If I understood correctly, basically you want to cast context of activity to interface that activity implements. The issue is: you can not get current activity context, because maybe/probably there is no current activity at all. There is some context available but this context can’t be used for what you want. Let me explain it:

Let’s say user didn’t use app for a week and he finished all activities, exited app (or OS released memory and cleaned everything). Service is still running in a background and when push message comes it will react according to your code (let’s say you immediately want to show notification). If you need context in this moment, for example for notification icon color, you can use following context:

int color = ContextCompat.getColor(getApplicationContext(), R.color.colorAccent);

getApplicationContext() will give you needed context but that is of course not activity context, because there is still no activity (all of them finished days ago)

Hope this explanation helps to understand the concept here.
For understanding even better what kind of contexts exist check Context,
What Context?

Answer:

I did it from this way

@Override
public void onMessageReceived(final RemoteMessage remoteMessage) {

    if (Manager.getInstance().actualContext != null)
    {
        //Let this be the code in your n'th level thread from main UI thread
        Handler h = new Handler(Looper.getMainLooper());
        h.post(new Runnable() {
            public void run()
            {
                CFAlertDialog.Builder pDialog = new CFAlertDialog.Builder(Manager.getInstance().actualContext)
                        .setDialogStyle(CFAlertDialog.CFAlertStyle.NOTIFICATION)
                        .setTextGravity(Gravity.CENTER)
                        .setMessage(remoteMessage.getNotification().getBody())
                        .setTitle(remoteMessage.getNotification().getTitle());

                pDialog.show();

            }
        });
    }

    super.onMessageReceived(remoteMessage);
}

and

Manager.getInstance().actualContext is a variable Context in my Manager (Singletone class)

Just you have to instance in all your Activities

@Override
protected void onResume() {
    super.onResume();
    Manager.getInstance().actualContext = this;
}

And destroy it

@Override
protected void onDestroy() {
    super.onDestroy();
    Manager.getInstance().actualContext = null;
}