Android 利用BroadcastReceiver实时检测网络状态变化

本文介绍了一个自定义的Android服务ReceiveMsgService,用于监听设备的网络连接状态变化,并将状态更新通知给绑定的Activity。通过定时任务的方式检查网络连接情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、定义ReceiveService类

当接收到的网络状态发生改变时通知Activity,需要一个Service,并且绑定该到Activity。

import 
java.util.Date;import java.util.Timer;import java.util.TimerTask;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.Binder;import android.os.IBinder;import android.util.Log;public class ReceiveMsgService extends Service { private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { Timer timer = new Timer(); timer.schedule(new NetworkTask(getApplicationContext()), new Date()); } } }; public interface GetConnectState { void GetState(boolean isConnected); // 网络状态改变之后,通过此接口的实例通知当前网络的状态,此接口在Activity中注入实例对象 } private GetConnectState onGetConnectState; public void setOnGetConnectState(GetConnectState onGetConnectState) { this.onGetConnectState = onGetConnectState; } private Binder binder = new MyBinder(); private boolean isConnected = true; @Override public IBinder onBind(Intent intent) { return binder; } @Override public void onCreate() {// 注册广播 IntentFilter mFilter = new IntentFilter(); mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action registerReceiver(mReceiver, mFilter); } class NetworkTask extends TimerTask { private Context context; public NetworkTask(Context context) { this.context = context; } @Override public void run() { if (isNetworkConnected(context)) { isConnected = true; } else { isConnected = false; } if (onGetConnectState != null) { onGetConnectState.GetState(isConnected); // 通知网络状态改变 } } /* * 判断是否有网络连接 */ private boolean isNetworkConnected(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { return false; } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (NetworkInfo net : info) { if (net.getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } } public class MyBinder extends Binder { public ReceiveMsgService getService() { return ReceiveMsgService.this; } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); // 删除广播 }} 

二、接下来在Activity中,绑定服务

注意:在TabActivity的子Activity中使用service时,bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE),需要改为:

            this.getApplicationContext().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE) ,才可正常使用。

  • public class MainActivity extends Activity  {  
  •   
  •     ReceiveMsgService receiveMsgService;  
  •     private boolean conncetState = true// 记录当前连接状态 
  •   
  •     @Override  
  •     protected void onCreate(Bundle savedInstanceState) {  
  •         // TODO Auto-generated method stub  
  •         super.onCreate(savedInstanceState);  
  •         setContentView(R.layout.page_main);     
  •         bind();  
  •     }  
  •   
  •     private void bind() {  
  •         Intent intent = new Intent(MainActivity.this, ReceiveMsgService.class);  
  •         bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);  
  •     }  
  •   
  •     private ServiceConnection serviceConnection = new ServiceConnection() {  
  •         @Override  
  •         public void onServiceDisconnected(ComponentName name) {  
  •         }  
  •   
  •         @Override  
  •         public void onServiceConnected(ComponentName name, IBinder service) {  
  •             receiveMsgService = ((ReceiveMsgService.MyBinder) service)  
  •                     .getService();  
  •             receiveMsgService.setOnGetConnectState(new GetConnectState() { // 添加接口实例获取连接状态  
  •                         @Override  
  •                         public void GetState(boolean isConnected) {  
  •                             if (conncetState != isConnected) { // 如果当前连接状态与广播服务返回的状态不同才进行通知显示  
  •                                 conncetState = isConnected;  
  •                                 if (conncetState) {// 已连接  
  •                                     handler.sendEmptyMessage(1);  
  •                                 } else {// 未连接  
  •                                     handler.sendEmptyMessage(2);  
  •                                 }  
  •                             }  
  •                         }  
  •                     });  
  •         }  
  •     };  
  •       
  •     private void unbind() {  
  •         if (receiveMsgService != null ) {  
  •             unbindService(serviceConnection);  
  •         }  
  •     }  
  •   
  •     Handler handler = new Handler() {  
  •         public void handleMessage(Message msg) {  
  •   
  •             switch (msg.what) {  
  •             case 1:// 已连接  
  •                 Toast.makeText(MainActivity.this"网络已经连接" ,Toast.LENGTH_LONG).show();  
  •                 break;  
  •             case 2:// 未连接  
  •                 Toast.makeText(MainActivity.this"网络未连接" ,Toast.LENGTH_LONG).show();  
  •                 break;  
  •             default:  
  •                 break;  
  •             }  
  •             ;  
  •         };  
  •   
  •     };  
  •       
  •     @Override  
  •     protected void onDestroy()  
  •     {  
  •         // TODO Auto-generated method stub  
  •         super.onDestroy();  
  •         unbind();  
  •     }   

三、在Manifest中注册Serevice和相关权限

<usespermission android:name="android.permission.ACCESS_NETWORK_STATE" />   
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
//注册service
<service android:enabled="true" android:name=".ReceiveMsgService" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值