Android处理程序handleMessage
有人能告诉我为什么在Android处理程序handleMessage,android,networking,Android,Networking,有人能告诉我为什么在handleMessage中出现主线程上的网络异常,因为您在主线程中创建了处理程序实例,并且正在处理它。在heandler中,您尝试在主线程中创建套接字连接(internet连接) /** * Default constructor associates this handler with the {@link Looper} for the * current thread. * * If this thread does not
handleMessage
中出现主线程上的网络异常,因为您在主线程中创建了处理程序实例,并且正在处理它。在heandler中,您尝试在主线程中创建套接字连接(internet连接)
/**
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*/
public Handler() ;
我猜您遇到异常是因为
Toast.makeText(getApplicationContext(),count,Toast.LENGTH_LONG).show()代码>
尝试使用新线程:
runOnUiThread(new Runnable() {
@Override
public void run() {
showToast(MessageBuilder.SUCCESSFUL_COMMENT);
}
});
您需要在后台运行处理程序。您可以为此使用活套
。
参考
你可以试试这个:
Thread thread = new Thread() {
@Override
public void run() {
super.run();
Looper.prepare();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
try {
String tmp = msg.obj.toString();
InetAddress serverAddr = InetAddress.getByName(serverIP);
socket = new Socket(serverAddr, serverPort);
OutputStream outStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outStream);
writer.write(tmp);
writer.flush();
InputStream inStream = socket.getInputStream();
byte[] xxx = new byte[20];
int count = inStream.read(xxx);
// Toast.makeText(getApplicationContext(), count, Toast.LENGTH_LONG).show();
outStream.flush();
outStream.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
Looper.myLooper().quit();
}
}
};
handler.removeCallbacks(this);
Looper.loop();
}
};
thread.start();
此外,您正在处理程序中显示一个Toast
,这将导致运行时错误。请从处理程序中删除Toast。尝试使用AsyncTasks,这更简单、更干净。可能是这样,但问题是如果我在doInbackground
中使用onPictureTaken
中的onPictureTaken
时遇到了与onPictureTaken
相同的错误。您可以共享logcat日志吗?请阅读并重试。如果没有这些信息,很难判断错误来自何处。好吧,它应该是什么样子?你能根据我的代码给我看一下吗?我试图在我的WIN上解决这个问题,但我总是有“主线程上的网络异常”引起的Inputstream@SimpleCoder我已经更新了答案,请检查。我已经根据您的示例更新了代码,问题是我没有得到任何错误(logcat没有显示任何内容)但当我按下按钮时,图片已生成但未发送,但当我关闭应用程序时,图片已发送。。。。这很奇怪吗?在按下按钮后,会生成并发送带有注释的InputStream
部分图片,但我需要从服务器接收响应,所以我需要InputStream