NetWork On main thread Exception

后端 未结 2 953
慢半拍i
慢半拍i 2020-12-04 02:29

Hi, I try to check network connectivity and Internet present by using following method

check = new ConnectionDetector(getApplicationContext());

相关标签:
2条回答
  • 2020-12-04 03:10

    You can't make HTTP requests on the main thread, it would cause the UI to freeze up. So it throws that exception. You need to do it in an AsyncTask or another Thread.

    0 讨论(0)
  • 2020-12-04 03:15

    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. 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. 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.

    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. Can make multiple spice request. Notifies on the ui thread. https://github.com/octo-online/robospice

    To check Netowrk Connectivity.

    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

    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;
            }
    
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题