码迷,mamicode.com
首页 > 其他好文 > 详细

通过静态广播监听网络变化,在通过回调通知

时间:2016-04-12 12:35:18      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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>

 

通过静态广播监听网络变化,在通过回调通知

标签:

原文地址:http://www.cnblogs.com/zzw1994/p/5382139.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!