网络监听器安卓
2022-08-31 15:59:39
我想检查Android中的手机网络何时关闭。我可以捕获该事件吗?
我没有得到正确的API或任何可以解释同样的例子。如果有人做过或任何示例链接,将非常有帮助。
我想检查Android中的手机网络何时关闭。我可以捕获该事件吗?
我没有得到正确的API或任何可以解释同样的例子。如果有人做过或任何示例链接,将非常有帮助。
新的 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();
}
}
}
AndroidManifest 中的新 xml.xml“manifest” 元素下:
<!-- Needed to check when the network connection changes -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
AndroidManifest 中的新 xml.xml“application”元素下:
<receiver android:name="com.blackboard.androidtest.receiver.ConnectionChangeReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
我一直在使用一个小的设置来检查带宽,以确定如何缩放事物,例如图像。
在活动下,在 AndroidManifest 中:
<intent-filter>
...
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
在执行检查的活动中:
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;
}
然后,一个示例用法是:
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
}
它不是最漂亮的,但它提供了足够的灵活性,我可以根据项目是什么以及我对它们的要求来更改项目的带宽截止值。