我正在尝试使用PhoneStateListener来处理连接状态更改。我已经在服务的创建方法中注册了侦听器。当我从手机设置中启用或禁用 wifi 连接时,侦听器的覆盖方法 onDataConnectionStateChanged(int 状态)被调用,但在这两种情况下,"状态"参数都是 0,它总是进入开关的第一个情况。这是我对该方法的实现:
PhoneStateListener listener = new PhoneStateListener() {
@Override
public void onDataConnectionStateChanged(int state) {
super.onDataConnectionStateChanged(state);
switch (state) {
case TelephonyManager.DATA_DISCONNECTED:
Toast.makeText(LocationService.this, "Data connection lost!", Toast.LENGTH_LONG).show();
break;
case TelephonyManager.DATA_CONNECTED:
Toast.makeText(LocationService.this, "Data connection available!", Toast.LENGTH_LONG).show();
break;
}
}
};
结果始终是一条吐司消息,说:"数据连接丢失!我确定我在这里错过了一些简单的东西,但我无法找出问题所在。
老问题,但您显示的代码是针对"数据"的,而不是用于 Wifi。我有相同的代码,并且仅在我连接"LTE"(数据)时执行
private void registerDataListener(Context context) {
listener = new PhoneStateListener() {
@Override
public void onDataConnectionStateChanged(int state) {
switch (state) {
case TelephonyManager.DATA_DISCONNECTED:
Log.d(TAG, "Disconnected");
break;
case TelephonyManager.DATA_CONNECTED:
Log.d(TAG, "Connected");
break;
case TelephonyManager.DATA_CONNECTING:
Log.d(TAG, "Connecting");
break;
case TelephonyManager.DATA_SUSPENDED:
Log.d(TAG, "Disconnecting");
break;
}
}
};
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(listener,PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
Log.d(TAG, "Registering PhoneStateListener");
}
并且不要忘记在清单中添加权限
<uses-permission android:name="android.permission.READ_PHONE_STATE" />