【问题标题】:Starting Activity from background and hiding MainActivity - Popup Window从后台启动 Activity 并隐藏 MainActivity - 弹出窗口
【发布时间】:2018-03-21 14:34:50
【问题描述】:

我想知道是否可以从后台运行的服务启动 Acitivty,然后将 MainActivity 移动到后台。 我不想完成() MainActivity。把它藏起来。

    Intent it=new Intent(context, NewPopupRecognizer.class);
    it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(it);

我试过这段代码,但它总是延迟启动 Activity。

我想创建可以使用浮动按钮打开/关闭的弹出式活动。我曾经使用过WindowManger,但它非常有问题,所以我决定尝试使用Activity。

弹出窗口应类似于:Facebook Messenger 或 Google Assistant。

【问题讨论】:

    标签: android android-activity service


    【解决方案1】:

    我在另一篇文章中读到了这篇文章,这可能会对你有所帮助:

       Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ComponentName cn = new ComponentName(this, NewPopupRecognizer.class);
        intent.setComponent(cn);
        startActivity(intent);
    

    在这里找到How to start an Activity from a Service? 服务/3456099

    【讨论】:

      【解决方案2】:

      您可以做的是从服务向您的活动发送Broadcast

      Intent intent = new Intent("com.yourcompany.testIntent");
      intent.putExtra("value","test");
      sendBroadcast(intent);
      

      然后你的MainActivity 拿起它并执行:

      IntentFilter filter = new IntentFilter("com.yourcompany.testIntent");
              BroadcastReceiver receiver = new BroadcastReceiver() {
                  @Override
                  public void onReceive(Context context, Intent intent) {
                        Intent it=new Intent(context, NewPopupRecognizer.class);
                        it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        it.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
                        startActivity(it);
                  }
              };
      registerReceiver(receiver, filter);
      

      如果主要活动不存在,您可以添加一种机制,该机制将直接从服务中打开活动。如需更多选项,请查看此question 的答案。

      【讨论】:

      • 也有效,但活动开始时有延迟。
      • 延迟多长时间?您可以登录并检查,也许您的服务需要比您预期的更长的时间做出反应。
      • 3-4 秒,但仅在 mainactivity 位于前台时从后台开始,一切正常
      • 也许您知道如何创建弹出窗口的其他解决方案?
      • 是从获得初始触发器还是从发送广播开始 3 秒?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-10
      • 2018-02-16
      • 1970-01-01
      • 2013-05-10
      • 2018-07-21
      相关资源
      最近更新 更多