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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/root_linear_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    </LinearLayout>

</LinearLayout>
6.layout_network_status
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@color/gray">

    <TextView
        android:id="@+id/tv_network_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="网络连接不可用"
        android:textColor="@color/red" />


</RelativeLayout>

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

setCheckNetworkStatusChangeListenerEnable(true);

结束

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值