ここに簡単なバージョンがあります:
/*@return boolean return true if the application can access the internet*/
public static boolean haveInternet(Context context){
NetworkInfo info = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info==null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to disable internet while roaming, just return false
return true;
}
return true;
}
ここにwifiの設定があり、wifiのみを使用するように設定された設定によって一部のアクションを制限するかどうかを指定できます。たとえば、withRoamingPref=false;を使用して少量のダウンロードを確認できます。すべてのインターネット接続に対してtrueを返します。次に、withRoamingPref = trueを使用して大規模なダウンロードを確認します。この場合、ユーザーが「wifiのみ」を有効にしてダウンロードしたかどうかを確認し、wifiを使用している場合はtrueを返し、ユーザーがモバイル接続でダウンロードを許可した場合はtrueを返し、falseを返します。インターネット接続がない場合、またはモバイル接続を使用していて、ユーザーが重いファイルをダウンロードするためにモバイル接続を無効にしている場合。
public static boolean haveInternet(Context context, boolean withRoamingPref){
NetworkInfo info = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info==null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to disable internet while roaming, just return false
if(withRoamingPref) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
boolean onlyWifi = settings.getBoolean("onlyWifi", false);
if (onlyWifi) {
return false;
}else{
return true;
}
}else{
return true;
}
}
return true;
}
3つの状態すべてを返し、アプリケーションの別の部分でどのように動作するかを決定するようにケースを変更しました。
/*@return int return 0 if the application can't access the internet
return 1 if on mobile data or 2 if using wifi connection*/
public static int haveInternet(Context context){
NetworkInfo info = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info==null || !info.isConnected()) {
return 0;
}
if (info.isRoaming()) {
return 1;
}else{
return 2;
}
}
PS:数値の代わりに、静的intを各状態に割り当ててから、rawintの代わりにそれを返す必要があります。たとえば、クラスの開始時に次のように宣言します。
public static int INTERNET_DISABLED = 0;
次に、「return0;」の代わりに 「returnINTERNET_DISABLED;」を使用します。
このようにして、各番号の意味を覚えておく必要はありません。アプリの他のセグメントを次のように名前と照合します。
if(myClass.haveInternet == myClass.INTERNET_DISABLED){
//TODO show no internet message
}