AsyncTask仍然给出networkOnMainThreadException

时间:2014-12-25 20:17:06

标签: android android-asynctask

public class WelcomeActivity extends Activity {

class Retrieve extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("some link");
    try{
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("username","someUser"));
        nameValuePairs.add(new BasicNameValuePair("password","somepass"));
        nameValuePairs.add(new BasicNameValuePair("method","checkLogin"));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        //Execute HTTP Post
        HttpResponse response = httpClient.execute(httpPost);
        //  Log.v("response", response.toString());
        Log.d("hi","hello");
        //  Log.d("response",response.toString());
    }catch(Exception e){
        Log.e("YOUR_APP_LOG_TAG","I got an error",e);
    }
    return null;
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    new Retrieve().execute();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.welcome, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
        return super.onOptionsItemSelected(item);
    }
}

类Retrieve用于将POST请求发送到服务器,但我不明白为什么它仍被视为在主线程而不是异步任务上执行。

我已经查看了之前有关异步使用的问题,但一直收到此错误:

   12-25 13:31:57.310    1782-1782/com.example.dalvir.quizapp E/YOUR_APP_LOG_TAG﹕ I got an error
android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
        at java.net.InetAddress.getAllByName(InetAddress.java:214)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
        at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
        at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
        at com.example.dalvir.quizapp.WelcomeActivity.onCreate(WelcomeActivity.java:44)
        at android.app.Activity.performCreate(Activity.java:5231)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
        at android.app.ActivityThread.access$800(ActivityThread.java:135)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

您可能会将SDK定位为等于或高于api级别11.请尝试将其更改为api级别8或低于11的其他api级别。您可以在此处找到解决方案:

Error while publishing photo on facebook wall using android facebook sdk

答案 1 :(得分:0)

如果您使用的是SDK版本&gt; = 3,

在调用AsyncTask之前在onCreate()方法中添加以下代码:

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()   
    .detectDiskReads()   
    .detectDiskWrites()   
    .detectNetwork() 
    .penaltyLog()   
    .build());

希望这有帮助:)