How to exit the app on double back press? - java

I am trying to write a code to exit the app when double pressing the back button. I don't want to call super.onBackPressed(); since it takes me back to the first activity which is splash screen, and I don't want that, I want to exit the app on double pressing. Thank you.
This is my onBackPressed method:
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else{
if (doubleBackToExitPressedOnce) {
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}

If you didn't call finish() before you start your second Activity from the first one, it will remain, so when you close your second one,
the program takes you back to the first one, which is not finished yet.
So call finish() after startActivity() in your first Activity

Define two class level variables like
private long TIME_DELAY = 2000;
private long back_pressed;
on OnBackPressed() method, write below code.
if (back_pressed + TIME_DELAY > System.currentTimeMillis()) {
finish();
super.onBackPressed();
} else {
Toast.makeText(getBaseContext(), R.string.press_back_again_to_exit,
Toast.LENGTH_SHORT).show();
}
back_pressed = System.currentTimeMillis();

just use finish() after launching the intent to the next activity:
startActivity(new Intent(this, NextActivity.class));
//Below will enable the app to exit if back is pressed
finish();

Related

resultCode has value -1 after a buttonpress and finish() but 0 after backbutton pressed even with same code in corresponding functions

I have a RecyclerView with its Adapter.class in a separate file but the onClickListener in the adapter starts the second Activity just fine with startActivityForResult. When I have the users input I want the app to send back the data to the first Activity which only works when the user uses a button I provided, but not when he uses the backbutton even when it runs the same code in the corresponding functions.
i copied the exact same code from the button to onBackPressed, onPause and onDestroy but on Destroy gets run too late, and the other two lead to resultCode being 0 and data being null in Activity 1. I have changed setResult and its arguments to all possible variants I found(RESULT_OK+Intent, Activity.RESULT_OK+Intent and just RESULT_OK).
back = new Intent(this, MainActivity.class);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
back.putExtra("ANSWER", answer.getText().toString());
back.putExtra("QUESTION_ID", questionId);
setResult(RESULT_OK, back);
finish();
}
});
#Override
public void onBackPressed() {
super.onBackPressed();
back.putExtra("ANSWER", answer.getText().toString());
back.putExtra("QUESTION_ID", questionId);
setResult(RESULT_OK, back);
}
#Override
protected void onPause() {
super.onPause();
back.putExtra("ANSWER", answer.getText().toString());
back.putExtra("QUESTION_ID", questionId);
setResult(RESULT_OK, back);
}
if I use the Button it passes the data and sets the resultCode to -1 just fine but when I don't use the button but the backbutton resultCode = 0 and data in on ActivityResult is null. I don't know what makes the difference
Try set result before onBackPressed of superclass calling:
#Override
public void onBackPressed() {
back.putExtra("ANSWER", answer.getText().toString());
back.putExtra("QUESTION_ID", questionId);
setResult(RESULT_OK, back);
super.onBackPressed();
}

Within Android how do I check if and what other activities have been left open on the stack?

Basically I want to do an if statement like below, but I don't know how.
if (Android_Classes_Left_Open){
Intent a = new Intent(SplashScreen.this, 2ndtoTopElement.class);
startActivity(a);
} else {
Intent a = new Intent(SplashScreen.this, Other.class);
startActivity(a);
}
My SplashScreen code so far:
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreen.this, First.class);
startActivity(i);
finish();
}
}, 3000);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.splash, menu);
return true;
}
}
The purpose of this is, if the user moves the application into the background they are then returned to their most recently opened activity rather than starting the application from scratch each time. How can I achieve this?
your solution is that whenever you entered in any new activity....
1.) You have to save the name of this activity in shared preferance(on same key) you have to perform this things in onResume() of every activity or your BaseActivity.
2.) At the every time of splash screen you have to check the name of this activity and pass it in your intent.
so you get the last open activity each time after your splash screen done.

Closing app on pressed hardware button back twice returns to a previous activity instead

In my main activity the user gets notified to press the hardware back button to exit the app. This works in most circumstances except for when the user dies. When the user dies it goes to a GameOverActivity. If the user presses the back button in this activity and then proceeds to press back twice on the main activity, it reopens the game over activity. Here is the code, I have declared finish() on the back button in game over activity but it doesn't seem to help.
MainScreen back to quit method:
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press again to quit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
GameOverActivity code:
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent mainScreenActivityIntent = new Intent(GameOverActivity.this, MainScreenActivity.class);
startActivity(mainScreenActivityIntent);
finish();
}
});
}
#Override
public void onBackPressed() {
Intent mainScreenActivityIntent = new Intent(GameOverActivity.this, MainScreenActivity.class);
mainScreenActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainScreenActivityIntent);
finish();
}
Here is the logic for the collision and thus creation of GameOverActivity:
if (weight.getBounds().intersect(player.getBounds())) {
player.setTouched(false);
Intent gameOverIntent = new Intent(this.getContext(), GameOverActivity.class);
this.getContext().startActivity(gameOverIntent);
((Activity) getContext()).finish();
}
You are starting a new activity and just finishing current activity, add necessary code to finish the activity which you starts from onBackPressed.
I think you have some confuses about Activity life cycle.
Pressing back on GameOverActivity instantiates a new mainScreenActivity, which will produce your problem.
and in your GameOverActivity onbackpressed call super.onBackPressed
#Override
public void onBackPressed()
{
super.onBackPressed();
// and dont start a new activity as you are stacking MainActivity instances
finish()
}
You should call finish() in MainScreen immediately after start Activity GameOverActivity

