Make application quit Android - java

Hey guys I'm trying to make a function that quit my application when onClick on a Button but it doesn't work.
Would you take a look and let me now what's wrong with the code please ?
Here is the code :
public void addListenerOnButtonLeave()
{
quitButton = (ImageView) findViewById(R.id.quitButton);
quitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
moveTaskToBack(true);
}
});
}
I put this function into the overrided onCreate().
Thanks for your help guys.

You may also use finishActivity (int requestCode)
Force finish another activity that you had previously started with
startActivityForResult(Intent, int).

Probably some of your activities are running in background. When you have switched between activities, you have not finished them.
First finish those activities by adding
ActivityName.this.finish()
just before you sail to another activity, and then use
getActivity().finish();
System.exit(0);
to quit the app triggered where needed.

Related

How can i make double press back to close my app

I have startActivity and HomeScreen activity. HomeScreen activity appears after startActivity. I want to implement double click back to close the application. I tried this code, but after the app is closed, it immediately reopens again or just returns to startActivity.
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Нажмите ещё раз что бы закрыть приложение", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
If this code is in some child activity (not in the main activity), then try replacing:
super.onBackPressed()
with:
finishAffinity()
Since according to the docs:
The default implementation simply finishes the current activity, but you can override this to do whatever you want.
calling super.onBackPressed() will finish current activity - not the whole application. And probably this is the source of Your bugs, but I cannot know for sure, since You haven't provided us with broader context - more code.
So, on the other hand finishAffinity() might be the solution for You. Docs say:
Finish this activity as well as all activities immediately below it in the current task that have the same affinity.
This should finish all the activities.

Is there a way to exactly detect when an activity is destroyed in android?

I am making an android app in java in which I need to trigger some database requests whenever an activity is completely destroyed which would probably happen if the user presses the back button or leaves the app itself... But the onDestroy() function in my app is randomly getting triggered even when the user is still on the activity... I guess the probable reason for this is configuration changes but I am not able to figure out a proper solution for this.
Is there a way we could exactly detect when an activity is left by a user avoiding any in-page configuration changes??
The onDestroy() that I am using is this:
#Override
protected void onDestroy() {
/// do smthng
super.onDestroy();
}
Any help would be appreciated!!
Solved:
Thank you for the answer guys... For me onStop() worked out perfectly and it is working in every case whether it might be pressing the back button or exiting the activity or the app itself!!
If you want to check if the user ended the activity, meaning pressed back, do this:
#override
public void onBackPressed(){
//do something before we finish the activity
super.onBackPressed();
}
If you want to check when user, goes to next activity, then resturns to the same activity:
#override
public void onResume(){
//do something when return back to this activity
super.onResume();
}
#override
public void onPause(){
//do something before going to another activity
super.onPause();
}
onDestroy is called when the activity is destroyed or finished and not guaranteed to be called always, don't depend on it
We can check on whether our application is foreground or background based on the activity entering and exiting the foreground by implementing ActivityLifecycleCallbacks.
Good reference : https://medium.com/#iamsadesh/android-how-to-detect-when-app-goes-background-foreground-fd5a4d331f8a
Quoting from the above article,
#Override
public void onActivityStarted(Activity activity) {
if (++activityReferences == 1 && !isActivityChangingConfigurations) {
// App enters foreground
}
}
and,
#Override
public void onActivityStopped(Activity activity) {
isActivityChangingConfigurations = activity.isChangingConfigurations();
if (--activityReferences == 0 && !isActivityChangingConfigurations) {
// App enters background
}
}
by which we can make sure that our app is in foreground or not. Here you always have the control of what activity is in foreground based on which you can check and execute the logic.

How to exit an app when Back Button is pressed

This is a small question but I'm finding very hard to solve this. I have multiple activities. For example A B and C. When app is launched A is opened and on click of button will redirect me to activity B and then from B on click of another button will take me to C. On Back pressed will now bring me back to B and again on Back button is pressed will take me to A which is main Activity.
Now if I press back button, instead the app should exit...it creates loop between B and A and never exit the app.
I already used the following method
Method 1:
use of this.finishonBackPressed which didn't help
Method 2:
use android:nohistory = true in manifest
But If I do so then from C activity it will directly take me to A which I don't want.
Method 2.
Use of
Intent intent = new Intent(Intent.ACTION_MAIN);
//to clear all old opened activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
when I use this then everytime this opens up in my device
Please anyone help.
This is my code in Mainactivity now
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
But also it don't work and it creates loop between A and B Activity.
Your code (in MainActivity) is incorrect , put finish() after super.onBackPressed()
it must be :
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity(); // or finish();
}

On physical back button pressed how to go to device's home screen? [duplicate]

