Android back button app is not closing - android

i am using the below code for back button but it cant work it does not exit the app if i am pressing the back button of userdevice
private Boolean exit = false;
#Override
public void onBackPressed() {
if (exit) {
this.finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}

private Boolean exit = false;
#Override
public void onBackPressed() {
if (exit) {
this.finishAffinity();
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}

Change Your Code Like This.
private Boolean exit = false;
#Override
public void onBackPressed() {
if (exit) {
this.finishAffinity();
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}

use this...
private long lastBackPressTime = 0;
#Override
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
//Add Snhackbar or Toast, whatever you want
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
moveTaskToBack(true);
}
}

keep a boolean toClose=false;
and in onBackPressed() method use this code
if (toClose)
super.onBackPressed();
else
{
toClose=true;
Utils.showToast(context,getString(R.string.back_again));
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
toClose=false;
}
},2000);
}

This may work. Use finishAffinity() instead.
boolean doubleBackToExitPressedOnce = false;
public void onBackPressed(){
if(doubleBackToExitPressedOnce)
{
finishAffinity();
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;
}
},3500);
}

Use this to close the app on pressing back button.
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}

This will work for you
Define this it globally
private boolean doubleBackToExitProceed = false;
#Override
public void onBackPressed() {
if (doubleBackToExitProceed) {
finish();
return;
}
doubleBackToExitProceed = true;
Toast.makeText(this, "Press Back again to Exit.", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitProceed = false;
}
}, 2000);// time in milliseconds.
}

Related

Need help regarding CountDownTimer in onbackpressed

I have been trying to create the onbackpressed() function using countdown but i don't know what to do. Kindly help me to create the onbackpressed function using countdown
private static boolean onbackpressonce = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// using countdown timer
#Override
public void onBackPressed() {
if (!onbackpressonce) {
Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();
onbackpressonce = true;
} else {
super.onBackPressed();
}
new CountDownTimer(3000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
onbackpressonce = false;
}
}.start();
}
This will exit your app on the second onBackpressed within 1100 millis
private long mLastBackClick = 0;
#Override
public void onBackPressed() {
if (System.currentTimeMillis() - mLastBackClick < 1100) {
super.onBackPressed();
} else {
Toast.makeText(MainActivity.this, "Press back again to Exit", Toast.LENGTH_SHORT).show();
mLastBackClick = System.currentTimeMillis();
}
}

Press Double Back To Exit

