我想听取连接更改并按以下方式尝试:
清单
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- ....... -->
<receiver
android:name="<packagename>.ConnectionReceiver">
<intent-filter>
<action android:name="ConnectivityManager.CONNECTIVITY_ACTION" />
</intent-filter>
</receiver>
类
public class ConnectionReceiver extends BroadcastReceiver {
private static final String TAG = "ConnectionReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Connection changed");
}
}
不幸的是,当我打开和关闭WiFi连接时,它似乎没有被调用。
这里有什么问题,我错过了什么吗?
答案 0 :(得分:0)
您可以尝试这样的事情:
在“manifest”
下的AndroidManifest.xml中<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
在“application”
下的AndroidManifest.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>
接收者类:
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();
}
}
}