错误android.os.networkonmainthreadexception:asynctask getResponseCode

3
当我在同一个类中运行我的代码时,应用程序运行良好。但是当我在两个不同的类中运行此代码时,我的应用程序出现错误 android.os.networkonmainthreadexception。调试时,我发现错误在 responseHttp = httpConnection.getResponseCode(); 处。应用程序运行到 responseHttp = httpConnection.getResponseCode(); 这一行,然后进入 catch{},它取消了 "If..else"。并记录错误 android.os.networkonmainthreadexception。你能帮我吗!
我的代码类 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的正确方式。 - Andro Selva
2个回答

7

使用 asynctask.execute 来执行 AsyncTask,而不是手动调用 doInBackground 方法,如下所示:

 TestConnectionNew t = new TestConnectionNew();
 t.execute("http://longvansolution.tk/monthlytarget.php");

将您的TestConnectionNew更改为以下内容:

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;
}

@Override
     protected void onPostExecute(String recieve) {
           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的帮助,请参见:

http://developer.android.com/reference/android/os/AsyncTask.html


当我添加代码"String recieve=t.execute("http://longvansolution.tk/monthlytarget.php");"并收到此通知"Type mismatch: cannot convert from AsyncTask<String,Void,String> to String"时。 - Takeshi
@user1817079:请查看我的编辑答案,如果您需要更新UI,则需要覆盖onPostExecute方法。 - ρяσѕρєя K
如果您使用 String receive = t.execute("longvansolution.tk/monthlytarget.php").get();,那么这也会挂起UI线程,直到从AsyncTask返回控件为止。 - ρяσѕρєя K
谢谢...我使用了String recieve=t.execute("longvansolution.tk/monthlytarget.php").get();并且运行成功... - Takeshi
@user1817079:如果你想在后台发出请求而不等待,请不要使用get()。当我们使用execute.get()时,请参考此处:http://developer.android.com/reference/android/os/AsyncTask.html#get%28long,%20java.util.concurrent.TimeUnit%29 - ρяσѕρєя K
如果不使用get(),那么我应该使用函数吗? - Takeshi

0

在AndroidManifest.xml中添加代码:

uses-permission android:name="android.permission.INTERNET" 
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接