facebook twitter hatena line email

「Android/wifi判定」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
行2: 行2:
 
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 
TestActivity.java
 
TestActivity.java
  Context context = getApplicationContext();
+
  NetworkUtil.checkNetwork(getApplicationContext());
ConnectivityManager connMgr = (ConnectivityManager)
+
 
context.getSystemService(Context.CONNECTIVITY_SERVICE);
+
NetworkUtil.java
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
+
<pre>
if (networkInfo != null && networkInfo.isConnected()) {
+
import android.content.Context;
    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
+
import android.net.ConnectivityManager;
        Log.i("tag", "wifi");
+
import android.net.NetworkInfo;
    } else {
+
import android.util.Log;
        Log.i("tag", "mobile");
+
public class NetworkUtil {
    }
+
    public static void checkNetwork(Context context) {
} else {
+
        ConnectivityManager connMgr = (ConnectivityManager)
    Log.i("tag", "not connected");
+
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
+
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
 +
        if (networkInfo != null && networkInfo.isConnected()) {
 +
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
 +
                Log.i("tag", "wifi");
 +
            } else {
 +
                Log.i("tag", "mobile");
 +
            }
 +
        } else {
 +
            Log.i("tag", "not connected");
 +
        }
 +
    }
 +
}
 +
</pre>

2018年8月23日 (木) 15:54時点における版

AndroidManifest.xml

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

TestActivity.java

NetworkUtil.checkNetwork(getApplicationContext());

NetworkUtil.java

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class NetworkUtil {
    public static void checkNetwork(Context context) {
        ConnectivityManager connMgr = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                Log.i("tag", "wifi");
            } else {
                Log.i("tag", "mobile");
            }
        } else {
            Log.i("tag", "not connected");
        }
    }
}