我想在每10秒后调用一个方法。我的方法有线程。应用程序崩溃与此代码。建议我任何解决方案
Timer myTimer = new Timer();
MyTimerTask myTimerTask = new MyTimerTask();
// to start
myTimer.scheduleAtFixedRate(myTimerTask, 8000, 15000); // (timertask,delay,period)
现在是MyTimerTask活动类。
private class MyTimerTask extends TimerTask {
@Override
public void run() {
CheckMsgs();
}
}
和Checkmethod包含
private void CheckMsgs() {
showProgressDialog();
new Thread(new Runnable() {
@Override
public void run() {
msgList = DManager.getConversation(SenderID, reciverID, Url_Settings.conversation_Url);
// Log.d("TAG", "msglist" + msgList.size());
mHandler.post(new Runnable() {
public void run() {
cancelDialog();
if (msgList != null) {
Collections.reverse(msgList);
adapter = new MsgsAdatper(ConversationActivity.this, msgList);
listview.setAdapter(adapter);
if (msgList.size() > 5) {
listview.setSelection(msgList.size() - 1);
}
cancelDialog();
} else {
Toast.makeText(getApplicationContext(), "No record is found", Toast.LENGTH_LONG).show();
}
}
});
}
}).start();
}
日志
06-21 18:15:03.993: E/AndroidRuntime(24733): FATAL EXCEPTION: Timer-0
06-21 18:15:03.993: E/AndroidRuntime(24733): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
06-21 18:15:03.993: E/AndroidRuntime(24733): at android.os.Handler.<init>(Handler.java:121)
06-21 18:15:03.993: E/AndroidRuntime(24733): at android.app.Dialog.<init>(Dialog.java:114)
06-21 18:15:03.993: E/AndroidRuntime(24733): at android.app.AlertDialog.<init>(AlertDialog.java:114)
06-21 18:15:03.993: E/AndroidRuntime(24733): at android.app.AlertDialog.<init>(AlertDialog.java:98)
06-21 18:15:03.993: E/AndroidRuntime(24733): at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
06-21 18:15:03.993: E/AndroidRuntime(24733): at com.eAlimTech.nikahapp.ConversationActivity.showProgressDialog(ConversationActivity.java:483)
06-21 18:15:03.993: E/AndroidRuntime(24733): at com.eAlimTech.nikahapp.ConversationActivity.CheckMsgs(ConversationActivity.java:248)
06-21 18:15:03.993: E/AndroidRuntime(24733): at com.eAlimTech.nikahapp.ConversationActivity.access$9(ConversationActivity.java:247)
06-21 18:15:03.993: E/AndroidRuntime(24733): at com.eAlimTech.nikahapp.ConversationActivity$MyTimerTask.run(ConversationActivity.java:641)
06-21 18:15:03.993: E/AndroidRuntime(24733): at java.util.Timer$TimerImpl.run(Timer.java:284)
答案 0 :(得分:0)
我认为你的变量mHandler
定义了线程里面没有Looper
。在UI线程中重新定义它将有助于您的情况。