When a user presses the back button on an intent, the application should quit. How can I ensure the application quits when the back button is pressed?
In my Home Activity I override the "onBackPressed" to:
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
so if the user is in the home activity and press back, he goes to the home screen.
I took the code from Going to home screen Programmatically
Immediately after you start a new activity, using startActivity, make sure you call finish() so that the current activity is not stacked behind the new one.
EDIT
With regards to your comment:
What you're suggesting is not particularly how the android app flow usually works, and how the users expect it to work. What you can do if you really want to, is to make sure that every startActivity leading up to that activity, is a startActivityForResult and has an onActivityResult listener that checks for an exit code, and bubbles that back. You can read more about that here. Basically, use setResult before finishing an activity, to set an exit code of your choice, and if your parent activity receives that exit code, you set it in that activity, and finish that one, etc...
A better user experience:
/**
* Back button listener.
* Will close the application if the back button pressed twice.
*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
The app will only exit if there are no activities in the back stack. SO add this line in your manifest android:noHistory="true" to all the activities that you dont want to be back stacked.And then to close the app call the finish() in the OnBackPressed
<activity android:name=".activities.DemoActivity"
android:screenOrientation="portrait"
**android:noHistory="true"**
/>
Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.
If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).
If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.
Use onBackPressedmethod
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
This will solve your issue.
First of all, Android does not recommend you to do that within the back button, but rather using the lifecycle methods provided. The back button should not destroy the Activity.
Activities are being added to the stack, accessible from the Overview (square button since they introduced the Material design in 5.0) when the back button is pressed on the last remaining Activity from the UI stack. If the user wants to close down your app, they should swipe it off (close it) from the Overview menu.
Your app is responsible to stop any background tasks and jobs you don't want to run, on onPause(), onStop() and onDestroy() lifecycle methods. Please read more about the lifecycles and their proper implementation here: http://developer.android.com/training/basics/activity-lifecycle/stopping.html
But to answer your question, you can do hacks to implement the exact behaviour you want, but as I said, it is not recommended:
#Override
public void onBackPressed() {
// make sure you have this outcommented
// super.onBackPressed();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
To exit from an Android app, just simply use.
in your Main Activity, or you can use Android manifest file to set
android:noHistory="true"
finish your current_activity using method finish() onBack method of your current_activity
and then add below lines in onDestroy of the current_activity for Removing Force close
#Override
public void onDestroy()
{
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
}
I modified #Vlad_Spays answer so that the back button acts normally unless it's the last item in the stack, then it prompts the user before exiting the app.
#Override
public void onBackPressed(){
if (isTaskRoot()){
if (backButtonCount >= 1){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}else{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}else{
super.onBackPressed();
}
}
you can simply use this
startActivity(new Intent(this, Splash.class));
moveTaskToBack(true);
The startActivity(new Intent(this, Splash.class)); is the first class that will be lauched when the application starts
moveTaskToBack(true); will minimize your application
Add this code in the activity from where you want to exit from the app on pressing back button:
#Override
public void onBackPressed() {
super.onBackPressed();
exitFromApp();
}
private void exitFromApp() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}

Android - After closing an activity, when I run the app again, two activities run at the same time. How can I avoid it?

So I've got an activity in my android app, that runs on start.
This activity is just a page with a start button.
When I press the start button, it calls another activity and closes itself:
Intent i = new Intent(this, Dictating.class);
startActivity(i);
finish();
The other Activity is using Text-to-speech to dictate some words.
Now I've got something weird happening:
1) I listen to the dictating.
2) I press back button: dictating stops (what I want)
3) I run again the app, press the start button. Now I have my new activity running and dictating, but in the back I can hear the older Activity that resumed where it was, and continues dictating.
I would like for the new activity to start all over again, and not keep the other activity.
How can I do that ?
PS: This is an activity problem, and not a text-to-speech problem as I'm flushing the text-to-speech each time, It could not be kept in the memory
Thank you
EDIT:
Here is the onCreate of my Dictating class, there is tons of code in this class, I obviously don't want to post all my code, so here is some parts:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.streaming);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
this.txtCurrentWord = (TextView) findViewById(R.id.txtCurrentWord);
this.btnPlayPause = findViewById(R.id.btnPlayPause);
this.btnPlayPause.setOnClickListener(this);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
this.tts = new TextToSpeech(this, this);
} else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
there are a few weird things I'm doing like:
Runnable task = new Runnable() {
public void run() {
//runs on ui
runOnUiThread(new Runnable() {
public void run() {
readNextWord();
}
});
}
};
worker.schedule(task, 1, TimeUnit.SECONDS);
this delays the next word by one second, and then executes a fonction in the main ui thread. not sure if this matter
And some flushing at the end:
#Override
public void onDestroy() {
tts.shutdown();
super.onDestroy();
}
You need to add launchMode property to your activity inside AndroidManifest file, for more detail see "Using the manifest file"
This question is over a year old, but I can't believe no one ever gave you the right answer. Also, I don't think you should have accepted an answer that clearly didn't solve anything for you. By accepting such answers, you're just cluttering the StackOverflow google search results with junk for other people with the same problem.
The flushing you do at the end is completely wrong. According to the Activity lifecycle, onDestroy() is never guaranteed to be called. If you want to make sure the flushing gets done properly, do it inside of onPause().
For now the solution I'm giving you does fix the main problem you've described. However, if you do get the time to do a more complete rewrite, you'll want use a service that you bind to your activity. That will give you the finer control you require.

Categories

Resources