Android Webview
current code in my app works like this:
When user press back single time it will shows button asking "Do you want to quit?" shows yes or no options. when we select Yes it exit app and show interstitial ad. if you press No it will remains in the activity.
What I want is:
When user press back it will go to previous activity. If user double tap back button then it will ask for exit and if user select Yes. user will exit app and interstitial ad appears.
Please help me to solve this issue.
Main Activity:
public class MainActivity extends Activity{
private Fragment contentFragment;
String testDevice = "D0A04359EA1ECE9BA0CD4B6F457A9991";
String testDevice2 = "63C3530DA03C191310DB9AB8F0672E5C";
String testDevice3 = "801F2141A1DC3F743363AFDFDC42AF3A";
private InterstitialAd mInterstitialAd;
private AdView mAdView;
boolean displayAd = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mainWebView.loadUrl(this.getString(R.string.channel_url));
mAdView = (AdView) findViewById(R.id.ad_view);
// Create an ad request. Check your logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(testDevice)
.addTestDevice(testDevice2)
.addTestDevice(testDevice3)
.build();
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
displayAd = true;
// View servername = findViewById(R.id.txt_List);
// RelativeLayout.LayoutParams layoutparams =
(RelativeLayout.LayoutParams) servername.getLayoutParams();
// layoutparams.addRule(RelativeLayout.BELOW, mAdView.getId());
// layoutparams.removeRule(RelativeLayout.ALIGN_PARENT_TOP);
// servername.setLayoutParams(layoutparams);
}
#Override
public void onAdFailedToLoad(int errorCode) {
if (!displayAd) {
}
}
#Override
public void onAdClosed() {
// Proceed to the next level.
}
});
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
// Create the InterstitialAd and set the adUnitId (defined in values/strings.xml).
mInterstitialAd = newInterstitialAd();
loadInterstitial();
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
private InterstitialAd newInterstitialAd() {
InterstitialAd interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
}
#Override
public void onAdFailedToLoad(int errorCode) {
}
#Override
public void onAdClosed() {
// Proceed to the next level.
finish();
//goToNextLevel();
}
});
return interstitialAd;
}
private void showInterstitial() {
// Show the ad if it's ready. Otherwise toast and reload the ad.
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
finish();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void loadInterstitial() {
// Disable the next level button and load the ad.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(testDevice)
.addTestDevice(testDevice2)
.addTestDevice(testDevice3)
.setRequestAgent("android_studio:ad_template").build();
mInterstitialAd.loadAd(adRequest);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof EmpListFragment or if the stack entry count is == 0, then
* we prompt the user whether to quit the app or not by displaying dialog.
* In other words, from EmpListFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
onShowQuitDialog();
}
public void onShowQuitDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Do You Want To Quit?");
builder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
showInterstitial();
}
});
builder.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
}
This is the easiest code possible:
private static final int TIME_DELAY = 2000;
private static long back_pressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onBackPressed() {
if (back_pressed + TIME_DELAY > System.currentTimeMillis()) {
super.onBackPressed();
} else {
Toast.makeText(getBaseContext(), "Press once again to exit!",
Toast.LENGTH_SHORT).show();
}
back_pressed = System.currentTimeMillis();
}
}
A temp flag will do the thing.
add this code in your onBackPressed() method.
boolean isSecond;
#Override
public void onBackPressed(){
if (isSecond) {
// Open your dialog here
}
isSecond = true;
new Handler() . postDelayed(new Runnable() {
#Override
public void run(){
isSecond = false;
}
}, 2000);
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
onShowQuitDialog();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
Try following code :
int backFlag = 0;
#Override
public void onBackPressed() {
backFlag ++;
if(backflag == 1){
super.onBackPressed();
// go to previous activity
}
else if(backFlag == 2){
// ask user to exit
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
backFlag=0;
}
}, 2000);
}
There is no built-in function for double onBackPressed() so you have to construct your own version of it. The android system provides a Handler on which you can call postDelayed to measure the time between two and one click.
e.g. like this
boolean backPressed = false;
boolean backPressedTwice = false;
#Override
public void onBackPressed() {
if(!backPressed){
backPressed = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(!backPressedTwice)
MainActivity.this.finish(); // go back to previous activity
}
}, 500);
}
if(backPressed) {
// it's clicked twice
backPressedTwice = true; // cancel the handler so it does not finish the activity
onShowQuitDialog();
}
}
Demo for your task:
public class MainActivity extends AppCompatActivity {
Handler handler = new Handler();
boolean ShowDialog = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler(getMainLooper());
}
#Override
public void onBackPressed() {
if (!ShowDialog) {
this.ShowDialog = true;
handler.postDelayed(runnable, 2000);// time setting .. current is 2 sec
} else {
handler.removeCallbacks(runnable);
ShowDialog = false;
ShowDailog();
}
}
private void ShowDailog() {
Toast.makeText(this, "show dialog here", Toast.LENGTH_LONG).show();
}
Runnable runnable = new Runnable() {
#Override
public void run() {
ShowDialog = false;
MainActivity.super.onBackPressed();
}
};
}
You can do something like this
private long backPressedTime = 0;
private long backPressThreshold = 400;
private Handler mHandler = new Handler();
private Runnable bacPressedRunnable = new Runnable() {
#Override
public void run() {
MYActivity.super.onBackPressed();
}
};
#Override
public void onBackPressed() {
if(backPressedTime = 0){
backPressedTime = Systemm.currentTimeInMillis();
mHandler.postDelayed(bacPressedRunnable,backPressThreshold);
}else if(System.currentTimeInMillis()-backPressedTime >= backPressThreshold){
mHandler.removeMessages(bacPressedRunnable);
onShowQuitDialog();
}else{
super.onBackPressed();
}
backPressedTime = 0;
}
Exit android App on double back press use following updated code. It may solve your problem
private boolean doubleBackToExitPressedOnce;
private void onApplicationBackPressed() {
if (doubleBackToExit) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
return;
}
doubleBackToExit= true;
Utilities_dialer.showToastMessage(this, "Press Again To Exit");
//use your dialog box or toast message
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExit= false;
}
}, 2000);
}
Try this.. It may help you.
Boolean doubleBackToExitPressedOnce = true;
#Override
public void onBackPressed() {
if(doubleBackToExitPressedOnce){
// Do what ever you want
doubleBackToExitPressedOnce = false;
} else{
// Do exit app or back press here
super.onBackPressed();
}
}

How to interrupt a thread onBackPressed without crashing?

