【发布时间】:2016-07-10 19:32:49
【问题描述】:
我想知道在 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();
}
}
我使用上面的代码在连接互联网后运行服务,但这只是一个示例
【问题讨论】:
标签: java android sockets server