Android監聽手機網絡變化
Android監聽手機網絡變化
手機網絡狀态發生變化會發送廣播,利用廣播接收者,監聽手機網絡變化
效果圖
注冊廣播接收者
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="……" >
……
<application
…… >
……
<!-- 監聽網絡狀态的廣播接收者 -->
<receiver android:name=".receiver.NetworkBroadcastReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>
廣播接收者
package ……;
import ……;
/**
* Created by kongqw on 2015/11/23.
*/
public class NetworkBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//如果無網絡連接配接activeInfo為null
NetworkInfo activeInfo = manager.getActiveNetworkInfo();
if (wifiInfo.isConnected()) {
// wifi 網絡
Log.i("Network", "wifi 網絡");
} else if (mobileInfo.isConnected()) {
// 手機網絡
Log.i("Network", "手機網絡");
} else if (null == activeInfo) {
// 沒有網絡
Log.i("Network", "沒有網絡");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}