Creating an activity appears only once when the application starts

I have the following class: SplashActivity.java :

public class SplashScreen extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.splash); Thread timer = new Thread(){ public void run(){ try{ sleep(5000); }catch(InterruptedException e) { e.printStackTrace(); } finally{ Intent tutorial = new Intent(SplashScreen.this, TutorialOne.class); startActivity(tutorial); } } }; timer.start(); } } 

I want this activity to load only once, when the application is first installed on a mobile device for the first time. Being new to android, I know little about it. I read in places that SharedPreferences should be used, but didn't understand the implementation. And the thing about this activity is that the first time you use the activity should act like a Launcher , which really confused me. Because in the manifest file, I declare another action, which in my case would be MainPage.java . So how can I implement this logic? Am I SplashActivity in MainPage or is there something else that needs to be done? Help someone?

Can someone write code to implement this logic, if possible?

+6
source share
2 answers

Add this code to the onCreate method

  SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); if(pref.getBoolean("activity_executed", false)){ Intent intent = new Intent(this, TutorialOne.class); startActivity(intent); finish(); } else { Editor ed = pref.edit(); ed.putBoolean("activity_executed", true); ed.commit(); } 

SharedPreferences will be stored every time the application runs, unless you clear the data from the settings on your Android. The first time you get the value from the boolean (activity_executed) stored in such preferences (ActivityPREF).

If it does not find a value, it will return false, so we need to edit the preference and set it to true. The next run will launch the TutorialOne action.

finish() erases the current activity from the stack history, so returning is not possible using the button back from TutorialOne.

In your manifest, you can install this actitiy with

  <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> 

Each time the application is executed, it launches this action, but due to the true value set to "activity_executed" , a new action will be launched using startActivity .

+20
source
  SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); if(pref.getBoolean("activity_executed", false)){ } else { Intent intent = new Intent(this, TutorialOne.class); startActivity(intent); finish(); Editor ed = pref.edit(); ed.putBoolean("activity_executed", true); ed.commit(); } 

I think it should be so.

0
source

Source: https://habr.com/ru/post/944443/


All Articles