Android-从广播接收器启动应用程序 [英] Android - launch app from broadcast receiver

查看:376
本文介绍了Android-从广播接收器启动应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望广播接收器以这种方式启动我的应用程序:

I want the broadcast receiver to launch my app this way:

  1. 如果应用程序不在前台或后台,请像从启动器中启动一样启动它.

  1. If the app is not in the foreground or background, launch it as if it is launched from launcher.

如果应用程序在后台,则以应用程序的最新状态将其置于前台.

If the app is in the background, bring it to the foreground with the state it was last in.

如果应用程序位于前台,则不执行任何操作.

If the app is in the foreground, do nothing.

这是我的代码:

@Override
public void onReceive(Context context, Intent intent) {
        Intent launch_intent = new Intent("android.intent.action.MAIN");
        launch_intent.setComponent(new ComponentName("com.example.helloworld","com.example.helloworld.MainActivity"));
        launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        launch_intent.addCategory(Intent.CATEGORY_LAUNCHER);
        launch_intent.putExtra("some_data", "value");
        context.startActivity(launch_intent);
}

MainActivity是我的根本活动.就像我说的那样,如果该应用程序已经在运行,那么我只是希望将其放在最前面而不改变其状态.如果MainActivity之上有一些活动,请保持原样.

MainActivity is my root activity. Like I said, if the app is already running, I just want it brought to the front without changing its state. If there is some activity on top of MainActivity, leave it as it is.

在大多数情况下,上述代码都能正常工作,但有时我注意到从后台启动应用程序时,该应用程序已重新启动(或状态已重置-根目录重新位于顶部).

Most of the time the above code worked fine, but sometimes I noticed that the app was restarted (or the state was reset --- the root was back on top) when it was brought from the background.

我应该使用什么代码?感谢您的帮助!

What code should I be using? Any help is appreciated!

推荐答案

您无需编写所有代码.您可以使用启动意图",如下所示:

You don't need to write all that code. You can use a "launch Intent", as follows:

PackageManager pm = context.getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage("com.example.helloworld");
launchIntent.putExtra("some_data", "value");
context.startActivity(launchIntent);

但是,您的代码也应该可以使用.

However, your code should also work.

如果您说这在大多数情况下都可行,那么在这些情况下,您可能会看到一个讨厌的旧Android错误.当您直接从安装程序或通过IDE(Eclipse,Android Studio等)首次启动应用程序时,就会发生这种情况.您应始终始终首次直接从HOME屏幕或已安装的应用程序列表启动应用程序.有关此令人沮丧的Android错误的更多信息,请参见 https://stackoverflow.com/a/16447508/769265

If you say this works most of the time, you might be seeing a nasty old Android bug in those cases. This occurs when you launch your app for the first time either directly from the installer, or via an IDE (Eclipse, Android Studio, etc.). You should always launch your app for the first time directly from the HOME screen or list of installed apps. For more information about this frustrating Android bug see https://stackoverflow.com/a/16447508/769265

这篇关于Android-从广播接收器启动应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