Capture event on Android after some seconds
android, android-4.0-ice-cream-sandwich
Solution
I've made something similar, but in my case I wanted to show a new activity if the button was pressed continuously for 3 seconds. Use this code for reference.
Runnable mRunnable,timeRunnable;
Handler mHandler=new Handler();
btnBackoffice = (Button) findViewById(R.id.btn_backoffice);
btnBackoffice.setOnTouchListener(buttonOnTouchListener);
private OnTouchListener buttonOnTouchListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch ( event.getAction() ) {
case MotionEvent.ACTION_DOWN:
mHandler.postDelayed(timeRunnable, 3000);
break;
case MotionEvent.ACTION_UP:
mHandler.removeCallbacks(timeRunnable);
break;
}
return true;
}
};
timeRunnable=new Runnable(){
@Override
public void run() {
Intent intent = new Intent(MainActivity.this, BackofficeActivity.class);
startActivity(intent);
}
};
Hope it helps.
Problem
I want to add a button to my app in Android and capture the event on this button (onclick) after a couple of seconds pushing the button, so it doesn't react at the first touch. Is this possible to achieve on Android? Right now I have the next code that captures an onclick on the home button (in the ActionBar). ``` public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { showSendLogAlert(); } return super.onOptionsItemSelected(item); } ``` When an user clicks on this button, it sends a little report by email, and I don't want to launch this event accidentally, that's why I want the user to push a couple of seconds in order to be sure he wants to do that operation. Solution: Based on the comments below I got this working solution: ``` @Override protected void onCreate(final Bundle savedInstanceState) { // stuff // Set the home button clickable getActionBar().setHomeButtonEnabled(true); // Define a long click listener instead of normal one View homeButton = findViewById(android.R.id.home); homeButton.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { showSendLogAlert(); return false; } }); // more stuff } ```