【发布时间】:2010-09-21 16:24:31
【问题描述】:
我正在使用类似于下面的代码,但线程是通过按下按钮启动的。当我按下按钮时,会抓取 url 上的数据并将我切换到其他活动。我遇到的问题是,当我在其他活动中并点击后退按钮时,我得到一个异常,说线程已经启动。当活动加载检查 isAlive 时,我尝试杀死线程,但它似乎不会死。有谁碰巧知道我如何在创建的线程未运行的情况下将此活动恢复到其原始状态?
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
public class Iconic extends Activity {
private String html = "";
private Handler mHandler;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler = new Handler();
checkUpdate.start();
}
private Thread checkUpdate = new Thread() {
public void run() {
try {
URL updateURL = new URL("http://iconic.4feets.com/update");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
/* Convert the Bytes read to a String. */
html = new String(baf.toByteArray());
mHandler.post(showUpdate);
} catch (Exception e) {
}
}
};
private Runnable showUpdate = new Runnable(){
public void run(){
Intent newIntent = New Intent(Iconic.this, otherClass.class);
startActivity(newIntent);
}
};
}
【问题讨论】: