停止线程的onPause [英] Stop Thread onPause

查看:284
本文介绍了停止线程的onPause的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,当用户离开活动停止线程。这听起来很简单,但没有作用,我试过,效果。

I want to stop a Thread when the User leaves the Activity. It sounds so simple but no function, which i tried, works.

我开始与code中的活动

I start the Activity with the Code

lovi = new Intent(getApplicationContext(), listoverview.class);
lovi.putExtra("reloadAll", true);
startActivity(lovi);

在listoverview的OnCreate我开始与code线程

In the onCreate of the listoverview i start the Thread with the Code

rlMF.start();

和rlMF看起来是这样的:

And rlMF looks like this:

public Thread rlMF = new Thread(new Runnable() {
    public void run() {
        reloadMissingFiles();
    }
});

我试过了的onPause使用rlMF.stop(),.interrupt(),.suspend。没有什么可以阻止它。

I tried in the onPause to use rlMF.stop(), .interrupt(), .suspend. Nothing stops it.

推荐答案

您必须添加一些标志,以阻止它。通过其他方法停止线程可能会产生严重的后果,如资源泄漏。

You have to add some flag to to stop it. Stopping thread by other means might have dire consequences, like resource leaks.

例如:

volatile boolean activityStopped = false;

在创建可运行:

public Thread rlMF = new Thread(new Runnable() { 

    public void run() {
        while (!activityStopped) {
        // reloadMissingFiles() should check the flag in reality
            reloadMissingFiles(); 
        }
    }
});

在的onPause():

In onPause():

protected void onPause(){
    super.onPause();
    activityStopped = true;
}

这篇关于停止线程的onPause的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