我想知道在 Android 上,一旦用户单击 wifi 断开连接按钮以在设备与互联网断开连接之前运行方法,是否可以获得广播,我已经使用广播接收器来捕获网络更改,但它是在互联网断开连接后执行的,我使用下面的代码:
public class InternetReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
if (isNetworkAvailable(context) && !isMyServiceRunning(MessagingService.class,context)){
Intent i = new Intent(context,MessagingService.class);
context.startService(i);
Log.e("service started ","true");
}
}
private boolean isMyServiceRunning(Class<?> serviceClass, Context c) {
ActivityManager manager = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public boolean isNetworkAvailable(Context c) {
ConnectivityManager connectivityManager
= (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
我使用上面的代码在连接互联网后运行服务,但这只是一个示例
最佳答案
编辑:我假设您想要对用户点击 wifi 断开按钮使用react
您可以使用 Android 的 WifiManager
检查 wifi 连接的状态,它提供了一些获取有关您的 wifi 环境和连接信息的可能性。
Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.
来源:http://developer.android.com/reference/android/net/wifi/WifiManager.html
看看下面的内容。我想这对你会有帮助。
WIFI_STATE_CHANGED_ACTION Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown.
int WIFI_STATE_DISABLED Wi-Fi is disabled.
int WIFI_STATE_DISABLING Wi-Fi is currently being disabled.
关于java - 互联网断开之前的广播接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36179365/