I am working in android studio.I have a bottom-navigation fragment. For the last switch case, I need a button to navigate to the HomeActivity (home screen). I tried:
...
case SUMMARY:
navNextText.setText(R.string.end);
navNextImageView.setOnClickListener(v -> navigateHome());
navNextText.setOnClickListener(v -> navigateHome());
break;
default:
Log.w(TAG, "Executing a default case in navigateNext(). CTX: " + contextState.toString());
}
private void navigateHome() {
Objects.requireNonNull(getActivity()).finish();
Intent in = new Intent(getActivity(), HomeActivity.class);
startActivity(in);
}
This works to an extent. I can navigate home, but when I click back into the activity that the navigation fragment resides, the navigation bar resumes where it was previous to changing activity.
I have also tried adding onStop() and onDestroy to private void navigateHome, but that seemed to do nothing.
I am just wondering what is the cleaner way to close an activity from a fragment and start a new one.
just add finish() if you want to remove the current activity from the backstack
As you're in a fragment, use requireActivity().finish()
Also to make sure you have no activities in back stack, you can remove all using below intent flag
private void navigateHome() {
Objects.requireNonNull(getActivity()).finish();
Intent in = new Intent(getActivity(), HomeActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // <<<<< flag
startActivity(in);
requireActivity().finish(); // <<< finish the current activity
}
I'm struggling with this issue and I want to know if there is any option to know why an activity is being closed, I have checked if it was a low memory issue with Runtime.getRuntime().freeMemory(); but everything looks fine.
UPDATE
Here is how I call the activities and when suddenly all the background activities are closed. In all the way from MainActivity to SketchActivity I'm not calling the finish(); method but when I start the SketchActivity from BoulderProfileActivity, all the activies are destroyed, except SketchActivity :
MainActivity:
private void SendUserToFindBoulderActivity(){
Intent boulderFindIntent = new Intent(MainActivity.this, FindBouldersActivity.class);
startActivity(boulderFindIntent);
}
FindBouldersActivity:
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent boulderProfileIntent = new
Intent(FindBouldersActivity.this,BoulderProfileActivity.class);
boulderProfileIntent.putExtra("BoulderKey", BoulderKey);
startActivity(boulderProfileIntent);
}
});
BoulderProfileActivity:
public void SendUserToSketchUpActivity(){
Intent sketchIntent = new Intent(BoulderProfileActivity.this, SketchActivity.class);
sketchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if(sustituir==false) {
sketchIntent.putExtra("BoulderKey", BoulderKey);
sketchIntent.putExtra("Uri", ImageUri);
sketchIntent.putExtra("sustituir", sustituir);
}else{
sketchIntent.putExtra("BoulderKeyForSwitchFirstImage", BoulderKey);
sketchIntent.putExtra("Uri", ImageUri);
sketchIntent.putExtra("photoKey", photoKey);
sketchIntent.putExtra("sustituir", sustituir);
}
startActivity(sketchIntent);
}
When you start SketchActivity you are using flags
sketchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
and these flags close all previous activities and start the activity in a new task.
so to keep old previous activities please remove this line.
if you don't know what is a task, the task is the container for activities, so when you start new task this means that the activity is the first activity if you want to read more about tasks follow this link :
https://developer.android.com/guide/components/activities/tasks-and-back-stack
and you can find more information about intent flags here
https://developer.android.com/reference/android/content/Intent#FLAG_ACTIVITY_CLEAR_TASK
Any chance you enabled developer mode (System -> Developer options), and it is force-closing the Activity?
There's an option (Developer Options, under 'apps', I'm using a Pixel 3) called 'Don't keep Activities' which should be disabled.
I am developing an android application. So in there I have button called "Aboutus". when I click that one it starts another activity and show corresponding view.
Here is the code for button Aboutus click event.
aboutus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,AboutUs.class);
startActivity(intent);
}
});
}
And then in that aboutus activity I have back button.when we press that back button it will go to the main activity again.
back button key event goes like this..
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(AboutUs.this,MainActivity.class);
intent.putExtra("aboutus", true);
startActivity(intent);
finish();
System.exit(0);
}
});
here i put some intent extras for some other purposes.In this case they do not matter. So and then again in mainactivity i have exit button. which should kill whole app.
and my exit button code goes like this.
exit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
System.exit(0);
}
});
Exit button works perfectly (it ends the app) except for one scenario. if we click on aboutus and go to that activity and then press back button on that aboutus activity and then again come back to main activity and finally when i want to exit it won't kill whole app, instead it again goes to the about activity.
in conclusion,
MainActivity---> click aboutus button(no problem in here.this will start aboutus activity)
Aboutus----->click back button(this also works fine. go back to main activity)
MainActivity--> Exit button (not working .it goes to aboutus activity again)
So how to fix this problem?
i dont see why you have to start MainActivity.java ...the user can just hit the back button as long as its on the activity stack. Also The system.exit(0) is bad. Just let the app finish gracefully with finish().
if you want to pass something to the activity when aboutUS is done, you can look up onNewIntent() method.
use intent flag ACTIVITY_CLEAR_TOP to clear all activities on top of it:
Intent intent = new Intent(AboutUs.this,MainActivity.class);
intent.putExtra("aboutus", true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent);
FLAG_ACTIVITY_CLEAR_TOP From the doc:
If set, and the activity being launched is already running in the
current task, then instead of launching a new instance of that
activity, all of the other activities on top of it will be closed and
this Intent will be delivered to the (now on top) old activity as a
new Intent.
In my application, I have two activities. First is a splash screen, which simply shows the application name and few other info.
Upon clicking on the splash screen activity, I'm loading the main activity. My app works fine, but I'm facing a small issue. If I press back button from my main activity, control is going to splash screen activity. But I don't want to show the splash screen activity again, I want to avoid splash screen activity when pressing Back button.
Is it possible? If so how?
In your AndroidManifest.xml file, add android:noHistory="true" attribute in your splash screen <activity>.
As I understand, you want the splash activity to not show after changing activity. You should note activities save On Stack and with starting new activity push on it and with finish you pop on top stack. I think that if you the call finish() method your problem fix as in your splash screen activity where you call StartActivity insert finish() after
public void onClick(View v) {
Intent intent = new Intent(Main.this, Splash.class);
startActivity(intent);
finish();
}
Hope to be useful :)
You can just call
finish();
In your Splash screen when you jump to the second screen.
In addition to the above answers, you should note
that:
1: by calling the finish() method, the Splash activity
will close after execution, meaning that it will not be
available in the stack.
#Override
protected void onCreate(Bundle saveInstsnceState){
super.onCreate( saveInstanceState);
\\ do something here
Intent intentSplash = new Intent(SplashActivity.this, NextActivity.class);
StartActivity(intentSplash);
finish ();
}
You will achieve your aim using the method above
but...
2: If you want to prevent your users from force
exiting the app (pressing back button) while the
splash activity in still ongoing which is the best
practice in android, then you need to call the
onBackPressed () method.
Class NoBackSplash{
#Override
protected void onCreate(Bundle saveInstsnceState){
super.onCreate( saveInstanceState);
\\ do something here
Intent intentSplash = new Intent(SplashActivity.this, NextActivity.class);
StartActivity(intentSplash);
finish ();
}
#Override
public void OnBackPressed(){
};
}
With this OnBackPressed() method, your splash activity will not be force to exit no matter how hard the user try.
I understand, you want the splash activity to not show when you click on back button. First of all you should know that all the activities on android are in form of STACK. So what we need we just end the splash activity after it execute. we can do this by calling finish() method in android studio. here is the solution:
Intent intent = new Intent(MainActivity.this, home.class);
startActivity(intent);
finish();
public class Splash extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Handler hd = new Handler();
hd.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(Splash.this,MainActivity.class);
startActivity(i);
#by calling finish() method,splash activity will close after execution
finish();
}
},3000);
}}
I am sure this question has been asked number of times because I read a few. My client wants me to put a button into his app where users can click and exit. I have read this and found calling finish() will do it. But, finish is only closing the current running activity right? I have lot of activities so in this case I have to pass each and every activity's instance and finish them or make every activity into Singleton pattern.
I also got to know Activity.moveTaskToBack(true) can get you into the home screen. OK, this is not closing but backgrounding the process. So is this is effective?
Which method should I use to close the app completely? Any of above described or any other method/other usage of above methods?
The finishAffinity method, released in API 16, closes all ongoing activities and closes the app:
this.finishAffinity();
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
Since API 21, you can use:
finishAndRemoveTask();
Finishes all activities in this task and removes it from the recent tasks list.
Alternatives:
getActivity().finish();
System.exit(0);
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Process.sendSignal(Process.myPid(), Process.SIGNAL_KILL);
Intent i = new Intent(context, LoginActivity.class);
i.putExtra(EXTRA_EXIT, true);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(i);
Source: How to quit android application programmatically
Actually everyone is looking for closing the application via an onclick event, wherever may be activity...
Add this code to an onclick event:
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory( Intent.CATEGORY_HOME );
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
You can call System.exit(); to get out of all the acivities.
submit=(Button)findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
If you want to exit from your application, use this code inside your button pressed event:
public void onBackPressed() {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Exit Application?");
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
It's way too easy. Use System.exit(0);
Accually there are two possible situations:
You may want to exit from the activity
Or you want to exit from the application
You can exit from the activity using following code:
var intent = new Intent(Intent.ActionMain);
intent.AddCategory(Intent.CategoryHome);
intent.SetFlags(ActivityFlags.NewTask);
startActivity(intent);
finish();
But this will not kill the underlying activities in the same application.
This will just minimize the application.
If you want to exit from application use the following code to end its process:
android.os.Process.killProcess(android.os.Process.myPid());
for mono development just use
process.KillProcess(Process.MyPid());
How about this.finishAffinity()
From the docs,
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
android.os.Process.killProcess(android.os.Process.myPid());
this will clear Task(stack of activities) and begin new Task
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
System.exit(1);
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory( Intent.CATEGORY_HOME );
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
System.exit(1);
Use this Code it's much useful, and you can exit all of the activities.
#Override
public void onBackPressed() {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory( Intent.CATEGORY_HOME );
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
Achieving in Xamarin.Android:
public override void OnBackPressed()
{
MoveTaskToBack(true);
Process.KillProcess(Process.MyPid());
Environment.Exit(1);
}
put this one into your onClic:
moveTaskToBack(true);
finish()
Try this on a call. I sometimes use it in onClick of a button.
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
It instead of closing your app , opens the dashboard so kind of looks like your app is closed.
read this question for more clearity
android - exit application code
Use this.finishAffinity(); on that button instead of finish();
If it does not work then you can also try by adding android:noHistory="true" in your manifest and then finish your activity by uisng finish(); or finishAffinity();
Hope it helps....:)
Just call these two functions
finish();
moveTaskToBack(true);
Link this method to your quit/exit button
public void quitGame(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
finishAndRemoveTask();
} else {
finish();
}
}
ghost activity called with singletop and finish() on onCreate should do the trick
It works using only moveTaskToBack(true);
Instead of System.exit(1) Just use System.exit(0)
finish();
finishAffinity();
System.exit(0);
worked for me
If someone still wonders, for Xamarin.Android (in my case also Monogame running on it) the command FinishAndRemoveTask() on Activity does the job very well!
in the fragment
getActivity().finishAndRemoveTask();
in the Activity
finishAndRemoveTask();
just use the code in your backpress
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
If you are using EventBus (or really any other pub/sub library) in your application to communicate between activities you can send them an explicit event:
final public class KillItWithFireEvent
{
public KillItWithFireEvent() {}
public static void send()
{
EventBus.getDefault().post(new KillItWithFireEvent());
}
}
The only downside of this is you need all activities to listen to this event to call their own finish(). For this you can easily create shim activity classes through inheritance which just listen to this event and let subclasses implement everything else, then make sure all your activities inherit from this extra layer. The kill listeners could even add some extra functionality through overrides, like avoiding death on certain particular situations.
Just run the below two lines when you want to exit from the application
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
Just call this:
finishAffinity();
This can work I tried it too.
this.finishAffinity();
In Fragment use getActivity().finishAffinity(); and clear fragment binding without memory leaks