0

I'm trying to make a certain function to start only when a user,

  • Opens the app for the first time,
  • Goes back to an app from home.

But not start if the user switches between activities within the app.

I have looked through this topic,and the best answer is to use singleTask with onNewIntent(). So, if a user is goes back to the app from Home, a onNewIntent call with the launcher intent passed to it can be used.

However, here is my code:

public class AdMobSDK_DFP_Interstitial extends Activity implements AdListener {
    private static final String MOBMAX_INTERSTITIAL_AD_UNIT_ID = "/7732/test_portal7/android_app1_test_portal7/splash_banner_android_app1_test_portal7";
    private DfpInterstitialAd interstitialAd;
    private int num = 0;

    public void onNewIntent(Intent intent){
        super.onNewIntent(intent);
        Log.d("flow", "onNewIntent");

}

If I switch between different activities in the app, onNewIntent() is always called, which is the same as I go back to the app from Home.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Kit Ng
  • 993
  • 4
  • 12
  • 24

1 Answers1

0

First thing you can do is to implement your own "Application" object and have it run the needed function when it is created.

public class MyApplication extends Application { 
   @Override
   public void onCreate() { 
        // Call your function
   }
}

Your application object will be live as long as your app is alive (any activity/service is still running), but note that the Application object is not destroyed immediately when the user presses "Home", and might stay alive for a while and a user can return to it without the function being called.

If you need this function to run as part of your main activity, just save a flag in your Application context : public boolean alreadyDisplayed = false; and then in your activity's onStart you can just call

if ((MyApplication)getApplication().alreadyDisplayed ) {
    // Call your function
    (MyApplication)getApplication().alreadyDisplayed = true;
}

** If this solution is not enough for you and you need to call your function every time your main activity is displayed from the home page you'll need to do something not as nice... one suggestion I can give you is to implement the same Application object but this time with an "open activity" counter:

public class MyApplication extends Application { 
   public int mActivityCounter = 0;
}

Then you can increment this counter on every onStart of activity in your app and decrement on every onStop (of course this can be done by implementing a class MyActivity and make all your relevant activities inherit it. Then you can use this counter to know if there are any other activities opened. Note that you'll have to make sure the access to this counter is synchronized and work your way with it as you need.

I hope this helps...

Talihawk
  • 1,299
  • 9
  • 18