我想知道如何通过BroadcastReceiver处理任何应用程序的网络检查,我知道如何在我调用我的服务时检查网络可用性但是假设我的网络在事务之间断开连接我无法处理这种情况。
请提供一些教程链接,我也可以在这里学习。
谢谢。
答案 0 :(得分:3)
使用: -
public boolean isNetworkAvailable()
{
ConnectivityManager cmanager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInformation= cmanager .getActiveNetworkInfo();
if (netInformation!= null && netInformation.isAvailable() && netInformation.isConnected())
{
return true;
}
return false;
}
或检查: -
Checking the Networking Connectivity using BroadcastReceiver in Android
答案 1 :(得分:3)
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.w("Network Listener", "Network Type Changed");
}
};
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkStateReceiver, filter);
这是example code。
答案 2 :(得分:1)
你也可以像这样添加info.isConnectedOrConnecting()选项..
public static boolean checkConn(Context ctx)
{
ConnectivityManager conMgr = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = conMgr.getActiveNetworkInfo();
if (info == null || !info.isConnected() || !info.isAvailable()||!info.isConnectedOrConnecting()){
Toast.makeText(ctx, "Internet is not available", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
答案 3 :(得分:0)
这是我在Stackoverflow上找到的代码(不记得是谁写的)
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info == null) {
return false;
}
return info.isConnected();
}
需要internet
和network_state
权限