I have the following code which brings my Android app to foreground once I receive a Firebase Push notification or FCM.
@ReactMethod
public void backToForeground() {
Context context = getAppContext();
String packageName = context.getApplicationContext().getPackageName();
Intent focusIntent = context.getPackageManager().getLaunchIntentForPackage(packageName).cloneFilter();
Activity activity = getCurrentActivity();
boolean isOpened = activity != null;
if (isOpened) {
focusIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
activity.startActivity(focusIntent);
} else {
// Custom flag to check whether app was started from this method
focusIntent.putExtra("FLAG_ON_CALL_BRING_TO_FRONT", "true");
focusIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK +
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED +
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD +
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getReactApplicationContext().startActivity(focusIntent);
}
}
Now in MainActivity I have used the bundle as following:
@Override
protected void onCreate(Bundle savedInstanceState) {
SplashScreen.show(this);
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
// Custom flag defined in AppStateManagerModule
String extraString = extras.getString("FLAG_ON_CALL_BRING_TO_FRONT");
if (extraString != null) {
getWindow()
.addFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
);
}
}
}
My code is working correctly in the following cases:
When FCM is received on device:
Now here's the case which doesn't work properly:
Action is performed fine in point 5 but it doesnt show on top of lock screen.
If app is active or in background, after phone is locked it will still be considered active. So since an activity is active, it can't be thrown on top with intent since its already used to activate the activity.
We need to add window flags on an active activity to bring it to front like this:
if (isOpened) {
focusIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
activity.startActivity(focusIntent);
// Adding Window Flags to bring app forward on lock screen
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
activity.getWindow()
.addFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
);
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.