Android实现监测网络变化以及无网络listview填充 简易新闻(十六 上)

Android实现监测网络变化以及无网络listview填充 简易新闻(十六 上)

  • 关于
  • 实现
    • 第一步,编写NetworkChange继续广播
    • 第二步,新增NetworkStateUtil.java
    • 第三步,添加对应权限修改Androidmanifest.xml
    • 第四步,修改对应的BasicActivity.java
    • 第五步,在MyApplication中注册

关于

这篇文章分为两部上,上半部为讲解如何实现简易新闻的监听网络变化(其他的app上也是通用的,只不过本篇就简易新闻来讲述),下半部实现对应网络变化的应对,如无网络下,适配器的填充问题以及数据库的访问操作等。(本来想着20号以前发布的,考虑到1024的徽章hh)
废话不多说,先上一下效果图:

由于大小限制,以及网络限制的原因,导致只能录制这么短啦,等到你们实现就知道具体效果啦。

实现

通过配置广播监听网络变化来实现网络变化的提示以及后续数据转换。

第一步,编写NetworkChange继续广播

package com.example.frametest.tools;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;

public class NetworkChange extends BroadcastReceiver {
    public final int wifi =2 ,mobile =1 ,none = 0;
    public int oldState = none;
    public List<OnNetWorkChange> onNetWorkChange = new ArrayList<OnNetWorkChange>();
    private static NetworkChange networkChange;
    public static NetworkChange getInstance(){
        if (networkChange ==null){
            networkChange = new NetworkChange();
        }
        return networkChange;
    }


    //回调接口
    public interface OnNetWorkChange{
        //返回各个(wifi,移动网络,无网络)状态的值,上一个网络状态的值,当前的网络状态的值
        void onChange(int wifi, int mobile ,int none, int oldStatus, int newStatus);
    }
    /**
     * 增加网络变化监听回调对象
     * 如果设置多个回调,请务必不要设置相同名字的OnNetWorkChange对象,否则会无效
     *
     * @param onNetWorkChange 回调对象
     */
    public <onNetWorkChange> void setOnNetWorkChange(onNetWorkChange onNetWorkChange){
        if (this.onNetWorkChange.contains(onNetWorkChange)){
            return;
        }
        this.onNetWorkChange.add((OnNetWorkChange) onNetWorkChange);
    }
    /**
     * 取消网络变化监听监听回调
     *
     * @param onNetWorkChange 回调对象
     */
    public void delOnNetWorkChange(OnNetWorkChange onNetWorkChange){
        if (this.onNetWorkChange.contains(onNetWorkChange)){
            this.onNetWorkChange.remove(onNetWorkChange);
        }
    }
    /**
     * 触发网络状态监听回调
     *
     * @param nowStatus 当前网络状态
     */
    private void setChange(int nowStatus){
        for (OnNetWorkChange change:onNetWorkChange){
            change.onChange(wifi,mobile,none,oldState,nowStatus);
        }
        oldState = nowStatus;
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        if (onNetWorkChange ==null){
            //当没有设置回调的时候,什么都不做
            return;
        }
        if (NetworkStateUtil.isNetWorkConnected(context)) {
            if (NetworkStateUtil.isWifiConnected(context)) {
                Log.i("通知", "Wifi网络可用");
                setChange(wifi);

            }
            if (NetworkStateUtil.isMobileConnected(context)) {
                Log.i("通知", "仅移动网络可用");
                setChange(mobile);

            }
        } else {
            Log.i("通知", "网络不可以用");
            setChange(none);

        }

    }
}

第二步,新增NetworkStateUtil.java

读取网络信息,并判断是否网络连接,是否wifi连接是否移动数据连接等。

package com.example.frametest.tools;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.widget.Toast;

import java.lang.reflect.Method;

