How to switch Activities without killing them in Android? - java

I have this Activity1(Restaurant) which switch to Acticity2(Home)
Intent intent = new Intent(RestaurantActivity.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); // Call once you redirect to another activity
My other Activity (Home) has a boolean to check if I have been at Home before
public static boolean visitedHomeAlready = true;
if(!visitedHomeAlready) {
Intent intent = new Intent(HomeActivity.this, RestaurantActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); //
}
My idea is: If I have not visited the home before and switch to Restaurant Activity, I want to "remember" the data in the Home Activity to continue my game after come back home but it always start from the beginning from my home...
I am not sure which flags I have to set or which method to resume that state from where exactly where I switch the activity.

As Amin commented above,the finish(); means that the first activity has finished its job and the app will end it,if you removed it the second activity will start,but the first activity will still be in its place and you can go back to it just by clicking the back button on your phone or virtual device.

Related

How to exit onBackPressed method in android studio?

I have developed an android apps that have a splash screen and a login page. The problem is when a user give credential and pressed log in button it open controlActivity. but when I pressed back button, I navigate to login page again If I pressed back button again I navigate to splash screen. How can I stop navigating to previous page, when user press back button then app should exit?
Why does it happen ?
This is happening because whenever you open another activity from intent, it creates it over it.
How to solve the problem?
You can add a flag like this
Intent intent = new Intent(this, SecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
OR
You can finish it.
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
finish();
If you want to close the app onBackPressed, you can override the method. Add this to your activity.
#Override
public void onBackPressed(){
finish();
System.exit(0);
}
Doing this, the app will be closed on back pressed!
You need to put a flag in the activity you want to be forgotten.
Intent intent = new Intent(this, Main2Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Answer by #Sambhav Khandelwal should solve your problem. In your splash screen you need to do add flags with intent like:
Intent intent = new Intent(SplashScreenActivity.this, LoginActivity.class); //assuming your splash screen name as SplashScreenActivity and login as LoginActivity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Or you can do without flags like below:
Intent intent = new Intent(SplashScreenActivity.this, LoginActivity.class);
startActivity(intent);
finish();

build a "fake" stake using startActivity()

I need to build a fake back stack in my application. I am starting an activity using aContext.startActivity(aIntent) and would like to build a stack to allow the user to go to the HomeActivity instead of exiting the application.
Now I know about the TaskStackBuilder but I am not sure on how to implement it when it comes to startActivity method.
This is what I got so far when building the stack but I am not sure how to use it in startActivity method
Intent detailActivity = new Intent(aContext, DetailsActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(aContext);
stackBuilder.addNextIntentWithParentStack(detailActivity);
PendingIntent pendingIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Why don't you just use onBackPressed
Context context = this;
#Override
public void onBackPressed()
{
Intent intent = new Intent(context,YourActivity.class);
startActivity(intent);
}
You need to start activity without adding to back stack, then override the onBackpressed
//Start activity without adding to history stack
Intent i = new Intent(...); // Your list's Intent
i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY); // Adds the FLAG_ACTIVITY_NO_HISTORY flag
startActivity(i);
//Override the newly open activity onBackPressed()
#Override
public void onBackPressed()
{
Intent i= new Intent(getApplicationContext(),HomeActivity.class);
startActivity(i);
}
The fix that i found to work without having to use onBackPressed was to add a flag to the intent
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
For building fake stack use TaskStackBuilder.This will help you to create back stack.
Suppose you activities are 'ActivityA', ActivityB, ActivityC, ActivityD. Now you are in ActivityB and from ActivityB you want launch ActivityD and want a back stack like this:
ActivityA -> ActivityC -> ActivityD
That means back press from ActivityD will go to ActivityC and back press from ActivityC wil go to ActivityA
In ActivityB you can use this
TaskStackBuilder.create(this)
.addParentStack(ActivityA.class)
.addNextIntent(new Intent(this, ActivityA.class))
.addNextIntent(new Intent(this, ActivityC.class))
.addNextIntent(new Intent(this, ActivityD.class))
.startActivities();
To use TaskStackBuilder you min sdk version should be 16 or higher.
For sdk less than 16 you can manually check in onBackPressed and start Activity.
In Activity D:
#Override
public void onBackPressed(){
Bundle extras = getIntent().getExtras();
if (extras.containsKey("FROM_ACTIVITY_B_FOR_STACK")){
// start Activity C
}else{
super.onBackPressed();
}
}
Do this for other activities where you want to add back stack

Intent not working always as expected

There are two flows in my app.
Flow 1:
Splash Screen --> Activity A --> Activity B --> Activity C --> Activity A
Flow 2:
Splash Screen --> Activity C --> Activity A
To explain the above; in Flow 1 a user sees the splash screen, goes to home screen, goes to login screen and on successful login, goes to main screen. If the user hits logout from the main screen he is redirected to the home screen.
In Flow 2 the user is an old user, he sees the splash screen and directly sees the main screen. If he logs out he should be directed to the home screen.
The problem which I am facing is that, in Flow 1, everything is working as expected. But in Flow 2, after logout (Activity C), the home screen (Activity A) is not opening. The intent is not working.
On click logout:
#Override
public void onClick(View v) {
((StudyStoryMain)getActivity()).logoutUser();
}
The Method:
public void logoutUser() {
//Problem: the intent is getting called in case the user creates an account. But, if the user is already an existing user, the intent is nit working
ParseUser.getCurrentUser();
ParseUser.logOut();
Intent i = new Intent(StudyStoryMain.this, HomeActivity.class);
//logic to fix logout
// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
finish();
startActivity(i);
}
Why is the Intent not working in both the flows?
Try this way :
Intent intent = new Intent(StudyStoryMain.this, HomeActivity.Class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); // Call once you redirect to another activity
Before finishing current Activity start another Activity :
startActivity(i);
finish();
As in logoutUser() method you are calling finish() before startActivity() which is wrong as startActivity(intent) get never call.
So just change sequence to
startActivity(intent)
finish()
#Override
public void onClick(View v) {
((StudyStoryMain)getActivity()).logoutUser();
finish();
}
The Method:
public void logoutUser() {
ParseUser.getCurrentUser();
ParseUser.logOut();
Intent i = new Intent(StudyStoryMain.this, HomeActivity.class);
startActivity(i);
}
Try this way, hope it solves your problem.

How to close all running activities from another one?

I've got some activities which I execute one after another without closing (1->2->3->4). I want to close 1,2,3 activities from 4 and execute a new one; the code:
Intent intent = new Intent(UserpickActivity.this, CommunicationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
UserpickActivity - 4th activity, CommunicationActivity - the next activity. But after this code all previous activities still worked. How can I close all running activities and execute some new activity?
Try this:
When you want to launch CommunicationActivity from Activity4, do this instead:
Intent intent = new Intent(this, Activity1.class); // Your root activity
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Will remove all other activities from the task
intent.putExtra("foo", true); // This is to tell Activity1 to launch Activity4
startActivity(intent);
In Activity1.onCreate() do the following:
super.onCreate();
if (getIntent().hasExtra("foo")) {
// We should now launch CommunicationActivity and finish ourselves
Intent intent = new Intent(this, CommunicationActivity.class);
startActivity(intent);
finish();
return; // Don't continue the rest of onCreate()
}
// The rest of your onCreate() goes here
You can only use CLEAR_TOP to clear down to an existing activity in the activity stack. That's why your use of CLEAR_TOP isn't working (because CommunicationActivity doesn't exist in the activity stack).
This method clears all activities and launches the root activity again. When the root activity's onCreate() is called, it checks the Intent for the extra "foo", which it uses as a signal that it needs to launch CommunicationActivity and finish itself. This should do what you want.
Call activity.finish(); after you switch to other activity. This way no activity will remain on stack.
Intent intent = new Intent(UserpickActivity.this, CommunicationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//YOUR_ACTIVITY.finish();
Uncomment the above line if you want this activity to be removed from activity stack.
// This will clear all activity and start new task.
Intent intent = new Intent(UserpickActivity.this, CommunicationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Use android:nohistory=true in manifest for Activities.
<activity
android:name=".A"
android:label="#string/app_name"
android:noHistory="true" >

How to restart activity using intent?

I am making an android app which plays mp3 files. I am launching the mp3 playing activity from within another activity using intent:
Intent intent=new Intent(ListViewA.this,mp3player.class);
intent.putExtra("feed",gh);
i.setFlags(0);
i.setPackage(null);
//intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
Now when the user selects another song from a list, I want to close the previous instance of the mp3player activity and start a new one using the intent code (above). How do I go about doing that? Thanks.
Instead of startActivity use startActivityForResult(intent, PLAY_SONG) then you can call finishActivity(PLAY_SONG) where PLAY_SONG is a constant number.
class member
private static final int PLAY_SONG
And then
finishActivity(PLAY_SONG);
Intent intent=new Intent(ListViewA.this,mp3player.class);
intent.putExtra("feed",gh);
i.setFlags(0);
i.setPackage(null);
startActivityForResult(intent, PLAY_SONG)
Hey its very simple Instead of calling Intent from Mp3Playeractivity call finish() when you are pressing the back button by implementing
#Override
public void onBackPressed(){
finish();
}
which will cause close your MpeplayerActivity

Categories