tj56
tj56

Reputation: 162

How to check if intent/activity is already open in Android?

So, I'm kind of a noob in Android but I searched a lot for this and I was not able to find a solution:

In my navigation drawer, each row opens a new intent. How can I check if a certain intent is open/active so that I'll use that instead of creating a new one?

I tried using this solution:

Link

But my issue is that the drawer opens the same class everytime, but each class has different "extras." For example:

    public void itemClicked(View view, int position) {
        Intent intent=null;
        switch (position) {
            case 1:
                intent = new Intent(getActivity(), DisplayActivity.class);
                intent.putExtra("ARGUMENT","SECTION 1");
                break;
            case 2:
                intent = new Intent(getActivity(), DisplayActivity.class);
                 intent.putExtra("ARGUMENT","SECTION 2");
               break;
            case 3:
                intent = new Intent(getActivity(), DisplayActivity.class);
                intent.putExtra("ARGUMENT","SECTION 3");
                break;
           }        
      startActivity(intent);
    }

How can I check if an intent with that class and with those extras is already open?

Thanks!

Upvotes: 1

Views: 2630

Answers (2)

frost
frost

Reputation: 520

You can also check about the launch modes in android which you make use of. I think it will serve your requirement well. For your reference have a look at this http://www.intridea.com/blog/2011/6/16/android-understanding-activity-launchmode

Upvotes: 1

Murtaza Khursheed Hussain
Murtaza Khursheed Hussain

Reputation: 15336

You can use shared preferences or extent from Application class where you store last/current activity visible

If you extend class for Application or you are targetting devices API Level 14 or above you can implement ActivityLifecycleCallbacks.

Sample Code

public class MyApplication extends Application implements ActivityLifecycleCallbacks {
    private static boolean isMySomeActivityVisible;

    @Override
    public void onCreate() {
        super.onCreate();

        // Register to be notified of activity state changes
        registerActivityLifecycleCallbacks(this);
        ....
    }

    @Override
    public void onActivityResumed(Activity activity) {
        if (activity instanceof YOURACTIVITY) {
             isMySomeActivityVisible = true;
        }
    }

    @Override
    public void onActivityStopped(Activity activity) {
        if (activity instanceof YOURACTIVITY) {
             isMySomeActivityVisible = false;
        }
    }

    // Other state change callback stubs
    ....
}

Upvotes: 2

Related Questions