/*
* Created by Tobey_r1 on 2019/10/15
* */
public class NetworkStateUtil {
    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isNetWorkConnected(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo !=null && networkInfo.isConnected());
    }
    /**
     * 检测网络连接状态
     *
     * @param context
     * @return
     */
     public static boolean isNetworkConnected(Context context){
         if (context !=null){
             ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
             NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
             if (mNetworkInfo !=null){
                 return mNetworkInfo.isAvailable();
             }

         }
         return false;
     }
    /**
     * 网络是否未连接
     * 未连接给出提示
     *
     * @param context
     * @return boolean 是否连接网络
     */
      public static boolean isNetDisconnected(Context context){
          if (! isNetWorkConnected(context)){
              Toast.makeText(context,"无网络,请检查网络连接",Toast.LENGTH_SHORT).show();
              return true;
          }
          return false;
      }
    /**
     * 判断wifi是否连接
     *
     * @param context
     * @return
     */
    public static boolean isWifiConnected(Context context){
        //获取ConnectivityManager对象
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo;
        //检测API是否小于23,api23以后getNetWorkInfo(int networkType)方法被弃用
        if (Build.VERSION.SDK_INT< Build.VERSION_CODES.LOLLIPOP){
            //获取ConnectivityManager对象对应的NetworkInfo对象
            //获取WIFI连接的信息
            wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (wifiNetworkInfo != null&& wifiNetworkInfo.isConnected()){
                return true;
            }
        }else {
            //获取所有网络连接的信息
            Network[] networks = connectivityManager.getAllNetworks();
            //通过循环将网络信息逐个读取出来
            for (Network mNetWork : networks){
                wifiNetworkInfo = connectivityManager.getNetworkInfo(mNetWork);
                if (wifiNetworkInfo !=null&& wifiNetworkInfo.getType() ==ConnectivityManager.TYPE_WIFI){
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * 判断移动网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isMobileConnected(Context context) {
        //获得ConnectivityManager对象
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo;
        //检测API是不是小于23,因为到了API23之后getNetworkInfo(int networkType)方法被弃用
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
            //获取ConnectivityManager对象对应的NetworkInfo对象
            //获取WIFI连接的信息
            wifiNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (wifiNetworkInfo != null && wifiNetworkInfo.isConnected()) {
                return true;
            }
        } else {
            //获取所有网络连接的信息
            Network[] networks = connMgr.getAllNetworks();
            //通过循环将网络信息逐个取出来
            for (Network mNetwork : networks) {
                wifiNetworkInfo = connMgr.getNetworkInfo(mNetwork);
                if (wifiNetworkInfo != null && wifiNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 调用系统设置进行设置网络
     *
     * @param context
     */
    public static void goToSetNetWork(Context context) {
        Intent intent = null;

        /**
         * 判断安卓版本
         */
        if (Build.VERSION.SDK_INT > 10) {
            /*3.0以上版本*/

            intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
        } else {
            /*3.0以下版本*/

            intent = new Intent();
            intent.setClassName("com.android.settings", "com.android.settings.WifiSettings");
        }

        context.startActivity(intent);
    }
     *
     * @param context
     * @param enabled
     */
    public static void setWifiEnabled(Context context, boolean enabled) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(enabled);
    }


    /**
     * 设置移动网络状态
     * 注意需要添加权限:
     *
     * @param context 上下文
     * @param enabled 是否开启移动网络连接
     */
    public static void setMobileDataEnabled(Context context, boolean enabled) {
        /**
         * 必须采用反射机制获取系统隐藏的功能
         */
        
        /*
         * 进行简化
         */
        ConnectivityManager connectivityManager = null;
        Class connectivityManagerClz = null;
        try {
            connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            connectivityManagerClz = connectivityManager.getClass();
            Method method = connectivityManagerClz.getMethod("setMobileDataEnabled", boolean.class);
            method.invoke(connectivityManager, enabled);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

第三步,添加对应权限修改Androidmanifest.xml

<!-- 设置wifi状态 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

第四步,修改对应的BasicActivity.java

BasicActivity继承AppCompatActivity,关于所有activity的收集添加以及继承就不在这里写了,算是比较基础的东西。写在BasicAcitivity中也是为了所有页面都能继承使用。

package com.example.frametest.tools;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import com.autonavi.base.amap.mapcore.maploader.NetworkState;
import com.example.frametest.fontsliderbar.MessageSocket;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

public class BasicActivity extends AppCompatActivity implements NetworkChange.OnNetWorkChange {
    public Observable observable;
    private long lastClickTime;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);          
        //注册网络监听
        registerNetWorkReceiver();
    }

    private void registerNetWorkReceiver() {
             //获取对应实例
          NetworkChange.getInstance().setOnNetWorkChange(this);
    }
    //取消监听网络变化
    private void unregisterNetWorkReceiver(){
        NetworkChange.getInstance().delOnNetWorkChange(this);
    }
    @Override
    public void onChange(int wifi, int mobile, int none, int oldStatus, int newStatus) {
        if (newStatus == none) {
            //没有网络
            ToastUtil.showShortToastCenter(this, "已进入无网络状态,请检查网络设置");
        }
        if (newStatus == mobile) {
            //移动网络
            ToastUtil.showShortToastCenter(this, "已连接到移动网络");
        }
        if (newStatus == wifi) {
            //wifi网络
            ToastUtil.showShortToastCenter(this, "已连接到WIFI网络");
            if (oldStatus == mobile) {
                //从移动网络切换到wifi网络
                ToastUtil.showShortToastCenter(this, "已切换至WIFI网络");
            }
        }
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

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

        ActivityCollector.removeActivity(this);
        RxBus.getInstance().unregister(this.getClass().getSimpleName(), observable);
        //这里解绑注销网络监听广播
        unregisterNetWorkReceiver();

    }
}

第五步,在MyApplication中注册

package com.example.frametest.tools;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.multidex.MultiDex;
import android.support.v7.app.AppCompatDelegate;
import java.util.Stack;
import interfaces.heweather.com.interfacesmodule.view.HeConfig;

public class MyApplication extends Application {
    private static Context context;
    private static MyApplication instance;
    private static String moublefhoneUser;
    private static int statueflag;
    private PreferencesHelper ph;
    private static Stack<Activity> activityStack;
    // 单例模式获取唯一的Application实例
    public static Application getInstance() {
        return instance.getApplication();
    }

    public static MyApplication getMyInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        //获取去全局context
        context = getApplicationContext();
        super.onCreate();
        //实例个人Application类
        instance = this;
        //这个是和风天气的注册,不用管
        HeConfig.init("HE1909171034071268","xxx");
        HeConfig.switchToFreeServerNode();   
        MultiDex.install(this);
        //动态注册网络监听广播
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(NetworkChange.getInstance(),filter);
    }
 
    private Application getApplication() {
        return this;
    }

    public static int getStatueflag() {
        return statueflag;
    }
    public static void setStatueflag(int statueflag) {
        MyApplication.statueflag = statueflag;
    }
    /**
     * add Activity 添加Activity到栈
     */
    public static void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }
    public static Context getContext() {
        return context;
    }
    public static void setMoublefhoneUser(String moublefhoneUser) {
        MyApplication.moublefhoneUser = moublefhoneUser;
    }
    public static String getMoublefhoneUser() {
        return moublefhoneUser;
    }
    /**
     * 结束所有Activity
     */
    public static void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }
   
    @Override
    public void onTerminate() {
        super.onTerminate();
        unregisterReceiver(NetworkChange.getInstance());
    }


}

好啦,上半篇就到此结束啦,欢迎一起讨论,欢迎批评指正!

你可能感兴趣的:(简易新闻App,android,广播器)