首先,我使用的是 api 23 而不是 android N,所以 android.net.conn.CONNECTIVITY_CHANGE 应该仍然对我有用,但它没有。
显现:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="enis.example.com.connectivitytest">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver android:name="com.connectivitytest.ConnectionChangeReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
</application>
</manifest>
连接更改接收器
package com.connectivitytest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
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_LONG ).show();
Log.v("Active Network Type : ", activeNetInfo.getTypeName());
}
if( mobNetInfo != null )
{
Toast.makeText( context, "Mobile Network Type : " + mobNetInfo.getTypeName(), Toast.LENGTH_LONG ).show();
} Log.v("Mobile Network Type : ", activeNetInfo.getTypeName());
}
}
没有任何 toast 消息,所以我添加了日志消息只是为了清楚起见,但它也没有出现在 logcat 中。我什至尝试了以下代码:https ://gist.github.com/mjohnsullivan/1fec89187b1274dc256e 但都是一样的,没有错误但没有任何反应,没有吐司消息也没有日志消息