Android全局监听系统广播

从事安卓有两年多了,对广播的认识却非常少,平时用到广播最多的莫过于监听系统的网络变化,我在本文中主要是讲解自己对于广播应用的一种思想,如果对于广播还不是很熟悉的童鞋们可以参考以下这个链http://www.cnblogs.com/trinea/archive/2012/11/09/2763182.html
下面就以网络监听为例子进行讲解。

1、自定义广播

这里在onReceive里面进行回调处理,通过NetworkCallback回调给注册监听的页面。
ANDROID_NET_CHANGE_ACTION:广播IntentFilter的action
ObjectsHolder:内部用ArrayList实现的多对象持有管理类(详情见下)

public class NetworkReceiver extends BroadcastReceiver
{

    private final static String ANDROID_NET_CHANGE_ACTION = "com.king.CONNECTIVITY_CHANGE";
    private static BroadcastReceiver sReceiver;
    private static IObjectsHolder sObjectsHolder = new ObjectsHolder<>();

    @Override
    public void onReceive(Context context, Intent intent)
    {
        sReceiver = this;
        String action = intent.getAction();
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action) || ANDROID_NET_CHANGE_ACTION.equals(action))
        {
            final NetworkType type = getNetworkType(context);

            sObjectsHolder.foreach(new IterateCallback()
            {
                @Override
                public boolean next(int i, NetworkCallback item, Iterator it)
                {
                    item.onNetworkChanged(type);
                    return false;
                }
            });

        }

    }


    public static BroadcastReceiver getReceiver()
    {
        if (sReceiver == null)
        {
            sReceiver = new NetworkReceiver();
        }
        return sReceiver;
    }


    /**
     * 发送网络检测广播
     *
     * @param context
     */
    public static void sendBroadcast(Context context)
    {
        Intent intent = new Intent();
        intent.setAction(ANDROID_NET_CHANGE_ACTION);
        context.sendBroadcast(intent);
    }

    /**
     * 注册广播
     *
     * @param context
     */
    public static void registerReceiver(Context context)
    {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ANDROID_NET_CHANGE_ACTION);
        context.getApplicationContext().registerReceiver(getReceiver(), filter);
    }


    /**
     * 取消注册广播
     *
     * @param context
     */
    public static void unregisterReceiver(Context context)
    {
        if (sReceiver != null)
        {
            try
            {
                context.getApplicationContext().unregisterReceiver(sReceiver);
            } catch (Exception e)
            {
            }
        }
    }


    /**
     * 添加回调
     *
     * @param callback
     */
    public static void addCallback(NetworkCallback callback)
    {
        sObjectsHolder.add(callback);
    }

    /**
     * 移除回调
     *
     * @param callback
     */
    public static void removeCallback(NetworkCallback callback)
    {
        sObjectsHolder.remove(callback);
    }

    /**
     * 获得ConnectivityManager对象
     *
     * @param context
     * @return
     */
    public static ConnectivityManager getConnectivityManager(Context context)
    {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return manager;
    }

    /**
     * 网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context)
    {
        ConnectivityManager manager = getConnectivityManager(context);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null)
        {
            return info.isConnected();
        } else
        {
            return false;
        }
    }

    /**
     * wifi是否可用
     *
     * @param context
     * @return
     */
    public static boolean isWifiConnected(Context context)
    {
        ConnectivityManager manager = getConnectivityManager(context);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo == null)
        {
            return false;
        } else
        {
            return ConnectivityManager.TYPE_WIFI == networkInfo.getType();
        }
    }


    /**
     * 获得网络类型
     *
     * @param context
     * @return
     */
    public static NetworkType getNetworkType(Context context)
    {
        ConnectivityManager manager = getConnectivityManager(context);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo == null)
        {
            return NetworkType.None;
        } else
        {
            int type = networkInfo.getType();
            if (type == ConnectivityManager.TYPE_MOBILE)
            {
                return NetworkType.Mobile;
            } else if (type == ConnectivityManager.TYPE_WIFI)
            {
                return NetworkType.Wifi;
            } else
            {
                return NetworkType.None;
            }
        }
    }


    public enum NetworkType
    {
        /**
         * wifi网络
         */
        Wifi,
        /**
         * 移动数据网络
         */
        Mobile,
        /**
         * 无网络
         */
        None
    }

    public interface NetworkCallback
    {
        /**
         * 网络变化监听
         *
         * @param type
         */
        void onNetworkChanged(NetworkType type);
    }

}
2、创建接口和ObjectsHolder类

一个内部用ArrayList实现的多对象持有管理类

public interface IObjectsHolder
{

    /**
     * @Description 添加对象
     * @param object
     */
    void add(T object);

    /**
     * @Description 移除对象
     * @param object
     */
    boolean remove(T object);

    /**
     *
     * @Description 是否已经包含了该对象
     * @param object
     */
    boolean contains(T object);

    /**
     * @Description 对象个数
     */
    int size();

    /**
     * @Description 清空对象
     */
    void clear();

    /**
     * @Description 遍历对象
     */

    boolean foreach(IterateCallback callback);


    /**
     * @Description 倒序遍历对象
     */
    boolean foreachReverse(IterateCallback callback);

}
public class ObjectsHolder implements IObjectsHolder
{
    private List mListObject = new ArrayList<>();

    @Override
    public void add(T object)
    {
        if (object == null)
        {
            return;
        }
        if (!mListObject.contains(object))
        {
            mListObject.add(object);
        }
    }

    @Override
    public boolean remove(T object)
    {
        if (object == null)
        {
            return false;
        }
        return mListObject.remove(object);
    }

    @Override
    public boolean contains(T object)
    {
        if (object == null)
        {
            return false;
        }
        return mListObject.contains(object);
    }

    @Override
    public int size()
    {
        return mListObject.size();
    }

    @Override
    public void clear()
    {
        mListObject.clear();
    }

    @Override
    public boolean foreach(IterateCallback callback)
    {
        return CollectionUtil.foreach(mListObject,callback);
    }

    @Override
    public boolean foreachReverse(IterateCallback callback)
    {
        return CollectionUtil.foreachReverse(mListObject,callback);
    }
}
3、在程序入口处进行注册
public class App extends Application
{
    private static App sInstance;

    public static App getApplication()
    {
        return sInstance;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        sInstance = this;
        init();
    }

    private void init()
    {
        NetworkReceiver.registerReceiver(this);
    }


    @Override
    public void onTerminate()
    {
        NetworkReceiver.unregisterReceiver(this);
        super.onTerminate();
    }
}
4、在BaseActivity实现接口并提供方法给子类调用
public class BaseActivity extends AppCompatActivity implements NetworkReceiver.NetworkCallback
{

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init()
    {
        NetworkReceiver.addCallback(this);
    }

    @Override
    protected void onDestroy()
    {
        NetworkReceiver.removeCallback(this);
        super.onDestroy();
    }

    @Override
    public void onNetworkChanged(NetworkReceiver.NetworkType type)
    {

    }

public class MainActivity extends BaseActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onNetworkChanged(NetworkReceiver.NetworkType type)
    {
        //此处因为为测试机没有SIM卡,如在开发中可以改成mobil
        if (type == NetworkReceiver.NetworkType.Wifi)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("当前处于数据网络下,会耗费较多流量,是否继续?");
            builder.setCancelable(false);
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {

                }
            });
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {

                }
            });
            builder.show();
        }
        super.onNetworkChanged(type);
    }
}

具体的demo请查看https://github.com/BingoKingCoding/NetworkMonitor。
谢谢支持。

你可能感兴趣的:(Android全局监听系统广播)