Android 实现对网络状态变化进行全局监听并提示

这里是把代码写在BaseActivity中,然后那个页面需要监听那个页面就继承BaseActivity,然后打开监听方法,

//这里是EventBus依赖地址:implementation 'org.greenrobot:eventbus:3.1.1'

代码如下:

1.TestBaseActivity

package com.tsq.junbanpt.aiui.activity;

import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.tsq.junbanpt.R;
import com.tsq.junbanpt.aiui.bean.MessageEvent;
import com.tsq.junbanpt.aiui.util.NetBroadcastReceiver;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class TestBaseActivity extends AppCompatActivity {
    private NetworkStatusLayout mNetworkStatusLayout;
    private NetBroadcastReceiver receiver;
    private boolean checkNetworkStatusChangeListenerEnable = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_test_base);
        EventBus.getDefault().register(this);
    }

    @Override
    public void setContentView(int layoutResID) {
        LinearLayout mRootLayout = findViewById(R.id.root_linear_layout);
        //将网络状态view添加到根视图
        mNetworkStatusLayout = new NetworkStatusLayout(this);
        //默认隐藏状态
        mNetworkStatusLayout.setVisibility(View.GONE);
        mRootLayout.addView(mNetworkStatusLayout, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        //将子类的layout,添加到根目录
        View mContentView = LayoutInflater.from(this).inflate(layoutResID, null);
        mRootLayout.addView(mContentView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!checkNetworkStatusChangeListenerEnable) {
            return;
        }
        receiver = new NetBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void setCheckNetworkStatusChangeListenerEnable(boolean checkNetworkStatusChangeListener) {
        this.checkNetworkStatusChangeListenerEnable = checkNetworkStatusChangeListener;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event) {
        if (event.getType().equals("广播网络变化")) {
            if (event.getContect().equals("网络已断开")) {
                if (mNetworkStatusLayout.getVisibility() == View.GONE) {
                    mNetworkStatusLayout.setVisibility(View.VISIBLE);
                }
            } else {
                if (mNetworkStatusLayout.getVisibility() == View.VISIBLE) {
                    mNetworkStatusLayout.setVisibility(View.GONE);
                }
            }
        }
    }

}

2.NetBroadcastReceiver

package com.tsq.junbanpt.aiui.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


import com.tsq.junbanpt.aiui.bean.MessageEvent;

import org.greenrobot.eventbus.EventBus;


public class NetBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        EventBus.getDefault().post(new MessageEvent("广播网络变化",getNetworkConnectionType(context)));
    }

    public String getNetworkConnectionType(Context context) {
        //获取连接管理器
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null)
            return "网络已断开";
        //获取网络连接信息
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                return "WIFI网络";
            }
            if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                return "手机数据网络";
            }
        }
        return "网络已断开";
    }
}

3.NetworkStatusLayout

package com.tsq.junbanpt.aiui.activity;

import android.content.Context;
import android.widget.LinearLayout;

import com.tsq.junbanpt.R;


public class NetworkStatusLayout extends LinearLayout {
    public NetworkStatusLayout(Context context) {
        super(context);
        inflate(context, R.layout.layout_network_status, this);
    }
}

4.MessageEvent

public class MessageEvent {
    private String type;
    private String contect;

    public MessageEvent(String type, String contect) {
        this.type = type;
        this.contect = contect;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getContect() {
        return contect;
    }

    public void setContect(String contect) {
        this.contect = contect;
    }
}

xml文件

5.activity_test_base




    

    

6.layout_network_status



    


7.在你要监听的Activity继承这个父类 然后在onCreate方法中调用此方法:

setCheckNetworkStatusChangeListenerEnable(true);

结束

你可能感兴趣的:(Android 实现对网络状态变化进行全局监听并提示)