私は私の要件に合うように彼の答えを適応Rohan :)
の助けを借りて解決策を働きました。
ユーザーがボタンを押すと、スレッドが開始されます。スレッドは私の希望する遅延のためにスリープ状態になり、スリープ状態になると、必要なコードを実行します。ユーザーが離れると、スレッドは強制終了されます。これは、ユーザーがスレッドを起動する前にスレッドを中断し、アクションが発生しないため、必要な処理を実行します。
私はこの方法が好きです。なぜなら、遅れているとすぐにビジネスロジックを実行できるからです。これは、ユーザーに十分な時間をプッシュしたことを知らせるいくつかのフィードバックを与えることができるためです(電話は、例えば)。
このアプローチの欠点は、必要なアクションが実行されている間にユーザーがボタンを離し、すべてが完了する前にスレッドを強制終了するというリスクがあることです。私のビジネスロジックはほとんど役に立たないので、これは私の場合には大きな問題ではありません。他のクラスのイベントを処理するだけです。アクションが完全に完了しなかった場合は、ユーザーが再試行する必要はありません。
コードは少し時間がかかりますが、これがアプリケーションの共通機能であれば、簡単に再利用できます。ここでは、コードの例です:
protected class MyLongClickListener implements View.OnTouchListener {
private Thread longClickSensor;
public boolean onTouch(View view, MotionEvent event) {
// If the user is pressing down and there is no thread, make one and start it
if (event.getAction() == MotionEvent.ACTION_DOWN && longClickSensor == null) {
longClickSensor = new Thread(new MyDelayedAction());
longClickSensor.start();
}
// If the user has let go and there was a thread, stop it and forget about the thread
if (event.getAction() == MotionEvent.ACTION_UP && longClickSensor != null) {
longClickSensor.interrupt();
longClickSensor = null;
}
return false;
}
private class MyDelayedAction implements Runnable {
private final long delayMs = 1200;
public void run() {
try {
Thread.sleep(delayMs); // Sleep for a while
doBusinessLogic(); // If the thread is still around after the sleep, do the work
} catch (InterruptedException e) { return; }
}
private void doBusinessLogic() {
// Make sure this logic is as quick as possible, or delegate it to some other class
// through Broadcasted Intents, because if the user lets go while the work is happenening,
// the thread will be interrupted.
}
}
}
これはほとんど私がそれを行うのに必要なことです。投稿されたアプローチは、ユーザーが指を離したときにのみコードを実行します。私は、ビジネスロジックを、ユーザーが押さなくても、遅延が上がるとすぐに実行したいと思います。 – ampersandre
then then = getSystemTime()はコメントアウトされていますか? getSystemTime()メソッドも機能しません。あなたは: System.currentTimeMillis() –
を確認しましたか?次に、intではなくlongとして定義します。次に、を使用します:then =(Long)System.currentTimeMillis();その差を見つけるときに、getSystemTime()の代わりにSystem.currentTimeMillis()を使用すると、もう一度長くキャストするようにしてください。 –