sahithi
sahithi

Reputation: 1089

How to know whether app is opened for the first time after installing in xamarin android

As the question says how can I know that the app is launched for the first time in users device in android?

Upvotes: 0

Views: 361

Answers (2)

FreakyAli
FreakyAli

Reputation: 16409

There are two ways that I am aware of that you can use to do this the easy one would be the Shared preferences as they are available from the android side and are pretty lightweight.

The Xamarin.Android equivalent of SharedPreferences is an interface called ISharedPreferences.

For example, to save a true/false bool using some Context you can do the following:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
ISharedPreferencesEditor editor = prefs.Edit ();
editor.PutBoolean ("is_first_time", mBool);
// editor.Commit();    // applies changes synchronously on older APIs
editor.Apply();        // applies changes asynchronously on newer APIs

Access saved values using:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
mBool = prefs.GetBoolean ("is_first_time", <default value>);  
if(mBool)
{
 //this is first time   
 prefs.PutBoolean ("is_first_time", false).Apply();
}
else
{
//this is second time onwards
// your piece of code
}

Upvotes: 0

Arvind Chourasiya
Arvind Chourasiya

Reputation: 17392

Use SharedPreferences to know whether app opening first or second time onwards. This code should be at startup of you app like OnCreate of your MainActivity

var pref = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
var editorLogin = pref.Edit();

if (pref.GetBoolean("firstTime", true))
{
    Toast.MakeText(this, "App opening first time", ToastLength.Short).Show();
    editorLogin.PutBoolean("firstTime", false).Commit();
}
else
{
    Toast.MakeText(this, "App opening second time", ToastLength.Short).Show();
}

Upvotes: 1

Related Questions