Start activity only once - android

I want my app to start a activity only the first time the app launches.
Any one got any idea?
I found this but it only shows a black screen.
public class WhatsNew extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
protected void onCreate(Bundle state){
super.onCreate(state);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean dialogShown = settings.getBoolean("dialogShown", false);
if (!dialogShown) {
// AlertDialog code here
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("dialogShown", true);
editor.commit();
}
}
}

When the app launches, set a flag in the activity preferences that the activity has already run. Default your setting to false, and then only start that activity if the flag isn't set. Note that if the user cleans your application data, or uninstalls it and later installs it again the activity would show again.

I think that you talk about activities like "log" page that you would launch only once in your application's whole life.
For this, you can use sharedPreferences:
SharedPreferences prefs;
SharedPreferences.Editor editor;
and below your startActivity(intent), you add:
prefs = getSharedPreferences("nbRepet",Context.MODE_PRIVATE);
editor = prefs.edit();
editor.putInt("nbRepet", 1);
editor.commit();
Now your variable nbRepet have 1 as value.
After that, you can add these lines ABOVE your startActivity(intent) to verify that your activity was never launched before:
//here you recover nbRepet's value..
preferences = MainActivity.this.getSharedPreferences("nbRepet", MODE_PRIVATE);
int value = preferences.getInt("nbRepet", 0);
//.. and you verify if your activity is launched before.
if(value<1)
{
startActivity(intent);
}

You will need an Activity which checks a persisted boolean. ie,
onCreate(Bundle bundle)
{
boolean firstRun = // persistance method here
Intent toForward;
if(firstRun)
// Create an intent to start you "only once" activity
// persist "firstRun" as false;
else
// Create an intent for your usual startup
startActivity(toForward);
finish();
}

this will do the job for you
package com.example.startup;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main); //we don't need this line
SharedPreferences settings=getSharedPreferences("prefs",0);
boolean firstRun=settings.getBoolean("firstRun",false);
if(firstRun==false)//if running for first time
{
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
Intent i=new Intent(MainActivity.this,Second.class);//Activity to be launched For the First time
startActivity(i);
finish();
}
else
{
Intent a=new Intent(MainActivity.this,Main.class);//Default Activity
startActivity(a);
finish();
}
}
}

Depends on what "first time" means. Easiest way is to put some flag into the SharedPreferences... but that can stay around for a while. ^^

If you mean that onCreate should be invoked only once when "start only once when app is launched", you could set the launchMode of the acitivty to singleInstance or singleTask in the manifest.

See my answer in this post, regarding this same issue.
I recommend checking the SharedPreference value for whether the app has previously been ran, inside of the onResume().

Related

Shared preferences not working as expected

Below is my code to the MainActivity.java of my project, this is the welcome like screen for my app and should only appear first time user opens the app. Otherwise the user should get to see the Medicine_Activity.java which is also triggered when the user presses "Get Started" button on MainActivity. In order to implement this i came across something known as SharedPreferences and tried to implement it. But it isnt working quite as expected, the MainActivity flashes for a second before Medicine_Activity is launched. I am new so please help me out
Here is a video clip to view this bug in action - https://www.dropbox.com/s/fqbo9urb6xnh3pd/WhatsApp%20Video%202019-06-20%20at%202.12.50%20PM.mp4?dl=0
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnGetStarted;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.apply();
} else{
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
}
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
getSupportActionBar().hide(); // hide the title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
setContentView(R.layout.activity_main);
Button btnGetStarted = findViewById(R.id.btnGetStarted);
btnGetStarted.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
}
}
Use commit() while storing the true and finish() the MainActivity.
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), true);
edit.commit();
} else{
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
finish();
}
A short explanation: commit() writes the data synchronously (blocking the thread its called from). It then informs you about the success of the operation. However, apply() schedules the data to be written asynchronously. It does not inform you about the success of the operation.
Quoting from Documentation:
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures

How can I get the name of the previous activity and store in a variable