I have tried overriding onBackPressed to not only finish the current activity but also to interrupt the thread as I am calling an intent to the next activity within. When I pressed back before, the splash activity finished, but the thread kept running and call the intent to the next activity. Now that I've include the thread interruption onBackPressed,the app crashes when I press back. What am I doing wrong?
skipscreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences savestate = getSharedPreferences("skip", MODE_PRIVATE);
savestate.edit().putBoolean("skip", true).apply();
skip= true;
homeintent();
}
});
Thread splashthread = new Thread() {
#Override
public void run() {
try {
sleep(3000);
if (!skip) { homeintent();}
} catch (InterruptedException Interrupt) {
Interrupt.printStackTrace();
}
}
};
splashthread.start();
}
private void homeintent() {
Intent i = new Intent(splash.this, home.class);
startActivity(i);
finish();
}
#Override
public void onBackPressed() {
splashthread.interrupt();
finish();
}
}
UPDATED: (This solution has worked for me).
skipscreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences savestate = getSharedPreferences("skip", MODE_PRIVATE);
savestate.edit().putBoolean("skip", true).apply();
skip= true;
homeintent();
}
});
Thread splashthread = new Thread() {
#Override
public void run() {
try {
sleep(3000);
if (!skip) { homeintent();}
} catch (InterruptedException Interrupt) {
Interrupt.printStackTrace();
}
}
};
splashthread.start();
}
private void homeintent() {
if (!ThreadInterrupted) {
Intent i = new Intent(splash.this, home.class);
startActivity(i);
}
finish();
}
#Override
public void onBackPressed() {
SharedPreferences savestate= getSharedPreferences("ThreadInterrupted", MODE_PRIVATE);
savestate.edit().putBoolean("ThreadInterrupted", true).apply();
ThreadInterrupted = true;
homeintent();
}
}
To give you a succint answer as well as to explain how to do this in the future,take a look at the Handler class and the Handler.postDelayed() method.
private Handler homeIntenthandler;
#Override
protected void onCreate(){
//other things
skipscreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences savestate = getSharedPreferences("skip", MODE_PRIVATE);
savestate.edit().putBoolean("skip", true).apply();
skip= true;
homeintent();
}
});
//initialise handler and set timer;
homeIntenthandler= new Handler();
homeIntenthandler.postDelayed(new Runnable() {
#Override
public void run() {
homeintent();
}
},3000);
}
}
private void homeintent() {
Intent i = new Intent(splash.this, home.class);
startActivity(i);
finish();
}
#Override
public void onBackPressed() {
if(homeIntenthandler!=null)
homeIntenthandler.removeCallbacksAndMessages(null)
finish();
}
}
the Handler.removeCallbacksAndMessages(null) is based on the documentation given for the same
When you call interrupt() method on your thread, while in sleep, an InterruptedException will be thrown.
You can check inside your thread weather it should continue:
Thread splashthread = new Thread() {
#Override
public void run() {
while (shouldContinue) {
doSomeWork();
}
}
};
You can then change shouldContinue to false in your onBackPressed method:
#Override
public void onBackPressed() {
shouldContinue = false;
finish();
}
Udi I has answered your question.
But i refer you to use TimerTask and Timer instead of Thread.
Timer timer;
TimerTask timertask;
timer = new Timer();
timertask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
homeintent();
}
});
}
};
timer.schedule(timertask, 3000);
#Override
public void onBackPressed() {
if(timertask!=null){
timertask.cancel();
}
if(timer!=null){
timer.cancel();
}
finish();
}
You can create a volatile boolean check to stop thread from progressing, see following code:
private volatile boolean cancelled = false;
Thread splashthread = new Thread() {
#Override
public void run() {
if ( cancelled ) {
return; // or handle this however you want
}else{
// do what ever you want to do here
}
}
};
splashthread.start();
And in onBackPressed do something like this:
#Override
public void onBackPressed() {
cancelled = true;
finish();
}
The volatile keyword is recommended because, generally, the thread doing the cancelling not necessarily will be the same thread that is being cancelled. Marking boolean check as volatile ensures that the thread checking the flag will see the up to date value.

My Application is not exiting when I double tap the Hardware Back Button

I'm trying to exit my application when the user double taps the HardWare Back Button, I've used the following code in my application:
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
Dashboard_Activity.this.finish();
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);
Here when the user Double Taps the Hardware Back Button the same activity appears again and again, but the app doesn't exits. Can you please help me fixing the issue.
Try the following:
private static long back_pressed;
#Override
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
Source
Try This Method Any where in your code Out side of Oncreate, Working for me
#Override
public void onBackPressed()
{
try
{
//pop up Window closed.
if (doubleBackToExitPressedOnce)
{
super.onBackPressed();
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);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
First, create SplashScreenActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finish();
}
Then in your activity(or in BaseActivity) add this variable as class member:
private long milis;
And override onBackPressed():
#Override
public void onBackPressed() {
if(milis + 2000 > System.currentTimeMillis()){
Intent intent = new Intent(this, SplashScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else{
milis = System.currentTimeMillis();
}
}

App exit on double tab in android

I want to exit the app only when double tap continously. I am using fragment class. I used the below code but doesn't work
private long lastPressedTime;
private static final int PERIOD = 2000;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
if (event.getDownTime() - lastPressedTime < PERIOD) {
finish();
} else {
Toast.makeText(getApplicationContext(), "Press again to exit.",
Toast.LENGTH_SHORT).show();
lastPressedTime = event.getEventTime();
}
return true;
}
}
return false;
}
please guide me how to implement this in an app.
#Override
public void onBackPressed() {}
in your activity, because activity responsible for back button handling
Look to this question, it has not got an accepted answer, but contain some solutions
Remove your implementation inside onKeydown and try this code
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
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);
}
try this :
private boolean doubleBackToExitPressedOnce;
#Override
public void onBackPressed() {
Log.i(tag, "Start: On Back Pressed!");
if (doubleBackToExitPressedOnce) {
Log.i(tag, "Double Back Pressed!");
super.onBackPressed();
return;
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, R.string.msg_exit, Toast.LENGTH_SHORT).show();
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2500);
}
dont forget to add this line in onResume:
#Override
protected void onResume() {
doubleBackToExitPressedOnce = false;
}

Categories

Resources