开发者

Application Launch Count

I am working on an application, wherein after say 5 times the app is opened by a user, at 6th attempt the app should a开发者_开发百科sk for feedback from user. I tried using Activity OnStart,OnResume, but its not working out since even after leaving and re-entering activity these methods are called. Also as per android functionality, I cannot quit app so that I can find it out from the first activity called. How do I find how many times the app was launched?

I hope this is not confusing.

Edit

Alternatively is there a way, wherein I can always resume my app from the first activity( or welcome page for eg.), once user presses home to quit the app.


This is actually quite simple. Using SharedPreference or the Database.

during OnCreate add 1 to the numberofTimes counter and commit.

OnCreate (Bundle bundle){
  mPref = getPreferences();
  int c = mPref.getInt("numRun",0);
  c++;
  mPref.edit().putInt("numRun",c).commit();
  //do other stuff...
}

OnCreate is called regardless of you start the app or you resume the app, but isFinishing() returns true if and only iff the user (or you) called finish() on the app (and it was not being destroyed by the manager)

This way you only increment when you are doing fresh start.

the isFinishing() Method inside of a OnPause method to check to see if the activity is being finish() or just being paused.

@Override
protected void OnPause(){
  if(!isFinishing()){
    c = mPref.getInt("numRun",0);
    c--;
    mPref.edit().putInt("numRun",c).commit();
  }
  //Other pause stuff.
}

This covers all your scenarios:

1. user starts app/activity (+1)-> finishes app, exit with finish()
2. user starts app (+1) -> pause (-1) -> returns (+1)-> finish
3. user starts app (+1) -> pause (-1) -> android kills process (0) -> user returns to app (+1) -> user finish.

every scenario you only increment the "times run" counter once per "run" of the activity


Just:

  1. declare:

    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;
    private int totalCount;
    
  2. initialize in onCreate():

    prefs = getPreferences(Context.MODE_PRIVATE);
    editor = prefs.edit();
    
  3. print or count wherever you want (any where in onCreate() or any specific click as you specified):

     totalCount = prefs.getInt("counter", 0);
     totalCount++;
     editor.putInt("counter", totalCount);
     editor.commit();
    
  4. now print totalCount where you want to count e.g.:

     System.out.println("Total Application counter Reach to :"+totalCount);
    


if you have a starting activity for app launch then you can implement it in following ways 1. Database:- through database you can save your application launch count and retrieve it on create of activity.

  1. Static Variable:- static variable also retain values during application start and end

  2. Application Preference:-you can store value in application preference and use it

problem with 2 and 3 approach is that if you switch off and on again your phone you will loose data. but if you still want to use 2 or 3 approach then 2 approach is very simple and

sample code for 3rd approach here

well you have to extends Application class and create a subclass from that

public class MyApp extends Application{
int visitCount;
onCreate(){
 visitCount=0;
}

and you can mention it in your menifest file like

<application name="MyApp">

.....
</application>

and in onCreate of your activity you can get it by

MyApp myApp=(MyApp)getApplicationContext();

Edit1: subclass your activity and override method

public class myActivity extends Activity{

   @Override
   onSaveInstanceState(Bundle outState){
      super.onSaveInstanceState(outState);
      counterFlag=true;
   }
}

it is get called when user press home button

and again override onResume() and check whether your counter flag is enabled or not and create all your activity by subclassing your MyActivity

also if any other activity has exit point on click of back button then you can override

   @Override
   public void back_pressed(){

   }

and do your task accordingly


I think this would be the best option in order to cover all scenarios:

private static boolean valueOfLaunchCountModified = false;

@Override
protected void onCreate(Bundle savedInstanceState) {

    if(!valueOfCountModified){
        preferences = getPreferences(MODE_PRIVATE);
        launchCount= preferences.getInt("launchCount", 0);
        if(preferences.edit().putInt("launchCount", ++launchCount).commit()){
            valueOfCountModified = true;
            if(launchCount == 5){
                //Do whatever you want
            }
        }
    }
}

If we remember the definition of a static variable ("...They are associated with the class, rather than with any object. Every instance of the class shares a class variable...") we will discover that is perfect for us.

When onPause method or an orientation change is executed the value of "valueOfLaunchCountModified" doesn't change; however, if the app process is destroyed, the value of "valueOfLaunchCountModified" changes to false.


If you only want to count "true" invocations then extend Application and place counter logic into Application#onCreate. This could be a simple preference


I prefer to use onResume to track launch count since it’s getting called in every scenario (refer to Android Activity Lifecycle) when the activity is shown.

onResume could be called quite frequently depending on usage pattern, so instead of tracking launch count, it would be better to track launch session (as in only 1 launch count would be tracked per hour).

@Synchronized fun appSessionCount(sharedPref: SharedPreferences): Boolean {
    val now = LocalDateTime.now(ZoneOffset.UTC)

    val firstSeconds = sharedPref.getLong(KEY_FIRST_LAUNCH_DATE, 0)
    if (firstSeconds == 0L) {
        sharedPref.edit {
            putLong(KEY_FIRST_LAUNCH_DATE, now.atZone(ZoneOffset.UTC).toEpochSecond())
        }
    }

    val seconds = sharedPref.getLong(KEY_LAST_SESSION_DATE, 0)
    val lastDate = if (seconds > 0) LocalDateTime.ofInstant(Instant.ofEpochSecond(seconds), ZoneOffset.UTC) else null

    var count = sharedPref.getLong(KEY_SESSION_COUNT, 0)

    // first time or 1 hour ago
    if (lastDate == null || Duration.between(lastDate, now).toHours() >= 1) {
        sharedPref.edit {
            putLong(KEY_SESSION_COUNT, count + 1)
            putLong(KEY_LAST_SESSION_DATE, now.atZone(ZoneOffset.UTC).toEpochSecond())
        }
        return true
    }

    return false
}

I run the code at onResume of my main activity.

class MainActivity : AppCompatActivity() {
    lateinit var sharedPref: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        sharedPref = getSharedPreferences("LuaApp", Context.MODE_PRIVATE)
    }

    override fun onResume() {
        super.onResume()

        appSessionCount(sharedPref)
    }
}

https://code.luasoftware.com/tutorials/android/android-track-app-launch-count/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