当活动是onPause时如何停止线程?

时间:2013-04-27 02:07:51

标签: java android multithreading

因此,有一个5秒的启动画面,但底部还有一个skip按钮。这就是飞溅的运行方式。

public class Splash extends Activity implements View.OnClickListener {

MediaPlayer splashsong;
Button skipsplash;

@Override
protected void onCreate(Bundle chiefsplash) {
    // TODO Auto-generated method stub
    super.onCreate(chiefsplash);
    setContentView(R.layout.splash);

    splashsong = MediaPlayer.create(Splash.this, R.raw.jingle);
    splashsong.start();
    skipsplash = (Button) findViewById(R.id.skipsplash);

    skipsplash.setOnClickListener(this);

    Thread splashtimer = new Thread() {
        public void run() {
            try {
                sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                switchactivity();
            }
        }
    };

    splashtimer.start();
}

@Override
public void onClick(View skipbutton) {
    switchactivity();
}

private void switchactivity() {
    Intent aftersplash = new Intent("com.example.testapp.MENU");
    startActivity(aftersplash);
}

@Override
protected void onPause() {

    super.onPause();
    splashsong.release();
    finish();
}

}

现在我希望有一个选择按skip按钮来中断5秒等待,我猜不是在线程运行时。那么点击skip按钮后会发生什么:从创建Activity开始经过5秒后,它会打开Menu Activity,无论我是已经在那里或其他地方。无论如何要阻止这个?

4 个答案:

答案 0 :(得分:1)

您是否尝试使用处理程序

          Handler h = new Handler();
          h.postDelayed(runnable, delayMillis);

在runnable的run方法中调用switchactivity()。 在onClick()中删除该runnable的所有回调

h.removeCallbacks(runnable);

答案 1 :(得分:0)

你可以将boolean isSplashRunning设置为true,在运行中将所有操作都放在While(isSplashRunning){}循环中以及何时停止线程集 isSplashRunning = false; splashtimer.join();

答案 2 :(得分:0)

不使用5秒的休眠间隔,而是在循环中使用小间隔,并使用标志组合随时随意跳过线程。请尝试以下修改后的代码。

public class Splash extends Activity implements View.OnClickListener {

MediaPlayer splashsong;
Button skipsplash;
boolean skipWait = false;

@Override
protected void onCreate(Bundle chiefsplash) {
// TODO Auto-generated method stub
super.onCreate(chiefsplash);
setContentView(R.layout.splash);

splashsong = MediaPlayer.create(Splash.this, R.raw.jingle);
splashsong.start();
skipsplash = (Button) findViewById(R.id.skipsplash);

skipsplash.setOnClickListener(this);

Thread splashtimer = new Thread() {
    int waitTime = 0;
    public void run() {
        while(waitTime < 5000 && !skipWait) {
            try {
                sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } 
            waitTime += 500;
        }
        switchactivity();
    }
};

splashtimer.start();
}

@Override
public void onClick(View skipbutton) {
    skipWait = true;
}

private void switchactivity() {
Intent aftersplash = new Intent("com.example.testapp.MENU");
startActivity(aftersplash);
}

@Override
protected void onPause() {

super.onPause();
splashsong.release();
finish();
}

答案 3 :(得分:-1)

使用:

splashtimer.stop();

并且您应该将线程设置为全局对象。