Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two instances of my android application are running....How to avoid this?

Tags:

android

Here is my problem -

  1. I copied my .apk file onto phone memory card and launch my application clicking on it and it allows me to install my application.I install my application.Finally,I got system installation pop up containing two options "Open" and "Done".When i click "Open" my application got launched.Up to this point everything is working without any problem.

  2. Now in my application I click on a button and some download is taking place as a result(Showing progress dialog).Now I press a Home button,so my application goes to background.

  3. Now I again launch my application by going inside Menu and clicking on my application icon.

  4. Expected result - Still I Should see Progress Dialog for downloading. Actual result - A new instance/session of my application is getting started.

So how to avoid this so that only one and one instance/session of my application should run.

like image 336
Waugh Avatar asked May 07 '11 03:05

Waugh


Video Answer


1 Answers

@Palejandro, here you are. Put the code below into your main activity onCreate() method:

// Possible work around for market launches. See
// http://code.google.com/p/android/issues/detail?id=2373
// for more details. Essentially, the market launches the main activity
// on top of other activities.
// We never want this to happen. Instead, we check if we are the root
// and if not, we finish.
if (!isTaskRoot()) {
    final Intent intent = getIntent();
    final String intentAction = intent.getAction();
    if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intentAction != null && intentAction.equals(Intent.ACTION_MAIN)) {
        Log.w(TAG, "Main Activity is not the root. Finishing Main Activity instead of launching.");
        finish();
        return;
    }
}

I used this piece of code in my projects and it works fine!

like image 159
StenaviN Avatar answered Sep 27 '22 22:09

StenaviN