I'm developing an app where I have many activites. And when the user ends interacting with the content of each activity it launchs an Activity called WellDone! where the user can see the average of the lessons (it's a course). 100% completed and it has a button for the next lesson. I want to get the name of the previous activities for example activity_lesson1, activity_lesson2 to show in a TextView to have a Title.
When ends the lesson1 it launchs the WellDone! Activity and I want to set in a TextView (title) the name of the lessons that have just learned.
package com.flixarts.ar.**;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class welldone extends AppCompatActivity {
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pantallanextsesion);
title = (TextView)findViewById(R.id.tituloActivity);
title.setText() //Here the title of the previous activity that have come from intent
}
}
My impression is that the answer to the literal question is "no" - you cannot get the name of previous activity. But there's probably another way to accomplish what you need.
If these are all your activities, why not put an extra in the Intent (when going in the forward direction) which says which activity it is coming from.
You can then decide what name of the activity to display based on checking that extra, which should tell you what the previous activity was.
Maybe you could use SharedPreferences, which allow you to easily save some String value in one activity and read it in another. In previous activity e.g activity_lesson1 you could override method onPause (or onDestroy if you finish your activity while proceeding to next one by calling finish() method) and save the name of activity as String like this:
#Override
public void onPause() {
super.onPause();
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("LAST_ACTIVITY_NAME", this.getClass().getSimpleName());
editor.apply();
}
Then you can read saved value inside WellDone activity like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String lastActivityName = sharedPref.getString("LAST_ACTIVITY_NAME", "default_value");
title.setText(lastActivityName);
}
Two ways to pass previous activity name
Use Intent
FirstActivity
String TAG=FirstActivity.class.getSimpleName();
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name=nameEt.getText().toString();
mobile_number=mobileEt.getText().toString();
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("Last_Activity_Name",TAG);
startActivity(intent);
}
});
SecondActivity
String lastActivityName;
lastActivityName=getIntent().getStringExtra("Last_Activity_Name");
**use SharedPreferences **
FirstActivity
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Last_Activity_Name", TAG);
editor.apply();
SecondActivity
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String lastActivityName = sharedPref.getString("Last_Activity_Name",
"default_value");
title.setText(lastActivityName);

App resumes to wrong activity when singleTask flag is used

MainActivity in my app has launchMode set to singleTask. If I start ActivityB from MainActivity, then put app to background and start my app from applications screen it does not resume correctly. ActivityB automatically finishes and MainActivity resumes. I expect ActivityB to resume instead. Why is this happening and what could I do to make it work normally? It works OK without singleTask flag but I need that flag for other purposes.
By the way, my app resumes correctly from recent apps screen.
Use the following code in the LAUNCHER Activities.
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isTaskRoot()) {
finish();
return;
}
// Rest of your onCreate code goes here
}
Activity B is closed because it launched from Activity A, this is normal behavior for android because Activity A needs to be restarted (singleTask) and all related instance will be kill/finish.
So, what you can do is implement shared-preference.
your activity A should be like this :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//// read share preference
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger("MYSHARE_PRFERENCE");
int isOpened = sharedPref.getInt("IS_ACTIVITY_B_ALREADY_OPENED", defaultValue);
if (isOpened == 1)
{
//resume activity B
startActivity(new Intent(MainActivity.this, ActivityB.class));
}
////
findViewById(R.id.text).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, ActivityB.class));
//// write on share preference
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("IS_ACTIVITY_B_ALREADY_OPENED", 1);
editor.commit();
////
}
});
}
}
P.S : I didn't compile it yet, the code might be error on compile. But share preference can be solution for your problem.

How to run an activity only once like Splash screen

