How can I configure the back button to be pressed twice before the app exits? I want to trigger
#Override
public void onBackPressed() {
//custom actions
//display toast "press again to quit app"
super.onBackPressed();
}
Try this:
private boolean doubleBackToExitPressedOnce = false;
#Override
protected void onResume() {
super.onResume();
// .... other stuff in my onResume ....
this.doubleBackToExitPressedOnce = false;
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press twice to exit", Toast.LENGTH_SHORT).show();
}
This snippet handle also the reset state when the activityis resumed
I see this question is a bit old but I though this might help some people looking for an alternative to the answers already given.
This is how I handle backing out of my applications. If someone has a better -- or a Google suggested -- method of accomplishing this I'd like to know.
Edit -- Forgot to mention this is for Android 2.0 and up. For previous versions override onKeyDown(int keyCode, KeyEvent event) and check for keyCode == KeyEvent.KEYCODE_BACK. Here is a good link to check out.
private boolean mIsBackEligible = false;
#Override
public void onBackPressed() {
if (mIsBackEligible) {
super.onBackPressed();
} else {
mIsBackEligible = true;
new Runnable() {
// Spin up new runnable to reset the mIsBackEnabled var after 3 seconds
#Override
public void run() {
CountDownTimer cdt = new CountDownTimer(3000, 3000) {
#Override
public void onTick(long millisUntilFinished) {
// I don't want to do anything onTick
}
#Override
public void onFinish() {
mIsBackEligible = false;
}
}.start();
}
}.run(); // End Runnable()
Toast.makeText(this.getApplicationContext(),
"Press back once more to exit", Toast.LENGTH_SHORT).show();
}
}
You could do what you're asking with a global integer and just count it, if > 2, quit.
But you could take a better (IMO) approach, where you question the user if they would like to quit or not:
private void questionQuit(){
final CharSequence[] items = {"Yes, quit now", "No, cancel and go back"};
builder = new AlertDialog.Builder(mContext);
builder.setCancelable(false);
builder.setTitle("Are you sure you want to quit?");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0:
quit();
break;
case 1:
default:
break;
}
}
}).show();
AlertDialog alert = builder.create();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK :
int i = 0 ;
if(i == 1 )
{
finish();
}
i++;
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Related
So, In my code the user must answer a quick math question and press a button to answer but for the next question it does not check for the second answer only the first. How could you make it where it then checks for the next answer and not the previous one?
primaryText.setText(Questions[0]);
enter.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v)
{
if(numberVal.getText().toString().equals("14")) {
primaryText.setText(Questions[1]);
}
if(numberVal.getText().toString().equals("5")) {
primaryText.setText(Questions[2]);
}
}
}
);
instead of
OnClickListener
try :
MyBtn1.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event){
if(event.getAction() == MotionEvent.ACTION_UP){
//do stuff
}
else if(event.getAction() == MotionEvent.ACTION_DOWN){
//do stuff
}
else if(event.getAction() == MotionEvent.ACTION_CANCEL){
//do stuff
}
return true;
}
});
boolean questionComplete = false;
enter.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v)
{
if(!(questionComplete)){
if(numberVal.getText().toString().equals("14")) {
questionComplete = true;
primaryText.setText(Questions[1]);
}
}
else {
if(numberVal.getText().toString().equals("5")) {
primaryText.setText(Questions[2]);
}
}
}
}
);
This would make it so that after the first question is complete, it would display the second question. It would only work for two questions though
i need to close and activity and start another only when the user presses back twice. I am using this code
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
Log.e("Entering","Yes");
DatabaseHandler db=new DatabaseHandler(AddBreakfastActivity.this);
db.deleteTodaysUnsavedMenu(Integer.parseInt(newDay),Integer.parseInt(newIntMonth));
Intent intent=new Intent(AddBreakfastActivity.this,ProvidersUpdateActivity.class);
startActivity(intent);
finish();
}
else {
this.doubleBackToExitPressedOnce = true;
Log.e("BOOLEANVALUE", String.valueOf(doubleBackToExitPressedOnce));
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);
}
}
On pressing back once the app exits and shows the Toast message.
It doesnt wait for the second press. How can i resolve this?
Thank you.
EDIT
Found it to be working as expected when the back button is pressed. However shows aforesaid issue when called from
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==android.R.id.home){
onBackPressed();
}
}
you can also do this with on keydown event as code below remove backpressed
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(event.getAction()==KeyEvent.ACTION_DOWN && keyCode==KeyEvent.KEYCODE_BACK)
{
if (doubleBackToExitPressedOnce) {
Log.e("Entering","Yes");
DatabaseHandler db=new DatabaseHandler(AddBreakfastActivity.this);
db.deleteTodaysUnsavedMenu(Integer.parseInt(newDay),Integer.parseInt(newIntMonth));
Intent intent=new Intent(AddBreakfastActivity.this,ProvidersUpdateActivity.class);
startActivity(intent);
finish();
}
else {
this.doubleBackToExitPressedOnce = true;
Log.e("BOOLEANVALUE", String.valueOf(doubleBackToExitPressedOnce));
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);
return false;
}
}
return super.onKeyDown(keyCode, event);
}
Here's an example of "Press Twice to Exit" with fragments:
boolean doublePressToQuit = false;
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
if (doublePressToQuit) {
DashBoardActivity.this.finish();
} else {
this.doublePressToQuit = true;
Toast.makeText(this, getString(R.string.quit_notification), Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doublePressToQuit = false;
}
}, 2000);
}
}
}
Include super.onBackPressed(); inside your IF statement to override the onBackPressed() event.
Try the below code, it works for me
boolean firstBackPressed = false;
.
.
.
#Override
public void onBackPressed() {
if (!firstBackPressed) {
firstBackPressed = true;
Toast.makeText(MainMenu.this, "Press back again to exit", Toast.LENGTH_SHORT).show();
} else {
super.onBackPressed();
}
}
Please find this
private boolean isShownExit;
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
drawerLayout.closeDrawer(Gravity.LEFT);
isShownExit = false;
return;
} else {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
if (!isShownExit) {
isShownExit = true;
showToast(this, "Press again to exit");
} else {
hideSoftKeyboardDialogDismiss(this);
startAnotherActivityHereWhichDoYouwant();
}
} else {
getSupportFragmentManager().popBackStack();
}
}
}
I wanna make a button that can show me how long time it gets pressed. If the button stops to get pressed the time still stays there, then you can keep pressing it. How can i do this?
With this code, I made a 5 second button-press open a new activity :)
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1=(Button)findViewById(R.id.button1);
final Handler handel = new Handler();
button1.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN:
handel.postDelayed(run, 5000/* OR the amount of time you want */);
break;
default:
handel.removeCallbacks(run);
break;
}
return true;
}
Runnable run = new Runnable() {
#Override
public void run() {
Intent i = new Intent(MainActivity.this, SecActivity.class);
startActivity(i);
}
};});
}}
if your mean a Button count the times it's pressed you can use:
int count = 0;
(your button).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
count++;
}
});
if you mean the longer you hold it you can use:
long time = 0;
(your button).setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == event.ACTION_DOWN){
time = System.currentTimeMillis();
}else if( event.getAcion() == event.ACTION_UP){
time = System.currentTimeMillis() - time;
}
return true;
}
});
note: that your variables like (int count) and (long time) should be declared in the body of your class not into a method;
below code is a example code for recognizing double click on a view with Custom time;
boolean isPressed = false;
long delayed = 1000;
final Hanlder handler = new Handler();
Button b;
b.setOnClickListener(new View.onClickListener(){
public void onClick(View v){
if(isPressed == true){
// recognize double click;
}else{
Toast.makeText(getApplicationContext(),"tap again to exit",1).show();
isPressed = true;
handler.postDelayed(new Runnable(){
public void run(){
isPressed = false;
}
},delayed);
}
});
Try TouchListener:
Handler handel = new Handler();
b.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN:
handel.postDelayed(run, 5000);
break;
default:
handel.removeCallbacks(run);
break;
}
return true;
}
});
Later define run:
Runnable run = new Runnable() {
#Override
public void run() {
// Your code to run on long click
}
};
Set a listener for when the button is pressed and when the button is released. Create a timer that records after the button is pressed and stops when the button is released. There should be listeners for both if you are using JFrame or Android as your GUI.
I have a video view that is full screen and would like to trigger a popupMenu when a certain key is pressed. The log shows that the key event is captured, but the popup view will not show. Any ideas why?
#Override
public boolean onKeyDown(int keyCode , KeyEvent event ){
switch(keyCode){
case KeyEvent.KEYCODE_DPAD_CENTER:
Log.i("POP uP MENU","Show");
mVideoView.pause();
showPopupMenu(new View(VideoPlayer.this));
case KeyEvent.KEYCODE_D:
popupMenu.dismiss();
}
return true;
}
private void showPopupMenu(View v){
popupMenu = new PopupMenu(VideoPlayer.this, v);
if(bitRates != null){
for(int i=0;i<bitRates.size();i++){
int menuItem = i;
popupMenu.getMenu().add(0,menuItem, 0,qualityList.get(i)+" : "+bitRates.get(i));
}
}
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem item) {
progressDialog = ProgressDialog.show(VideoPlayer.this, "", "Loading video...");
final int position = mVideoView.getCurrentPosition();
new Thread() {
public void run() {
try{
runOnUiThread(new Runnable() {
public void run() {
play(streamUrls.get(item.getItemId()),position);
}
});
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
}
progressDialog.dismiss();
}
}.start();
return true;
}
});
}
It seems that
KeyEvent.KEYCODE_DPAD_CENTER
is an event that is set to be triggered by the VideoView by default. So when I pressed that key VideoView triggered its event event instead of the event I was requesting it to. I changed the KeyEvent KEYCODE to another key(One not used by Videoview) and it worked.
Hi I am working with android and I'm trying to put an "if" statement around this class but I get the error "Syntax error on token "if", invalid AnnotationName"
Any help?
private String str = "0";
if(str == 0){
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK)
{
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Coupon")
.setMessage("Do you want a coupon texted to you?")
.setPositiveButton("YES!", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Stop the activity
Toast.makeText(buttonOne.this, "Great! You'll get one in just a couple of minutes.", Toast.LENGTH_LONG).show();
finish();
}
})
.setNegativeButton("Not now", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Stop the activity
finish();
}
})
.show();
return true;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
}
else
{}
You can't put control structures (like if statements) outside a function.
you must use equals String method:
if (str.equals("0")){
...
}