Check if back key was pressed in android?

Say I'm on my main activity and I start a new activity
MainActivity > NewActivity
And from NewActivity I press the back key
MainActivity < NewActivity
I want MainActivity to do something if it's being displayed after NewActivity is closed, but not when MainActivity is run normally, such as when first running the application. Does anyone know if this is possible?
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.d(this.getClass().getName(), "back button pressed");
}
return super.onKeyDown(keyCode, event);
}
#Update. If you want to be notified when NewActivity is finished, you have to start it by startActivityForResult(Intent, requestCode). Then, you must override onActivityResult() on MainActivity. Check the requestcode parameter here, if the return code equals the submit code (when you start childActivity), put some code to do your business.
int MYCODE=1000;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Result OK.d.
if (requestCode == MYCODE) {
// do something good
}
}
I try the below method to detect the back button pressed on the action bar in activity by the first method and the second one is used to detecting the mobile hardware button back or kill activity button.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
setResult(RESULT_CANCELED);
super.onBackPressed();
}
You can override onBackPressed() method in NewActivity which will detect when back button is pressed. And then to inform the MainActivity about it, you can send a boolean flag in a bundle so that MainActivity detects that its opening after NewActivity.
In NewActivity:
#Override
public void onBackPressed() {
boolean fromNewActivity=true;
Intent mainIntent = new Intent(view.getContext(), MainActivity.class);
Bundle bundleObj = new Bundle();
bundleObj.putString("fromNewActivity", Boolean.toString(fromNewActivity));
mainIntent.putExtras(bundleObj);
startActivityForResult(mainIntent, 0);
}
In MainActivity in onCreate() method :
Bundle extras = getIntent().getExtras();
boolean fromNewActivity =Boolean.parseBoolean( extras.getString("fromNewActivity"));
Now you can check if the MainActivity is opened after NewActivity or not.
A couple of ideas:
You can just set a flag in MainActivity when it fires up NewActivity.
You can call startActivityForResult from MainActivity and arrange for NewActivity to set a result, which you will receive in MainActivity.onActivityResult() when NewActivity finishes.
When you start NewActivity you need to use startActivityForResult and use a valid requestId. Such requestId will be passed back to you to onActivityResult once NewActivity finishes.

Displaying a progress dialog until new activity loads

I have a progress dialog I am trying to show when a user clicks a button to launch a new activity. The spinner should be displayed on the current page until the other activity appears. ( The activity can take sometimes up to 4-5 seconds to launch and without the spinner it just shows a pressed button that looks frozen )
This is what I have, it's only working if I remove hideProgressDialog();, but then the spinner will still be there when I back to the previous activity, obviously.
What am I doing wrong ?
Progress Dialog :
public void showProgressDialog(Context context) {
if(this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
this.progressDialog = ProgressDialog.show(context, "", "Chargement en cours, veuillez patienter");
}
public void hideProgressDialog() {
if(this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
}
Function :
public void startActivity(Context context, Class<? extends Activity> activityClass) {
try {
showProgressDialog(context);
Intent intent = new Intent(this, activityClass);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
hideProgressDialog();
}
catch(Throwable e) {
e.printStackTrace();
}
}
Example of a button click where this calls the function to show the spinner :
#Override
public void onClick(View view) {
if(view.getId() == R.id.changeBannerButton) {
getBaseApplication().startActivity(this, BannerListActivity.class);
}...
Call hideProgressDialog() in the onResume() method. This way, if the user presses the back button, the onResume() method gets called and immediately hides the progress dialog.
Well First off you should use the new DialogFragment class with FragmentManager. Because showdialog() is deprecated from API level 8
Next you should use showdialog and removedialog for adding and removing the dialog.
And you should use the onCreateDialog to handle the dialog and the operations. Like start a new thread to run do the job when you are displaying the progressdialog.
Try to load data in a seperate thread on start of activity. But before start of that process show the progress dialog. Now once the process is done use runOnUI to hide the progress dialog..
Indicate the user that data is being loading
http://www.helloandroid.com/tutorials/using-threads-and-progressdialog
and this:
Android - using runOnUiThread to do UI changes from a thread

Categories