package com.changim.patient.app.sys.receive; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.changim.patient.app.sys.Constants; import com.changim.patient.app.sys.service.SocketService; import com.changim.patient.app.utils.TDevice; import java.util.ArrayList; public class NetBroadcastReceiver extends BroadcastReceiver { private final String TAG = "NetBroadcastReceiver"; public static ArrayList<NetEventHandler> mListeners = new ArrayList<NetEventHandler>(); @Override public void onReceive(final Context context, Intent intent) { if (intent.getAction().equals(Constants.INTENT_ACTION.ACTION_NET_CONN_CHANGE)) { Log.d(TAG, "监听网络连接状态"); boolean hasInternet = TDevice.hasInternet(); if (hasInternet) { context.startService(new Intent(context, SocketService.class)); } if (mListeners.size() > 0)// 通知接口完成加载 for (NetEventHandler handler : mListeners) { handler.onNetChange(hasInternet); } } else if (intent.getAction().equals(Constants.INTENT_ACTION.ACTION_NET_CONN_SUCCESS)) {//连接成功,尝试重连接 } else if (intent.getAction().equals(Constants.INTENT_ACTION.ACTION_NET_CONN_FAILURE)) {//连接失败 } } public static abstract interface NetEventHandler { public abstract void onNetChange(boolean hasInternet); } }
package com.changim.patient.app.sys; /** * <描述当前文件类名功能> * * @author : * @date : 2016-03-18 16:51 */ public interface Constants { interface INTENT_ACTION { final String ACTION_NET_CONN_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE"; final String ACTION_NET_CONN_SUCCESS = "android.net.conn.CONNECTIVITY_SUCCESS"; final String ACTION_NET_CONN_FAILURE = "android.net.conn.CONNECTIVITY_FAILURE"; } }
记得在AndroidManifest.xml中注册及加权限:
<receiver android:name=".sys.receive.NetBroadcastReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.conn.CONNECTIVITY_SUCCESS" /> <action android:name="android.net.conn.CONNECTIVITY_FAILURE" /> </intent-filter> </receiver>
时间: 2024-10-11 17:15:37