我发现了很多关于如何检查互联网访问的主题。但我无法理解如何动态制作它。例如,我发送一个请求(它将在另一个线程中工作),并且设备丢失了Internet连接。我如何取消对此活动的请求?
答案 0 :(得分:2)
这是我之前做过的东西;也许它会有所帮助:
public class NetworkStateMonitor extends BroadcastReceiver {
public interface Listener {
void onNetworkStateChange(boolean up);
}
Context mContext;
boolean mIsUp;
public
NetworkStateMonitor(Context context) {
mContext = context;
//mListener = (Listener)context;
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(this, intentFilter);
mIsUp = isUp();
}
public void
unregister() { // call this when finished with it, and no later than onStop(): callback will crash if app has been destroyed
mContext.unregisterReceiver(this);
}
public boolean
isUp() { // can be called at any time
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo!=null && activeNetworkInfo.isConnectedOrConnecting();
}
@Override public void
onReceive(Context context, Intent intent) { // registerReceiver callback, passed to mListener
boolean upNow = isUp();
if (upNow == mIsUp) return; // no change
mIsUp = upNow;
((Listener)mContext).onNetworkStateChange(mIsUp);
}
}
答案 1 :(得分:1)
这是我的建议,在您的函数中调用此方法以了解互联网是否可用
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
在你的清单中
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
或者您可以将该方法放在父活动或片段中(有条件的)。
答案 2 :(得分:0)
您可以使用连接管理器
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();