Hey
Hey

Reputation: 95

Starting Activity from background and hiding MainActivity - Popup Window

I was wondering if it is possible to start Acitivty from service running in background and then move MainActivity to background. I don't want to finish() MainActivity. Just hide it.

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

I tried this code but it is always starting Activity with delay.

I want to create popup Activity which i can turn on/off with floating button. I used to use WindowManger but it was very problematic so I decided to try doing it with Activity.

The popup should be like: Facebook Messenger or Google Assistant.

Upvotes: 1

Views: 538

Answers (2)

Doron Yakovlev Golani
Doron Yakovlev Golani

Reputation: 5480

What you can do is to send a Broadcast to your activity from the service:

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

Then your MainActivity picks it up and does:

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);

You can add a mechanism that will open the activity directly from the service if the main activity is not there. For more options check out the answers to this question.

Upvotes: 1

Amine ABDALKHALKI
Amine ABDALKHALKI

Reputation: 445

I have read this in another post that this may help you:

   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);

found here How to start an Activity from a Service? service/3456099

Upvotes: 1

Related Questions