2016-02-26 32 views
1
public class MainActivity extends AppCompatActivity { 
    Context context; 

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

    } 

    public void show(View v){ 
     if (hasActiveInternetConnection(context)){ 
      Toast.makeText(MainActivity.this, "Internet connection available", Toast.LENGTH_SHORT).show(); 
     }else{ 
      Toast.makeText(MainActivity.this, "Internet connection not available", Toast.LENGTH_SHORT).show(); 
     } 
    } 

    public boolean hasActiveInternetConnection(Context context) { 
     if (isNetworkAvailable(context)) { 

      new URLConnectTask().execute(); 


     } else { 
      // Log.d(LOG_TAG, "No network available!"); 
      Toast.makeText(MainActivity.this, "No network available!", Toast.LENGTH_SHORT).show(); 
     } 
     return false; 
    } 

    private class URLConnectTask extends AsyncTask<String, Void, String> { 
     @Override 
     protected String doInBackground(String... urls) { 

      // params comes from the execute() call: params[0] is the url. 
      try { 
       HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); 
       urlc.setRequestProperty("User-Agent", "Test"); 
       urlc.setRequestProperty("Connection", "close"); 
       urlc.setConnectTimeout(1500); 
       urlc.connect(); 
       String code = String.valueOf(urlc.getResponseCode() == 200); 
       return code; 
      } catch (IOException e) { 
       //Log.e(LOG_TAG, "Error checking internet connection", e); 
       //Toast.makeText(MainActivity.this, "Error checking internet connection", Toast.LENGTH_SHORT).show(); 
       return "Error checking internet connection"; 
      } 
     } 
    } 

    private boolean isNetworkAvailable(Context context) { 
     ConnectivityManager connectivityManager 
       = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
     return activeNetworkInfo != null; 
    } 
} 

我用這個post進行互聯網連接檢查。但因爲他們不使用asynctask,所以如果我使用這個代碼,我得到NetworkOnMainThreadException。我嘗試使用asynctask,但現在我只收到消息「Internet連接不可用」。我認爲它是因爲asynctask沒有返回布爾值true。所以任何幫助將不勝感激。按鈕點擊檢查互聯網連接

+1

你必須添加<>,裏面你如果條件(剛過新URLConnectTask()執行();行)。否則,默認情況下,它會根據您的代碼返回false – kishorepatel

+0

絕妙的答案。謝謝。那是我正在尋找的東西。 @kishorepatel – Sammy

回答

-1

請檢查u有清單文件,該代碼

<uses-permission android:name="android.permission.INTERNET" /> 

嘗試這個

ConnectivityManager cm = (ConnectivityManager) 
     activity.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 
    // if no network is available networkInfo will be null 
    // otherwise check if we are connected 
    if (networkInfo != null && networkInfo.isConnected()) { 
     return true; 
    } 
    return false; 
+0

添加了Internet和訪問網絡狀態權限。 – Sammy

0

試試這個代碼

public class MainActivity extends AppCompatActivity { 
Context context; 

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

} 
} 
public void show(View v){ 
    if (isConnectingToInternet(context)){ 
    Toast.makeText(MainActivity.this, "Internet connection available", Toast.LENGTH_SHORT).show(); 
    new URLConnectTask().execute(); 
}else{ 
    Toast.makeText(MainActivity.this, "Internet connection not available", Toast.LENGTH_SHORT).show(); 
} 
} 

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

private class URLConnectTask extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(String... urls) { 

     // params comes from the execute() call: params[0] is the url. 
     try { 
      HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); 
      urlc.setRequestProperty("User-Agent", "Test"); 
      urlc.setRequestProperty("Connection", "close"); 
      urlc.setConnectTimeout(1500); 
      urlc.connect(); 
      String code = String.valueOf(urlc.getResponseCode() == 200); 
      return code; 
     } catch (IOException e) { 
      //Log.e(LOG_TAG, "Error checking internet connection", e); 
      //Toast.makeText(MainActivity.this, "Error checking internet connection", Toast.LENGTH_SHORT).show(); 
      return "Error checking internet connection"; 
     } 
    } 
    } 
} 
+0

我使用HttpURLConnection來檢查WiFi是否具有活動的Internet連接。這段代碼會做同樣的事嗎? @Amit – Sammy