In my app, I would like to run the Splash screen once at first run only but the problem is that I already placed in the Manifest this line: android:noHistory="true" which works great if I press back button and exits the app but note that the app is still in the background running, and when I press the app icon it goes back again to the Splash screen then my Registration page. I wanted to be redirected to the Registration page directly when I reopen my application.
How do I do this? Thanks ahead for any suggestions.
This is how I achieved it!Hope it helps!
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
public class check extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
SharedPreferences settings=getSharedPreferences("prefs",0);
boolean firstRun=settings.getBoolean("firstRun",false);
if(firstRun==false)//if running for first time
//Splash will load for first time
{
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
Intent i=new Intent(check.this,Splash.class);
startActivity(i);
finish();
}
else
{
Intent a=new Intent(check.this,Main.class);
startActivity(a);
finish();
}
}
}
You can use Shared Preferences to save some boolean when you run your app at very first launch and then check that value on every launch if exits then directly start the Registration Activity.
Although, this approach of just saving a normal value has a loop hole where, suppose your app is
installed on a user device and user just updated the app with new
version without uninstalling the first one then in that case you also
not gonna see the Splash as the old shared preferences will already be
there with that old saved value.
So in that case you need to change the logic litle bit by saving the app version and check for app version on every launch in that way you will be able to produce real user experience.
Have a look at this : How to create a one-time welcome screen using Android preferences?
To elaborate on the mention of "shared preferences", I believe the following would work, if you inserted it in onCreate() of your main activity:
SharedPreferences settings = this.getSharedPreferences("appInfo", 0);
boolean firstTime = settings.getBoolean("first_time", true);
if (firstTime) {
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("first_time", false);
editor.commit();
}
After the block executes, "firstTime" should indicate whether this is the first time the app has been run. "appInfo" is just a placeholder name for whatever you want the preferences file to be called, I believe.
So here's what I did, in my SplashActivity(onCreate):
SharedPreferences settings = getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", true);
editor.commit();
Intent intent = new Intent(this, RegistrationActivity.class);
startActivity(intent);
SplashActivity(onResume):
#Override
public void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences("prefs", 0);
boolean firstRun = settings.getBoolean("firstRun", true);
if (!firstRun) {
Intent intent = new Intent(this, RegistrationActivity.class);
startActivity(intent);
Log.d("TAG1", "firstRun(false): " + Boolean.valueOf(firstRun).toString());
} else {
Log.d("TAG1", "firstRun(true): " + Boolean.valueOf(firstRun).toString());
}
}
In my RegistrationActivity(onCreate):
SharedPreferences settings = getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", false);
editor.commit();
boolean firstRun = settings.getBoolean("firstRun", true);
Log.d("TAG1", "firstRun: " + Boolean.valueOf(firstRun).toString());
And then disabled back button to prevent going back unless the user presses Home:
#Override
public void onBackPressed() {
}
Big thanks for those that contributed!
The simplest way it that
You can use android:noHistory="true" in your manifest file.

Call an activity only once in the app and show it again when the app restart after being killed

I'm developing an application in which I have to show an activity only once in the app lifecycle.
What I'm doing is on my MainActivity.java I'm calling an Activity 1, so after when I move in my app and whenever I come back to MainActivity.java my Activity 1 is called. I just want to show it once.
And again Activity 1 should be displayed when user kills the app and restarts it.
Here is what I'm doing in my MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startActivity(new Intent(MainActivity.this,
Activity1.class));
}
I have tried using the following code but it only run once, when the app is installed for the first time.
private boolean isFirstTime() {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
// first time
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
}
return !ranBefore;
}
How can I modify the above code, so that my requirement is satisfied.
Any kind of help will be appreciated.
You should set ranBefore to false in onDestroy
#Override
public void onDestroy()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", false);
editor.commit();
}
Change
return !ranBefore
to
return ranBefore
It looks to me that you are always returning the same thing instead of the variable you initialize. Also, you could put the code to start the Activity directly in that method. Then you don't have to even worry about a return statement. It will just never run it again after you change the value in SharedPreferences
Edit
you can set your SharedPreferences value to false in onCreate(). This will work if you don't finish your Activity when you go to another and if its your main Activity then you probably don't ever want to finish it until you exit the app
I have solved this problem using SharedPreferences. What I have done is on Splash I entered some values in SP, and on the MainActivity I checked that, if the value matches show the activity, otherwise don't open the dialog. And on keyCodeBack(), I have cleared SP, this helps me in meeting my requirement.
Use shared preferences..
and to kill the activity, use class.finish() at your onClick()..

Categories

Resources