守则
public void run() {
try {
send();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void send() throws ClientProtocolException, IOException
{
OutputStream mOutputStream = null;
BufferedWriter mWriter = null;
List<NameValuePair> mParameters = req.getParameters();
URL url = null;
HttpURLConnection connection = null;
try {
Looper.prepare();
url = new URL(req.returnRequestUrl());
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TINEOUT);
connection.setRequestMethod(Params.HTTP_REQUEST_METHOD_POST);
connection.setDoOutput(true);
connection.setDoInput(true);
mOutputStream = connection.getOutputStream();
mWriter = new BufferedWriter(new OutputStreamWriter(mOutputStream, Params.UTF8));
String sparams = URLEncodedUtils.format(mParameters, Params.UTF8);
mWriter.write(sparams);
mWriter.flush();
mResponseCode = connection.getResponseCode();
if (mResponseCode > 203) {
mData = readWebData(connection.getErrorStream());
this.req.getResponse().notGoodServerEroorr();
} else {
mData = readWebData(connection.getInputStream());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) {
try {
if (mOutputStream != null)
mOutputStream.close();
if (mWriter != null)
mWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.disconnect();
evaluateDataAndRespondToFragment(mData);
myLooper = Looper.myLooper();
Looper.loop();
myLooper.quit();
}
}
}
private void evaluateDataAndRespondToFragment(String mData) {
Listen lis = this.req.getResponse();
if (mData.equals("1"))
lis.good();
else
lis.notGood();
}
答案 0 :(得分:0)
创建一个处理程序并从新线程调用它以更新视图
final Hanlder hanlder=new Handler(){
@Override
public void handleMessage(Message msg){
//update views here
}
}
//from the thread
new Thread(new Runnable{
@Override
public void run(){
//do your async task
//call hanlder
handler.obtainMessage().sendToTarget()
}
}).start();
请参阅此处以在runOnUiThread和handler之间进行选择。 https://stackoverflow.com/a/7452913/5819589
答案 1 :(得分:0)
此问题是由连接请求引起的。通常,这些类型的请求不适用于主线程。因此,创建一个新线程来运行此代码或使用runOnUiThread()
方法。这可以解决您的问题。
试试这个
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
send();
}
});
}
答案 2 :(得分:0)
如错误消息所述,只有主线程可以触及VAny类型的视图, 似乎
evaluateDataAndRespondToFragment(mData);
上面的方法触及Android不允许的主线程组件, 从Main Thread调用此方法就像这样 -
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
evaluateDataAndRespondToFragment(mData);
}
});