停止线程下载图像时活动结束 [英] Stop a thread downloading images when activity finishes

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

问题描述

在我的应用程序,活动开始从服务器上下载图像的线程。有超过30个图像。在下载时,用户可以切换到另一个活动。所以,我想,该线程应该停止这样做不管它在做什么。我已经使用mThread.interrupt中的onDestroy()()的方法,但它并没有奏效。那怎么办?

In my app, the activity starts a thread which download images from server. There are more than 30 images. While downloading, the user can switch to another activity. So I want that the thread should stop doing whatever it is doing. I have used mThread.interrupt() method in onDestroy(), but it did not worked. How to do that?

推荐答案

我可以建议简单和放大器;更安全的方法来处理这​​个问题。

I can suggest simpler&safer approach to handle this

使用在您的应用程序共同价值;
共享preferences或内部应用程序上下文
重点= IsStopDownload
值=真/假

Use common value across your app; SharedPreferences or inside Application context Key=IsStopDownload Value= True / False

PART.1)
在应用程序上下文(所有MyApplication)

part.1) in Application context (MyApplication)

private boolean isAppActive = false;
public void setAppState(Context context, boolean state) {
    isAppActive = state;
    // note: you can also store this in SharedPreferences
}
public boolean getAppState(Context context) {
    return isAppActive;
    // note: you can also load this from SharedPreferences
}

PART.2)
活动onResume和的onPause有保证的地方,以确定您的活动状态。

part.2) Activity onResume and onPause are the guaranteed places to identify state of your activity.

onResume - >活动活跃
在onPause - >活动不活跃

onResume -> activity is active onPause -> activity is not active

PART.3)
让你的线程检查活动状态,如果不活动,可自行停止,这就是安全进而实现外部中断。从外部中断线程的时候可以充当怪异,它是安全从内部打破循环。

part.3) let your thread check the activity state and if not active, it can stop itself, thats safer then making external interrupt. threads can act weird when interrupted from outside, it is safer to break the loop from inside.

例如

((MyApplication)context.getApplicationContext()).getAppState(context);

如果多数民众赞成假,线程停止本身

if thats false, thread stops itself

希望这有助于...

---

社会编码 @AspiroTV

---
Social Coding @AspiroTV

这篇关于停止线程下载图像时活动结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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