Android应用适用于3g但不适用于Wi-Fi

时间:2014-02-20 16:10:10

标签: android wifi 3g networkonmainthread

我有一个活动(MainActivity)应该对服务器进行版本检查并允许用户登录帐户。问题是这两个函数都使用网络连接(显而易见),它们使用3g连接,但我尝试使用wifi连接,应用程序抛出NetworkOnMainThread异常。更奇怪的是(至少对我来说)这个问题只发生在这个活动中,所有其他活动都可以访问3g和wifi,它们使用与MainActivity相同的类。怎么会这样?

MainActivity:

public class MainActivity extends Activity implements OnTaskCompleted{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        try {
            version=Float.parseFloat(getApplicationContext().getPackageManager().
                    getPackageInfo(getApplicationContext().getPackageName(), 0).versionName);
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if(!isOnline()){
            //prevent user to go further
        }else{      
            String url="/*mydomain*//version_check.php";
            PostRequest post=new PostRequest(url,null,MainActivity.this,"version");
            post.execute(url);
        }

        //LOGIN CODE
    }

    @Override
    public void onTaskCompleted(Object return_value, String type) {
        if(type.equals("version")){
            float latest=Float.parseFloat((String)return_value);
            if(version<latest){
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);                
                 alertDialogBuilder.setMessage("update app!!!");
                    alertDialogBuilder.setNegativeButton("not now",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            // current activity
                            finish();
                        }
                      });
                    alertDialogBuilder.setPositiveButton("update now!",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                // if this button is clicked, close
                                // current activity
                                //go to playstore
                            }
                          });

                        // create alert dialog
                        alertDialog = alertDialogBuilder.create();
                        alertDialog.show();
            }
        }
        if(type.equals("login")){
            //login response handling


    }

    public boolean isOnline(){
        ConnectivityManager cm=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo=cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()){
            return true;
        }
        return false;
    }

}

PostRequest代码: 公共类PostRequest扩展了AsyncTask {

private HttpClient client;
private HttpPost request;
public String result, type;
private OnTaskCompleted listener;
public HttpResponse response;

public PostRequest(String url, List<NameValuePair> nameValuePairs, OnTaskCompleted listener, String type){
    this.client=new DefaultHttpClient();
    this.request = new HttpPost(url);
    this.listener=listener;
    this.type=type;



    try {
        if(nameValuePairs!=null)
            request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }


@Override
protected HttpResponse doInBackground(String... params) {

    try {

        response = client.execute(request);
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){

        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return response;
}

@Override
protected void onPostExecute(HttpResponse result) {
            //if the response doesn't contain a json
    if(type.equals("mod_database")||type.equals("version")||type.equals("push")){
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        out = new ByteArrayOutputStream();
        try {
            response.getEntity().writeTo(out);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(listener!=null)
            listener.onTaskCompleted(out.toString(),type);
        return;
    }
        //the response contain a json
    ReadJson jsonR=new ReadJson(type);
    Object obj=jsonR.read(response);
    listener.onTaskCompleted(obj, type);    
}

}

堆栈跟踪:

02-20 17:15:57.305: E/AndroidRuntime(13460): FATAL EXCEPTION: main
02-20 17:15:57.305: E/AndroidRuntime(13460): android.os.NetworkOnMainThreadException
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:220)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:183)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:155)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:175)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.entity.BasicHttpEntity.writeTo(BasicHttpEntity.java:129)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.entity.HttpEntityWrapper.writeTo(HttpEntityWrapper.java:101)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.conn.BasicManagedEntity.writeTo(BasicManagedEntity.java:126)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at it.stepapp.clienti.PostRequest.onPostExecute(PostRequest.java:78)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at it.stepapp.clienti.PostRequest.onPostExecute(PostRequest.java:1)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.AsyncTask.finish(AsyncTask.java:631)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.Looper.loop(Looper.java:137)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.app.ActivityThread.main(ActivityThread.java:4856)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at java.lang.reflect.Method.invokeNative(Native Method)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at java.lang.reflect.Method.invoke(Method.java:511)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:2)

FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException

at it.stepapp.clienti.PostRequest.onPostExecute(PostRequest.java:78)
at it.stepapp.clienti.PostRequest.onPostExecute(PostRequest.java:1)

不要在onPostExecute()中执行网络操作,因为它在主线程中运行。

无论你在PostRequest.java第78行做什么(你可以识别,我们做不到)最终是网络操作。您需要在doInBackground()方法中执行此操作。