private boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
不過這個方法需要程式主動去詢問,幹你娘我哪知道 user 何時開網路,所以更進階的作法是宣告一個 Receiver 去接收系統是否有開啟連線的訊息,如以下寫法
首先在 AndroidManifest.xml 中宣告權限與一個 Receiver
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
.....
<receiver android:name=".WifiReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
WifiReceiver 繼承 BroadcastReceiver,寫法如下
public class WifiReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager conMan = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = conMan.getActiveNetworkInfo(); if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI) { Log.d("Lotus", "Wifi on"); } else { Log.d("Lotus", "Wifi off"); } } }
easy~~
沒有留言:
張貼留言