यह उदाहरण दर्शाता है कि SharedPreferences का उपयोग करके किसी एक्टिविटी को केवल पहली बार ऐप खोलने पर कैसे दिखाया जाए (जैसे वेलकम स्क्रीन या ट्यूटोरियल)।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में नया प्रोजेक्ट बनाएं।
चरण 2: लेआउट XML
res/layout/activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="I will be launched once only" />
</LinearLayout>
चरण 3: MainActivity.java में SharedPreferences लॉजिक
src/MainActivity.java - onResume() में चेक करें:
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
String prevStarted = "prevStarted";
@Override
protected void onResume() {
super.onResume();
SharedPreferences sharedpreferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
if (!sharedpreferences.getBoolean(prevStarted, false)) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(prevStarted, Boolean.TRUE);
editor.apply();
} else {
finish(); // पहले से लॉन्च हो चुका है, एक्टिविटी बंद करें
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
चरण 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ऐप चलाएं
पहली बार चलाने पर एक्टिविटी दिखेगी, दूसरी बार ऐप खोलने पर तुरंत बंद हो जाएगी।
