Home > OS >  Generate random number only once
Generate random number only once

Time:09-13

I am using a library to rate my app and there is a function called .setInstallDays(n) that is called OnCreate method and it recieves a number as argument so that a rate dialog will be shown after the n days of installs. It is working ok, but I would want to set that n number as a random number in a range of numbers. The problem is that I have thought that maybe if it is generated OnCreate method it could generate one different number so that the n will change everytime the Activity is created. How could I generate only one random number so that it is only generated once so that I can use that random number in the .setInstallDays(n) function?

This is the library I am using:AndroidRateHotchemi

This is the code that I have already:


 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);


        AppRate.with(this)
                .setInstallDays(4) // default 10, 0 means install day.
                .monitor();

        AppRate.showRateDialogIfMeetsConditions(this);


}

CodePudding user response:

You could possible add an override to the onCreate method where you pass in a random number generated outside. eg.

 @Override
    protected void onCreate(Bundle savedInstanceState, int randomDays) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);


        AppRate.with(this)
                .setInstallDays(4) // default 10, 0 means install day.
                .monitor();

        AppRate.showRateDialogIfMeetsConditions(this);


}

Without much further information it's hard to say whether that would fit your needs.

Other that that you could try creating a globally randomized number and toss that in there. Again without much else to go on, its hard to find an adequate solution.

CodePudding user response:

If you want to generate a random number only once that is persistent across launches of your app, you can save it to SharedPreferences and then check for the saved value before re-generating it. This way it is only generated once, and is the same for all subsequent launches of the Activity and app.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    int rand;
    if( prefs.contains("MYRAND")) {
        rand = prefs.getInt("MYRAND", -1);
    }
    else {
        rand = new Random().nextInt(10) 4; // number from 4 to 13
        prefs.edit().putInt("MYRAND", rand).apply();
    }
    
    // do something with rand
    AppRate.with(this)
           .setInstallDays(rand)
           .monitor();
}

You can use nextInt(int bound) on the Java Random class to generate a random integer that is >= 0 and less than bound.

  • Related