gpt4 book ai didi

java - 线程因未捕获的异常而退出

转载 作者:太空狗 更新时间:2023-10-29 15:49:20 25 4
gpt4 key购买 nike

嗨!

我的代码:

Thread thread = new Thread (){
@Override
public void run() {
while (true)
{
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {

if (msg.obj.toString()!= null)
{
JSONParse json = null;
try {
Log.e("Channel_State",msg.obj.toString());
json = new JSONParse(msg.obj.toString());
String state = json.getChannelState();
id = state;
TextView tv2 = (TextView)findViewById(R.id.mainscreen_state);
tv2.setText("Channel State: "+ state);
Log.e("State",state);
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast toast ;
toast = Toast.makeText(getApplicationContext(), "Error" + e.getMessage(), 500);
Log.e("Error",e.getMessage());
toast.show();
}
});
}

}
else
{

runOnUiThread(new Runnable() {
public void run() {
Toast toast ;
toast = Toast.makeText(getApplicationContext(), "error", 500);

toast.show();
}
});
}
}
};

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("session_id", settings.getString("session_id","error")));
params.add(new BasicNameValuePair("channel_id",String.valueOf(settings.getInt("channel_id", -1))));
HttpConnection con = new HttpConnection(params, "http://surfkid.redio.de/getChannelImage", handler);
con.start();
try {
Log.e("Sleep","Begin");
this.sleep(5000);
Log.e("Sleep","End");

} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("Sleep","Fail");
}

}
}
};
thread.start();

日志:

02-10 00:01:29.044: ERROR/AndroidRuntime(1248): Uncaught handler: thread Thread-13 exiting due to uncaught exception
02-10 00:01:29.054: ERROR/AndroidRuntime(1248): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
02-10 00:01:29.054: ERROR/AndroidRuntime(1248): at android.os.Handler.<init>(Handler.java:121)
02-10 00:01:29.054: ERROR/AndroidRuntime(1248): at android.skiptvad.MainScreen$6$1.<init>(MainScreen.java:258)
02-10 00:01:29.054: ERROR/AndroidRuntime(1248): at android.skiptvad.MainScreen$6.run(MainScreen.java:258)

请帮忙!

最佳答案

似乎您想要做的是创建一个 HandlerThread

HandlerThread myThread = new HandlerThread();
myThread.start();
Handler myHandler = new Handler(myThread.getLooper()){
//your handler code.
}

这应该会为您提供一个由您的处理程序按照您正在寻找的方式处理的线程。

关于java - 线程因未捕获的异常而退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4951994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com