Call method in current activity from service

I am currently working on an Android project.

So far I have implemented Firebase, in particular FirebaseInstanceIdService and FirebaseMessagingService:

public class FirebaseIDService extends FirebaseInstanceIdService { private static final String TAG = "FirebaseIDService"; private Context context; @Override public void onTokenRefresh() { context = getApplicationContext(); // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.e(TAG, "Refreshed token: " + refreshedToken); SharedPreferences sharedPreferences = context.getSharedPreferences("token", context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("token", refreshedToken); editor.commit(); sendRegistrationToServer(refreshedToken); } /** * Persist token to backend. * @param token The new token. */ private void sendRegistrationToServer(String token) { SendRegistrationKey task = new SendRegistrationKey(context); task.execute(token); } 

}

 public class MessagingService extends FirebaseMessagingService { private static final String TAG = "MsgService"; /** * Called when message is received. * * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. */ @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.e(TAG, "From: " + remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.e(TAG, "Message data payload: " + remoteMessage.getData()); } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.e(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); sendNotification(remoteMessage); } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. } // [END receive_message] private void sendNotification(RemoteMessage remoteMessage) { RemoteMessage.Notification notification = remoteMessage.getNotification(); PushNotificationManager PNManager = PushNotificationManager.getInstance(getApplicationContext()); PNManager.buildNotification(notification.getTitle(), notification.getBody()); } 

I want to achieve the following:

When the application is in the background, I just want to get a simple notification in the notification center. (It already works)

BUT, when the application is in the foreground and is currently running, I want to have a different behavior: I want to use a push notification and show a warning instead.

But my question is: how can I interact with the current action from the service or what is the right way to achieve the intended behavior? It must be a simple heart, right?

Thanks in advance

+8
android firebase firebase-cloud-messaging
source share
4 answers

write this code in the application class

  public Context currentactvity = null; public Context getCurrentactvity() { return currentactvity; } public void setCurrentactvity(Context currentactvity) { this.currentactvity = currentactvity; } 

write this code in each active onresume method and set null in the onpause method

  // in onresume MyApplication.getInstance().setCurrentactvity(this); // in onpause MyApplication.getInstance().setCurrentactvity(null); 

now you can call the activity method from the service class

  if (MyApplication.getInstance().getCurrentactvity() != null && MyApplication.getInstance().getCurrentactvity() instanceof youractivityname) { ((youractivityname) MyApplication.getInstance().getCurrentactvity()).youmethodname(parameter); } 
+4
source share

how can I interact with the current action from the service or with what is the right way to achieve the intended behavior?

The best way would be to simply use an Event Bus (i.e. GreenRobot or local transfer ). Your activity registers the listener with onResume() (and unregisters with onPause() ), and your service simply broadcasts the message when the time comes.

The main advantage is that you completely separate both elements (services and activities). You also avoid the worst possible solution by directly invoking activity methods.

To find out when you are in the background or not, it is best to use Application GreenRobot ActivityLifecycleCallbacks - it makes no sense to force actions to report this, since nothing will benefit from this.

+2
source share

try the following:

This method checks all running applications and returns true or false whether the current application is in the background or in the foreground state.

  public static boolean isAppIsInBackground(Context context) { boolean isInBackground = true; ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) { List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) { if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { for (String activeProcess : processInfo.pkgList) { if (activeProcess.equals(context.getPackageName())) { isInBackground = false; } } } } } else { List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); ComponentName componentInfo = taskInfo.get(0).topActivity; if (componentInfo.getPackageName().equals(context.getPackageName())) { isInBackground = false; } } return isInBackground; } 
+1
source share

Try

1. Register your own broadcast receiver in your activity.

 context.registerReceiver (myBroadcastReceiver, new IntentFilter ("CUSTOM_ACTION")); private final BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver () { @Override public void onReceive (Context context, Intent intent) { //Do something } }; 

2. Send a broadcast from your service

 Intent intent = new Intent ("CUSTOM_ACTION"); context.sendBroadcast (intent) 
0
source share

All Articles