「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 | ||
− | + | NetworkUtil.checkNetwork(getApplicationContext()); | |
− | + | ||
− | + | NetworkUtil.java | |
− | + | <pre> | |
− | + | 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"); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </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"); } } }