如果没有 Internet 连接弹出 Snackbar
Snackbar Pop Up If No Internet Connection
你好,我正在制作一个仅用于教育目的的应用程序。我已经在控制台开发者网站上启用了 Google 地图。
我的问题是,如果在 phone 中未启用 GPS / 未检测到 Internet 连接 - 检测到 Snackbar 将弹出,我该如何实施或更确切地说是做出条件声明? - 文本 "Some functionalities will be enable/used if connected to the Internet".
要检查设备是否通过手机或 wifi 连接,您可以使用此代码:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
//wifi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
然后像这样使用它:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//wifi
}
还要检查 GPS 状态:
public boolean isGPSEnabled (Context mContext){
LocationManager locationManager = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
为了检查网络连接,您可以在任何文件中创建一个 public 函数并在其他文件中调用它。
方法如下所示:
public static boolean isconnected () {
ConnectivityManager connMan=(ConnectivityManager) MyApplication.getInstance().getApplicationContext().getSystemServices(Context.CONNECTIVITY_SERVICE) ;
NetworkInfo = connMan.getActiveNetworkInfo();
return active != null && active.isConnectedOrConnecting();
}
这里的 MyApplication 是 activity 在清单文件的应用程序标签内声明的名称。
你好,我正在制作一个仅用于教育目的的应用程序。我已经在控制台开发者网站上启用了 Google 地图。
我的问题是,如果在 phone 中未启用 GPS / 未检测到 Internet 连接 - 检测到 Snackbar 将弹出,我该如何实施或更确切地说是做出条件声明? - 文本 "Some functionalities will be enable/used if connected to the Internet".
要检查设备是否通过手机或 wifi 连接,您可以使用此代码:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
//wifi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
然后像这样使用它:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//wifi
}
还要检查 GPS 状态:
public boolean isGPSEnabled (Context mContext){
LocationManager locationManager = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
为了检查网络连接,您可以在任何文件中创建一个 public 函数并在其他文件中调用它。
方法如下所示:
public static boolean isconnected () {
ConnectivityManager connMan=(ConnectivityManager) MyApplication.getInstance().getApplicationContext().getSystemServices(Context.CONNECTIVITY_SERVICE) ;
NetworkInfo = connMan.getActiveNetworkInfo();
return active != null && active.isConnectedOrConnecting();
}
这里的 MyApplication 是 activity 在清单文件的应用程序标签内声明的名称。