简体   繁体   English

NetWork On主线程异常

[英]NetWork On main thread Exception

Hi, I try to check network connectivity and Internet present by using following method 嗨,我尝试使用以下方法检查网络连接和Internet存在

check = new ConnectionDetector(getApplicationContext()); check = new ConnectionDetector(getApplicationContext());

conn = check.isConnectingToInternet(); conn = check.isConnectingToInternet();

public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context){
    this._context = context;
}

/**
 * Checking for all possible internet providers
 * **/
/*public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
}*/

public boolean isConnectingToInternet(){
    try{
        ConnectivityManager cm = (ConnectivityManager)_context.getSystemService
                                                    (Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        Log.d("NetInfo", String.valueOf(netInfo));
        if (netInfo != null && netInfo.isConnected())
        {
            //Network is available but check if we can get access from the network.
            URL url = new URL("http://www.Google.com/");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(2000); // Timeout 2 seconds.
            urlc.connect();
            Log.d("NetInfo Response Code", String.valueOf(urlc.getResponseCode()));
           // Toast.makeText(getApplicationContext(), String.valueOf(urlc.getResponseCode()), Toast.LENGTH_LONG).show();
            if (urlc.getResponseCode() == 200)  //Successful response.
            {
                return true;
            } 
            else 
            {
                 Log.d("NO INTERNET", "NO INTERNET");
                return false;
            }
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return false;
}

} }

Note : 注意 :

But this will return NetworkOnMainThread Exception like follows.kindly any one suggest me what mistakes i made....... 但这将返回NetworkOnMainThread异常,如下所示。任何人都建议我犯了什么错误.......

03-27 12:53:35.617: W/System.err(1095): android.os.NetworkOnMainThreadException
03-27 12:53:35.627: W/System.err(1095):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
03-27 12:53:35.637: W/System.err(1095):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
03-27 12:53:35.637: W/System.err(1095):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
03-27 12:53:35.647: W/System.err(1095):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
03-27 12:53:35.647: W/System.err(1095):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
03-27 12:53:35.657: W/System.err(1095):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
03-27 12:53:35.668: W/System.err(1095):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
03-27 12:53:35.668: W/System.err(1095):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
03-27 12:53:35.677: W/System.err(1095):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
03-27 12:53:35.687: W/System.err(1095):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
03-27 12:53:35.699: W/System.err(1095):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
03-27 12:53:35.699: W/System.err(1095):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
03-27 12:53:35.707: W/System.err(1095):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
03-27 12:53:35.718: W/System.err(1095):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
03-27 12:53:35.727: W/System.err(1095):     at com.slet.routemytrips.beta.ConnectionDetector.isConnectingToInternet(ConnectionDetector.java:50)
03-27 12:53:35.727: W/System.err(1095):     at com.slet.routemytrips.beta.Disclaimer$1.onClick(Disclaimer.java:178)
03-27 12:53:35.738: W/System.err(1095):     at android.view.View.performClick(View.java:3480)
03-27 12:53:35.738: W/System.err(1095):     at android.view.View$PerformClick.run(View.java:13983)
03-27 12:53:35.748: W/System.err(1095):     at android.os.Handler.handleCallback(Handler.java:605)
03-27 12:53:35.757: W/System.err(1095):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-27 12:53:35.757: W/System.err(1095):     at android.os.Looper.loop(Looper.java:137)
03-27 12:53:35.767: W/System.err(1095):     at android.app.ActivityThread.main(ActivityThread.java:4340)
03-27 12:53:35.777: W/System.err(1095):     at java.lang.reflect.Method.invokeNative(Native Method)
03-27 12:53:35.777: W/System.err(1095):     at java.lang.reflect.Method.invoke(Method.java:511)
03-27 12:53:35.787: W/System.err(1095):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-27 12:53:35.797: W/System.err(1095):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-27 12:53:35.807: W/System.err(1095):     at dalvik.system.NativeStart.main(Native Method)
03-27 12:57:05.237: D/dalvikvm(90): GC_CONCURRENT freed 666K, 10% free 12624K/14023K, paused 6ms+10ms

You can't make HTTP requests on the main thread, it would cause the UI to freeze up. 您无法在主线程上发出HTTP请求,这会导致UI冻结。 So it throws that exception. 所以它引发了异常。 You need to do it in an AsyncTask or another Thread. 您需要在AsyncTask或其他Thread中执行此操作。

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

NetworkOnMainThreadException is thrown if you attempt to make a network request in the main UI Thread. 如果您尝试在主UI线程中发出网络请求,则抛出NetworkOnMainThreadException So all network related operation should be done on the background thread. 所以所有网络相关的操作都应该在后台线程上完成。

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTask旨在成为Thread和Handler的辅助类,并不构成通用的线程框架。 AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask. 理想情况下,AsyncTasks应该用于短操作(最多几秒钟。)如果需要保持线程长时间运行,强烈建议您使用java.util.concurrent pacakge提供的各种API,例如Executor,ThreadPoolExecutor和FutureTask。

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

class TheTask extends AsyncTask<Void,Void,Void>
{
          protected void onPreExecute()
          {           super.onPreExecute();
                    //display progressdialog.
          } 

           protected void doInBackground(Void ...params)
          {  
                //http request. do not update ui here

                return null;
          } 

           protected void onPostExecute(Void result)
          {     
                    super.onPostExecute(result);
                    //dismiss progressdialog.
                    //update ui
          } 

}

An alternative to asynctask is Robospice. asynctask的替代品是Robospice。 Can make multiple spice request. 可以制作多个香料请求。 Notifies on the ui thread. 通知ui线程。 https://github.com/octo-online/robospice https://github.com/octo-online/robospice

To check Netowrk Connectivity. 检查Netowrk连接。

In your activity 在你的活动中

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   if(CheckNetwork.isInternetAvailable(MainActivity.this))
   {
       //call asyntask and make http request.
   }
 }

CheckNetwork class CheckNetwork类

public class CheckNetwork {

private static final String TAG = CheckNetwork.class.getSimpleName();

public static boolean isInternetAvailable(Context context)
{
    NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
    context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if (info == null)
    {
         Log.d(TAG,"no internet connection");
         return false;
    }
    else
    {
        if(info.isConnected())
        {
            Log.d(TAG," internet connection available...");
            return true;
        }
        else
        {
            Log.d(TAG," internet connection");
            return true;
        }

    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM