我知道您可以编写代码,通过该代码可以确定设备是否连接到网络.
但在我的应用程序中,我想要做的是在设备将其状态从"网络"更改为"无网络"时收到通知.例如,当用户进入隧道并丢失信号等时会发生这种情况.或者当在WiFi上时,用户离开接入点的范围并且不再能够访问互联网.
Android API是否提供了可以注册监听器的功能,以便每次网络状态发生变化时都会收到通知?
我找到了这段代码并尝试使用它,但它没有做任何事情.网络状态发生变化时,我不会收到任何通知.
public class ConnectivityManager extends PhoneStateListener{
Activity activity;
public ConnectivityManager(Activity a){
TelephonyManager telephonyManager = (TelephonyManager)a.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(this, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
activity = a;
}
@Override
public void onDataConnectionStateChanged(int state) {
super.onDataConnectionStateChanged(state);
switch (state) {
case TelephonyManager.DATA_DISCONNECTED:
new AlertDialog.Builder(activity).
setCancelable(false).
setTitle("Connection Manager").
setMessage("There is no network connection. Please connect to internet and start again.").
setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
System.exit(0);
}
}).create();
break;
case TelephonyManager.DATA_CONNECTED:
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
另外,我在AndroidManifest.xml中添加了相应的权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> …Run Code Online (Sandbox Code Playgroud) 这个很奇怪.我有一个列表视图,它是相对布局的一部分.我已为此相对布局设置了背景,并使列表视图背景变为透明.
现在,一切都很好,直到今天早上.即使我的列表视图中只有一行,我也可以看到整个屏幕都覆盖了我的自定义背景.
然后,我获得了Verizon Motorola Droid X for 2.3.3的更新(之前为2.2).一旦更新,我再次启动我的应用程序,现在发生了什么.
如果我的列表视图只有一行,我看到它下面有一个白色区域而不是我的自定义背景.但如果它说100行并因此覆盖整个屏幕我将不会看到奇怪的白色背景.我的相对布局的宽度和高度设置为"fill_parent".
我在底部发布了我的XML.有没有其他人遇到过这个问题,或者我犯了一些非常愚蠢的错误.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:background = "@drawable/background"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id = "@+id/listQueue"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:layout_below = "@id/homeScreenBanner"
android:background="@android:color/transparent"
android:divider="@drawable/separator"
android:scrollingCache="false"/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
编辑:
我想我找到了解决这个问题的方法:
将layout_height属性更改为wrap_content,它就像一个魅力.:)
更改后的行.
android:layout_height = "wrap_content"
我想知道在Android源代码中应该有什么起点来实现Android中的本地DNS缓存.我想有这样的事情pdnsd或djbdns.可能djbdns在Android上移植并修改流程,以便Android框架指向djbdns解决方案.
如果有人可以将我指向Android源代码中的文件,该文件访问本地DNS设置以解析域名.