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);

結束

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章