首先需要一个service:
这里我定义了一个NetworkStateService,在这个service中我写了一个BroadcastReceiver用于监听网络状态发生改变的情况并在这个service中对其进行了动态注册与绑定
然后就是在你的activity中启动这个service就好了
代码实现:
package com.example.netstate;
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;
public class NetworkStateService extends Service {
private ConnectivityManager connectivityManager;
private NetworkInfo info;
private boolean flag = true;
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@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;
}
}
}
};
@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);
}
}