我所拥有的是Android代码来检查何时互联网连接发生了变化,所以我可以知道并做其他事情。我确信这段代码是真的,但它不适用于比API 15更新的版本,这是我的接收器:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
这里是网络Util类:
public class NetworkUtil {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
这是我的Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.viralpatel.network"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver
android:name="net.viralpatel.network.NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
</application>
</manifest>
那么我应该改变什么,我可以在Api 18或19上使用它?
这对我来说很有效
public class WifiControlReceiver extends BroadcastReceiver {
// Strings - Log
final String TAG = "WifiControlReceiver";
@Override
public void onReceive(Context wiFiContext, Intent wiFiIntent) {
Log.d(TAG, "WifiControlReceiver +++STARTED +++ ");
Log.d(TAG, "@WifiControlReceiver actionCaught :" + wiFiIntent.getAction());
if ("android.net.wifi.WIFI_STATE_CHANGED".equals(wiFiIntent
.getAction())) {
// TODO : what ever the action you want
}
Log.d(TAG, "DeviceControlHardware ---END/FIN--- / WifiControlReceiver ");
}}
对于Manifest
<receiver
android:name="com.example.WifiControlReceiver"
android:enabled="true"
android:label="WifiControlReceiver"
android:permission="android.permission.ACCESS_NETWORK_STATE" >
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" >
</action>
</intent-filter>
</receiver>
希望对你有帮助