在同一個類上運行我的代碼時,應用程序運行良好。但是當我在兩個不同的類上運行此代碼時,我的應用程序出現錯誤android.os.networkonmainthreadexception。 當我調試我發現錯誤在responseHttp = httpConnection.getResponseCode(); 應用程序運行至行responseHttp = httpConnection.getResponseCode();它去抓{},它取消「If..else」。並記錄錯誤android.os.networkonmainthreadexception。 你能幫助我嗎!錯誤android.os.networkonmainthreadexception asynctask getResponseCode
我的代碼類的AsyncTask
package com.example.finishdemo;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
public class TestConnectionNew extends AsyncTask<String, Void, String> {
private int responseHttp = 0;
private String flag="false";
@Override
protected String doInBackground(String... urltest) {
// TODO Auto-generated method stub
try {
URL url = new URL(urltest[0]);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
**responseHttp = httpConnection.getResponseCode();**
if (responseHttp == HttpURLConnection.HTTP_OK) {
flag = "true";
} else {
flag = "false";
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Thong bao loi: "+e.toString());
}
return flag;
}
}
代碼類主:
package com.example.finishdemo;
public class Hoadon extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hoadon);
TestConnectionNew t=new TestConnectionNew();
String recieve=t.doInBackground("http://longvansolution.tk/monthlytarget.php");
if(recieve.equalsIgnoreCase("true"))
{
doTimerTask();
}else
if(recieve.equalsIgnoreCase("false"))
{
showAlert("Không kết nối được đến server hoặc thiết bị chưa có kết nối internet!");
}
我不覺得這是怎麼你需要調用一個AsyncTask。 –