Android app中实现网络监听

来源:互联网 发布:淘宝v3会员是几钻 编辑:程序博客网 时间:2024/05/29 17:22
  • 创建BroadcastReceiver

  • Manifest中注册

  • NetWorkUtil

  • *ApplicationContex

BroadcastReceiver

首先创建一个BroadcastReceiver:

public class NetWorkChangeBroadcasetReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {         //ApplicationContext.getApplication()是自己写的一个,主要是为了获取Application,这里使用了弱引用        if (!NetWorkUtil.isConnected(ApplicationContext.getApplication())) {            //做你想做的事,弹出对话框提示用都可以            ToastUtils.showLong(context, R.string.local_network_error);        }    }}

Mmanifest中注册

监听网络变化

 <receiver android:name="com.alpha.lib_sdk.app.net.broadcast.NetWorkChangeBroadcasetReceiver">            <intent-filter android:priority="1000">                            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />            </intent-filter>        </receiver>

NetWorkUtil

网络是否连接

 public static boolean isConnected(Context context) {        ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo activeNetInfo = conMan.getActiveNetworkInfo();        boolean connect = false;        try {            connect = activeNetInfo.isConnected();        } catch (Exception e) {        }        return connect;    }

ApplicationContext

获取Application的弱引用对象,在Application中初始化

public class ApplicationContext {    private static final String TAG = "App.ApplicationContext";    private static WeakReference<Application> sApplicationWeakRef;    private static WeakReference<Context> sCurrContextWeakRef;    public static Application getApplication() {        return sApplicationWeakRef != null ? sApplicationWeakRef.get() : null;    }    public static void setApplication(Application application) {        if (application == null) {            ApplicationContext.sApplicationWeakRef = null;            return;        }        ApplicationContext.sApplicationWeakRef = new WeakReference<Application>(application);    }    public static Context getCurrentContext() {        return sCurrContextWeakRef != null ? sCurrContextWeakRef.get() : null;    }    public static void setCurrentContext(Context context) {        if (context == null) {            ApplicationContext.sCurrContextWeakRef = null;            return;        }        ApplicationContext.sCurrContextWeakRef = new WeakReference<Context>(context);    }    public static Context getContext() {        Context c = getCurrentContext();        if (c == null) {            Log.e(TAG, "ApplicationContext's currentContext is null.");            c = getApplication();        }        return c;    }    /**     * 不知道为什么?返回的是"@MAIN"     * @param context     * @param pid     * @return     */    public static String getPidKey(Context context, int pid) {        // TODO: 16/3/8 albieliang         return "@MAIN";    }}

通过上面这个的一个方式就可以实现app中的网络监听

原创粉丝点击