Reputation: 1673
It seems to be easy and should look like:
private long DOUBLE_CLICK_DELAY = 150;
private long lastButtonClick = // oldValue
private long currentButtonClick = System.currentTimeMillis();
...
if (currentButtonClick - lastButtonClick < DOUBLE_CLICK_DELAY ) // bla-bla
but I can't save the old value of previuous click in a BroadcastReceiver. Should I save it in a temporary database o something? (No activity used)
public class RemoteControlReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
if (/* DOUBLE_CLICK */){
Toast.makeText(context, "Tra-la-la!", 100).show();
}
}
}
}
Upvotes: 1
Views: 1863
Reputation: 304
Maybe the post is already a little bit old but today I was facing the same issue and I found a better (or at least more "elegant") solution instead of using the shared preferences.
Declare the global variables as static in your MainActivity:
static final long DOUBLE_CLICK_DELAY = 150;
static long lastButtonClick = 0; // oldValue
static long currentButtonClick = System.currentTimeMillis();
Now from your RemoteControlReceiver class do the following:
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
// Do something for action down
}
else if(action == KeyEvent.ACTION_UP){
MainActivity.lastPressTime = MainActivity.newPressTime;
MainActivity.newPressTime = System.currentTimeMillis();
long delta = MainActivity.newPressTime - MainActivity.lastPressTime;
// Case for double click
if(delta < MainActivity.DOUBLE_CLICK_DELAY){
// Do something for double click
}
}
}
Upvotes: 1
Reputation: 1673
Well, thanks to @gianpi it's working with SharedPreferences. But not sure about of good reading/writing speed in this case. Whatever, if anybodys's intrested:
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent keyEvent = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (keyEvent != null) {
if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
long last = settings.getLong("last", 0);
long delta = System.currentTimeMillis() - last;
if (delta < DOUBLE_CLICK_DELAY) {
context.startService(new Intent(context, MyService.class));
}
SharedPreferences.Editor editor = settings.edit();
editor.putLong("last", System.currentTimeMillis());
editor.commit();
}
}
}
}
Upvotes: 2