我花了几个小时在这里寻找答案,但似乎没有任何东西让我清楚。
这是我的问题:我有一个带有主菜单的简单应用程序。其中一个选项从 PHP 服务器检索评论列表,更新数据库,然后显示 ListView。
内部一切正常。现在,每次我按回键然后再次启动 Activity 时,都会启动一个新线程。我设法获得了 50 多个等待线程。我正在使用 Eclipse 的 DDMS 选项卡来监视踏板。
如果我尝试调用 Looper.getLooper().quit()
或 Looper.myLooper().quit()
,我会收到一条错误消息“main thread not允许退出”。
我做错了什么以及我应该在哪里/如何停止线程?
代码如下:
public class RequestActivity extends Activity {
ProgressDialog pDialog;
DatabaseHelper db;
int userId;
myCursorAdapter adapter;
Thread runner = null;
ListView list;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userId = myApplication.getInstance().getSession().getUserId();
setContentView(R.layout.request_list);
db = new myProvider.DatabaseHelper(this);
Cursor cursor = db.getRequests(userId);
startManagingCursor(cursor);
adapter = new myCursorAdapter(RequestActivity.this, cursor);
list = (ListView) findViewById(R.id.list);
list.setVisibility(View.INVISIBLE);
list.setAdapter(adapter);
pDialog = ProgressDialog.show(RequestActivity.this, "", "Loading ...", true, false);
runner = new Thread() {
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
adapter.getCursor().requery();
}
};
public void run() {
Looper.prepare();
// ... setup HttpGet
try {
// ... get HTTP GET response
if (response != null) {
// ... update database
handler.sendEmptyMessage(0);
}
} catch(Exception e) {
// .. log exception
}
Looper.loop();
}
};
runner.start();
}
private static class ViewHolder {
// .. view objects
}
private class myCursorAdapter extends CursorAdapter {
private LayoutInflater inflater;
public myCursorAdapter(Context context, Cursor c) {
super(context, c);
inflater = LayoutInflater.from(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// .. bind data
if (cursor.isLast()) {
pDialog.dismiss();
list.setVisibility(View.VISIBLE);
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = inflater.inflate(R.layout.request_list_item, parent, false);
ViewHolder holder = new ViewHolder();
// .. set holder View objects
view.setTag(holder);
return view;
}
}
}
最佳答案
您正在主线程的 Looper 上调用 quit()。不是线程的 Looper。
你可以试试这个。创建一个单独的私有(private)内部类来扩展 Thread
。在 run() 方法中,调用 Looper.myLooper() 以将线程的 Looper 实例保存在类中。然后有一个在该循环器上调用 quit 的退出方法。
例子:
private class LooperThread extends Thread{
private Looper threadLooper;
@Override
public void run(){
Looper.prepare();
threadLooper = Looper.myLooper();
Looper.loop();
}
public void stopLooper(){
if(threadLooper != null)
threadLooper.quit();
}
}
关于android - 从 Activity.onCreate() 创建永不消亡的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7042390/