經過BroadCast與service時時監聽網絡變化

首先須要一個service:android

  這裏我定義了一個NetworkStateService,在這個service中我寫了一個BroadcastReceiver用於監聽網絡狀態發生改變的狀況並在這個service中對其進行了動態註冊與綁定網絡

而後就是在你的activity中啓動這個service就行了app

代碼實現:ide

package com.example.netstate;this

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.widget.Toast;.net

public class NetworkStateService extends Service {get

private ConnectivityManager connectivityManager;
private NetworkInfo info;
private boolean flag = true;it

private BroadcastReceiver mReceiver = new BroadcastReceiver() {io

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
// Toast.makeText(getApplicationContext(), "網絡發生改變", Toast.LENGTH_SHORT).show();
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
info = connectivityManager.getActiveNetworkInfo();
if (info != null && info.isAvailable()
&& info.isConnected()) {
if(flag){
Toast.makeText(getApplicationContext(), "網絡已鏈接", Toast.LENGTH_SHORT).show();
flag = false;
}
} else {
Toast.makeText(getApplicationContext(), "當前無網絡鏈接", Toast.LENGTH_SHORT).show();
flag = true;
}
}
}
};ast

@Override
public IBinder onBind(Intent arg0) {
return null;
}

@Override
public void onCreate() {
super.onCreate();
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, mIntentFilter);
}

@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}

 

在Activity中啓動service就好啦:

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(MainActivity.this, NetworkStateService.class);
startService(intent);
}

}

相關文章
相關標籤/搜索