-1

如果我按下返回按钮,我希望我thread/timer停止并退出应用程序。如何告诉它 timer.stop();内部的计时器onBackPressed()与我使用的局部变量相同public void run()

代码:

Thread timer = new Thread(){
        public void run(){
                try{
                    sleep(4400);
                } catch (InterruptedException e){
                    e.printStackTrace();
                }finally{ 
                    Intent openHome = new Intent(Splash.this, main.class);
                    startActivity(openHome);
                    finish();
                }
            }
        };
    timer.start();
    }
        public void onBackPressed(){
            timer.stop();
        }

当我输入这个时,它说'timer' in timer.stop(); cannot be resolved.

4

1 回答 1

2

Thread.stop()已弃用,您不应使用它。更好的Splashscreen实现是使用Handler-Runnable类似下面的东西。

private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
  public void run(){
    Intent openHome = new Intent(Splash.this, main.class);
    startActivity(openHome);
    finish();
  }
}

public void onCreate(Bundle b) {
  super.onCreate(b);
  handler.postDelayed(runnable, 4400);
}

public void onBackPressed(){
  handler.removeCallbacks(runnable);
  super.onBackPressed();
}
于 2013-09-11T20:00:18.073 回答