Salman
Salman

Reputation: 195

Create a function that fires only once after app is installed on phone

I'm developing a mobile app using ApacheCordova/Phonegap. I need a function that sends a SMS to me once per install. If I put my function on "DeviceReady" it will be run each time the app opens. Is there any solution for a function to be run when app is installed OR when it runs for first time?

Any suggestion would be appreciated.

Upvotes: 4

Views: 4157

Answers (4)

muuk
muuk

Reputation: 932

I added a field to the localstorage and on startup just check if that field exists. So something like this:

if (window.localStorage.getItem("installed") == undefined) {
   /* run function */
   window.localStorage.setItem("installed", true);
}

Edit: The reason I prefer this over the other methods is that this works on iOS, WP, etc as well, and not only on android

Upvotes: 6

Dondaldo
Dondaldo

Reputation: 56

Use some boolean value if its true don't call that function other wise call that function example is here

if(smssent!=true)
{

//call sms sending method

}


else

{

//just leave blank or else notify user using some toast message

}

Note:-the boolean value store in some database like sharedprefernce or sqllite, files....

Upvotes: 0

erad
erad

Reputation: 1786

Check if it is the first time with a method and then perform the action if that method determines that it is the first time.

Ex:

isFirstTime() Method

private boolean isFirstTime()
    {
    SharedPreferences preferences = getPreferences(MODE_PRIVATE);
    boolean ranBefore = preferences.getBoolean("RanBefore", false);
    if (!ranBefore) {

        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("RanBefore", true);
        editor.commit();
        // Send the SMS

        }
    return ranBefore;

    }

You may want to add it to your onCreate()

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    topLevelLayout = findViewById(R.id.top_layout);



   if (isFirstTime()) {
        topLevelLayout.setVisibility(View.INVISIBLE);
    }

Upvotes: 8

Dominik Mayrhofer
Dominik Mayrhofer

Reputation: 491

This should be what u are searching for:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false)) 
{
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}

Upvotes: 0

Related Questions