+0

@sam嘗試我的改進代碼 –

+0

我在上下文中出錯。我不明白你是如何使用兩個上下文(上下文和_context)@Amit – Sammy

0

使用波紋管的方法來檢查網上

/***************** *檢查isOnline ******************/

public static boolean isOnline(Context context) { 
     boolean result = false; 
     if (context != null) { 
      final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
      if (cm != null) { 
       final NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 
       if (networkInfo != null) { 
        result = networkInfo.isConnected(); 
       } 
      } 
     } 
     return result; 
    } 

確保您清單包含此權限

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
0

你可以使用這個類:

import android.content.Context; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 

public class ConnectionDetector { 
private Context _context; 

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

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

}

0

如果你想

ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo(); 
      if (activeNetwork != null) { // connected to the internet 
       if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { 
        // connected to wifi 
        Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show(); 
       } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { 
        // connected to the mobile provider's data plan 
        Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show(); 
       } 
      } else { 
       // not connected to the internet 
      } 
0

我寫了檢查所有可能的網絡Wi-Fi或移動數據的自定義類個人網絡類型嘗試此一次,

Boolean isInternetPresent = false; 
isInternetPresent = findconn.isConnectingToInternet(); 
    if (isInternetPresent) { 
      new URLConnectTask().execute(); 
     } else { 
      // Log.d(LOG_TAG, "No network available!"); 
      Toast.makeText(MainActivity.this, "No network available!", Toast.LENGTH_SHORT).show(); 
     } 

    public boolean isConnectingToInternet(){ 
      ConnectivityManager connectivity = (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE); 

      NetworkInfo info=connectivity.getActiveNetworkInfo(); 
      if (info == null) { 
       return false; 
      } 
      else { 
       return info.isConnectedOrConnecting(); 
      } 
    } 

(或)。試試這個:

public class NetworkManager { 

    /** 
    * Checking for all possible internet providers 
    * **/ 
    public static boolean isConnectingToInternet(Activity activity){ 

     ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
      Network[] networks = connectivityManager.getAllNetworks(); 
      NetworkInfo networkInfo; 
      for (Network mNetwork : networks) { 
       networkInfo = connectivityManager.getNetworkInfo(mNetwork); 
       if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) { 
        return true; 
       } 
      } 
     }else { 
      if (connectivityManager != null) { 
       //noinspection deprecation 
       NetworkInfo[] info = connectivityManager.getAllNetworkInfo(); 
       if (info != null) { 
        for (NetworkInfo anInfo : info) { 
         if (anInfo.getState() == NetworkInfo.State.CONNECTED) { 
//       LOGD(TAG, "NETWORKNAME: " + anInfo.getTypeName()); 
          return true; 
         } 
        } 
       } 
      } 
     } 
     showInternetSettingsAlert(activity); 
     return false; 
    } 


    /** 
    * Display a dialog that user has no internet connection lauch Settings 
    * Options 
    * */ 
    public static void showInternetSettingsAlert(final Activity activity) { 

     activity.runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 

       AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity, R.style.AppCompatAlertDialogStyle); 

       // Setting Dialog Title 
       alertDialog.setTitle("Internet Settings"); 

       alertDialog.setCancelable(false); 

       // Setting Dialog Message 
       alertDialog 
         .setMessage("Internet is not enabled. Do you want to go to settings menu?"); 

       // On pressing Settings button 
       alertDialog.setPositiveButton("Settings", 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int which) { 

           if(activity instanceof BaseFragmentActivity) 
            ((BaseFragmentActivity)activity).hideLoader(); 
           else if(activity instanceof BaseActivity) 
            ((BaseActivity)activity).hideLoader(); 
//      take user to turn Wifi screen 
//      activity.startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK)); 

//      take user to turn on mobile data screen 
           activity.startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS)); 


          } 
         }); 

       // on pressing cancel button 
       alertDialog.setNegativeButton("Cancel", 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int which) { 
           System.exit(0); 
           dialog.cancel(); 
          } 
         }); 
       // Showing Alert Message 
       alertDialog.show(); 
      } 
     }); 


    } 

} 

如果網絡不可用,它將重定向用戶打開網絡。

3

這項工作很好,你可以使用此代碼

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

//add to permission <uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />