【问题标题】:Stop my timer when the screen touch happen当屏幕触摸发生时停止我的计时器
【发布时间】:2026-02-21 01:00:01
【问题描述】:

如果触摸屏的动作被执行,我想停止计时器,因为现在当我触摸屏时,计时器仍在运行并且没有让他停止的功能。 你能帮帮我吗


public class SplashActivity extends Activity {
RelativeLayout splash;
    Handler handler;
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        startActivity(new Intent(getApplicationContext(),LoginActivity.class));
        finish();
        return super.dispatchTouchEvent(ev);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashfile);

                    handler=new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            startActivity(new Intent(getApplicationContext(),LoginActivity.class));
                            finish();
                        }
                    },10000);

       /*splash=findViewById(R.id.splash);
              splash.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                startActivity(new Intent(getApplicationContext(),LoginActivity.class));
                finish();
                return true;
            }
        });*/
            }
            
}

【问题讨论】:

  • 用这个 handler.removeCallbacksAndMessages(null); 停止处理程序在意图之前在 dispatchTouchEvent 中尝试一下。

标签: java android android-handler


【解决方案1】:

您可以使用removeCallbacksAndMessages(null) 删除Handler 上的所有回调

splash=findViewById(R.id.splash);
splash.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        handler.removeCallbacksAndMessages(null); // this will remove your callback
        startActivity(new Intent(getApplicationContext(),LoginActivity.class));
        finish();
        return true;
    }
});

【讨论】:

    最近更新 更多