【问题标题】:Starting an activity from service从服务开始活动
【发布时间】:2014-04-01 17:27:45
【问题描述】:

我正在使用 Android 中的一项服务,该服务会在一段时间后启动一项活动。 这是我的代码:

Intent intent = new Intent(this, PopupActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

问题是,如果我的应用程序正在后台运行(已暂停),并且服务启动了 PopupActivity,那么在后台运行的应用程序也会启动。 我不想要这种行为,有没有办法禁用它,以便只显示我的 PopupActivity?

【问题讨论】:

  • “我在 Android 中使用一项服务,它会在一段时间后启动一个活动。” - 永远不要这样做。如果我安装了一个执行此类操作的应用程序,并在我玩游戏、回复短信或电子邮件等过程中将Activity 推到我脸上,我会立即卸载该应用程序。使用Notification 并让用户选择是否打开您的弹出窗口。
  • @Squonk 好的,我试过了,请看相关帖子:stackoverflow.com/questions/22793443/…

标签: android service android-activity


【解决方案1】:

不,在 Android 中,所有构建组件(包括活动)都存在于应用程序上下文中,如果不启动应用程序上下文,就无法显示您的活动,这违背了 Android 的本质,就像尝试启动汽车一样不启动引擎:P(想不出更好的例子),这没有任何意义......

问候!

【讨论】:

    【解决方案2】:

    使用变量来定义您的应用是否“暂停”以避免启动活动

    private boolean isPaused = false;
    

    如果您的应用已暂停,则 isPaused = true;

      @Override
            protected void onPause(){
                isPaused = true;
                super.onPause();
            }
    

    如果你的应用执行onResume()方法,那么isPaused = false;

    @Override
        protected void onResume(){
            isPaused = false;
        super.onResume();
        }
    

    判断 isPaused 是否为假,然后开始活动

    if(!isPaused){
     Intent intent = new Intent(this, PopupActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    }else{
    Log.i("Activity", "Activity cannot started, app is onBackground");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多