Android中網絡狀況時有變化,好比從有網到沒網,從wifi到gprs,gprs又從cmwap到cmnet...等等!
若是你的程序有些功能是須要網絡支持的,有時候就須要監聽到網絡的變化狀況進行相應的處理。
好比說下載一個文件,若是忽然斷網了,怎麼處理?網絡又恢復了,如何監聽到並重連?
當網絡變化的時候系統會發出義個廣播broadcast,只要在程序中註冊一個廣播接收器BroadcastReceiver,並在IntentFilter中添加相應的過濾,這樣一旦網絡有變化,程序就能監聽到
public
static
final
String CONNECTIVITY_CHANGE_ACTION =
"android.net.conn.CONNECTIVITY_CHANGE"
;
2 |
private void registerDateTransReceiver() { |
3 |
Log.i(TAG, "register receiver " + CONNECTIVITY_CHANGE_ACTION); |
4 |
IntentFilter filter = new IntentFilter(); |
5 |
filter.addAction(CONNECTIVITY_CHANGE_ACTION); |
6 |
filter.setPriority( 1000 ); |
7 |
registerReceiver( new MyReceiver(), filter); |
1 |
public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE" ; |
2 |
private void registerDateTransReceiver() { |
3 |
Log.i(TAG, "register receiver " + CONNECTIVITY_CHANGE_ACTION); |
4 |
IntentFilter filter = new IntentFilter(); |
5 |
filter.addAction(CONNECTIVITY_CHANGE_ACTION); |
6 |
filter.setPriority( 1000 ); |
7 |
registerReceiver( new MyReceiver(), filter); |
在MyReceiver中:
2 |
public void onReceive(Context context, Intent intent) { |
3 |
String action = intent.getAction(); |
4 |
Log.i(TAG, "PfDataTransReceiver receive action " + action); |
5 |
if (TextUtils.equals(action, CONNECTIVITY_CHANGE_ACTION)){ //網絡變化的時候會發送通知 |
2 |
public void onReceive(Context context, Intent intent) { |
3 |
String action = intent.getAction(); |
4 |
Log.i(TAG, "PfDataTransReceiver receive action " + action); |
5 |
if (TextUtils.equals(action, CONNECTIVITY_CHANGE_ACTION)){ //網絡變化的時候會發送通知 |
當網絡變化時,從有網到沒網也會發廣播,就舉的例子來講,若是下載時斷網了,接收到廣播的時候要判斷當前網絡是可用仍是不可用狀態,若是可用進行什麼操做;不可用進行什麼操做:
01 |
public static NetworkInfo getActiveNetwork(Context context){ |
04 |
ConnectivityManager mConnMgr = (ConnectivityManager) context |
05 |
.getSystemService(Context.CONNECTIVITY_SERVICE); |
08 |
NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo(); // 獲取活動網絡鏈接信息 |
public static NetworkInfo getActiveNetwork(Context context){ |
04 |
ConnectivityManager mConnMgr = (ConnectivityManager) context |
05 |
.getSystemService(Context.CONNECTIVITY_SERVICE); |
08 |
NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo(); // 獲取活動網絡鏈接信息 |
這個方法返回的aActiveInfo能夠判斷網絡的有無,若是返回的是null,這時候是斷網了,若是返回對象不爲空,則是連上了網。在返回的NetworkInfo對象裏,能夠有對象的方法獲取更多的當前網絡信息,好比是wifi仍是cmwap等,就很少說了。