Java 网络侦听器 Android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1783117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Network listener Android
提问by Sam97305421562
I want to check when the network of phone in Android goes off. Can I capture that event?
我想检查 Android 中的电话网络何时关闭。我可以捕获那个事件吗?
I am not getting the proper API or any example which would explain the same. If anyone had done or any example links would be really helpful.
我没有得到正确的 API 或任何可以解释相同情况的示例。如果有人做过或任何示例链接将非常有帮助。
采纳答案by Eric
New java class:
新的java类:
public class ConnectionChangeReceiver extends BroadcastReceiver
{
@Override
public void onReceive( Context context, Intent intent )
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo( ConnectivityManager.TYPE_MOBILE );
if ( activeNetInfo != null )
{
Toast.makeText( context, "Active Network Type : " + activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
if( mobNetInfo != null )
{
Toast.makeText( context, "Mobile Network Type : " + mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
}
}
New xml in your AndroidManifest.xml under the "manifest" element:
AndroidManifest.xml 中“manifest”元素下的新 xml:
<!-- Needed to check when the network connection changes -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
New xml in your AndroidManifest.xml under the "application" element:
AndroidManifest.xml 中“application”元素下的新 xml:
<receiver android:name="com.blackboard.androidtest.receiver.ConnectionChangeReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
回答by noillusion
The above answer only works if mobile packet data is enabled. Otherwise, ConnectivityManager would be null and you can no longer retrieve NetworkInfo. The way around it is to use a PhoneStateListener or TelephonyManager instead.
以上答案仅在启用移动分组数据时才有效。否则,ConnectivityManager 将为 null,您将无法再检索 NetworkInfo。解决方法是改用 PhoneStateListener 或 TelephonyManager。
回答by Abandoned Cart
I have been using a small setup to check the bandwidth for determining how to scale things, such as images.
我一直在使用一个小的设置来检查带宽,以确定如何缩放事物,例如图像。
Under the activity, in AndroidManifest:
在活动下,在 AndroidManifest 中:
<intent-filter>
...
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
In the activity where the checks are being performed:
在执行检查的活动中:
boolean network;
int bandwidth;
@Override
public void onCreate(Bundle savedInstanceState) {
...
network = isDataConnected();
bandwidth = isHighBandwidth();
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
network = isDataConnected();
bandwidth = isHighBandwidth();
}
}, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
...
}
...
private boolean isDataConnected() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
} catch (Exception e) {
return false;
}
}
private int isHighBandwidth() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
return wm.getConnectionInfo().getLinkSpeed();
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return tm.getNetworkType();
}
return 0;
}
An example usage would then be:
一个示例用法是:
if (network) {
if (bandwidth > 16) {
// Code for large items
} else if (bandwidth <= 16 && bandwidth > 8) {
// Code for medium items
} else {
//Code for small items
}
} else {
//Code for disconnected
}
It's not the prettiest, but it allows enough flexibility that I can change the bandwidth cutoff for items depending on what they are and my requirements for them.
它不是最漂亮的,但它提供了足够的灵活性,我可以根据项目的内容和我对项目的要求更改其带宽截止。
回答by luckyhandler
If using Android Annotationsis an option for you try this in your activities - that's all, the rest is generated:
如果您可以选择使用Android Annotations,请在您的活动中尝试此操作 - 仅此而已,其余部分将生成:
@Receiver(actions = ConnectivityManager.CONNECTIVITY_ACTION,
registerAt = Receiver.RegisterAt.OnResumeOnPause)
void onConnectivityChange() {
//react
}
Use this only if you already use AndroidAnnotations - putting this dependency inside your project only for this piece of code would be overkill.
仅当您已经使用 AndroidAnnotations 时才使用它 - 将此依赖项仅放在您的项目中用于这段代码将是矫枉过正。