[英]Android bring app to foreground on Firebase notification
I have the following code which brings my Android app to foreground once I receive a Firebase Push notification or FCM.一旦我收到 Firebase 推送通知或 FCM,我有以下代码将我的 Android 应用程序带到前台。
@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:现在在 MainActivity 中,我使用了如下捆绑包:
@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:当设备接收到 FCM 时:
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.动作在第 5 点执行得很好,但它没有显示在锁定屏幕的顶部。
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:我们需要在活动活动上添加 window 标志,以将其置于最前面,如下所示:
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
);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.