[英]Bring the Android app to foreground after recieving a notification push like the application launcher
[英]Is there a way to bring an application to foreground on push notification receive?
例如在WhatsApp中。 当我打电话给某人时,即使应用程序处于后台或被杀,活动也会打开。 我该如何实现呢? 此外,我不希望我的应用程序启动新活动,因为此应用程序将在受控环境中使用。 我的申请将始终在后台。 用户将在应用程序打开(后台或前台)时收到通知,因此当他们收到此通知时,他们的应用程序应自动应用(不启动新活动),只需将当前活动推送到前台即可。
为了更好地理解这是我想要实现的:用户A打开应用程序,然后最小化它。 所以现在他有资格接收通知。 该应用程序当前在活动A上。当用户收到通知时,我们将收到的数据推送到列表中并将其显示在活动A上。我想要做的是当用户A收到推送通知以将活动A推送到前台时不再创建活动A或任何类似的东西,只是将它带到前台。 任何帮助将非常感激。 谢谢!
您可以使用意图标志。
Intent.FLAG_ACTIVITY_SINGLE_TOP
你的代码就像
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
Intent intent= new Intent(this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
}
按照这个答案 。 您可以在活动中注册广播,或直接从onMessageReceived()
调用该方法
收到消息后,启动NotificationActivity
将检查您的应用程序是否已经运行然后finish
该活动将为您带来最后一次打开的活动 ,如果应用程序未运行将启动您的MainActivity
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
startActivity(new Intent(this , NotificationActivity.class));
}
}
public class NotificationActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// If this activity is the root activity of the task, the app is not running
if (isTaskRoot())
{
// Start the app before finishing
Intent startAppIntent = new Intent(getApplicationContext(), MainActivity.class);
startAppIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startAppIntent);
}
// Now finish, which will drop the user in to the activity that was at the top of the task stack
finish();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.