从后台启动活动并隐藏MainActivity - 弹出窗口

时间:2018-03-21 14:34:50

标签: android android-activity service

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

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

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

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

弹出窗口应该是:Facebook Messenger或Google智能助理。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以做的是从服务中向您的活动发送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的答案。

相关问题