Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android監聽網絡變化

Android監聽網絡變化

編輯:關於Android編程

最近在做APP,需要監聽Android手機網絡的變化情況,同時對不同的情況做出不同的響應策略,這裡有兩種方法。

判斷聯網工具類

這裡我使用的是ConnectivityManager和NetworkInfo兩個類來實現的。詳細代碼如下:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

/**
 * Created on 2016/10/31.
 * 網絡狀態判斷
 */
public class NetWorkUtils {
    public Context context = null;

    public NetWorkUtils(Context context) {
        this.context = context;
    }

    public static MyApplication getApplication() {
        return MyApplication.getInstance();
    }

    /**
     * 判斷是否聯網
     */
    public static boolean isConnectNET(final Context context) {
        final ConnectivityManager conManage = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo networkInfo = conManage.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            return true;
        } else {
            Toast.makeText(context, "斷網了,請檢查網絡~", Toast.LENGTH_SHORT).show();
            return false;
        }
    }
}

自定義BroadcastReceiver

單單使用BroadcastReceiver來實現監聽。


源碼

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.jiketuandui.antinetfraud.Activity.NetWorkErrorActivity;
import com.jiketuandui.antinetfraud.Util.NetWorkUtils;

/**
 * Created on 2016/10/31.
 * 使用廣播來監聽“網絡連接”的情況
 * 當網絡連接不存在的時候(斷網),NetWorkUtils.isConnectNET(context)
 * 返回false,這個時候我們就跳轉到一個錯誤提示的Activity中,提示用戶聯網
 */
public class NETChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (!NetWorkUtils.isConnectNET(context)) {
            intent.setClass(context, NetWorkErrorActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }
}

注冊

1.為了獲取上網的權限,和檢測網絡狀態,我們需要添加權限

 

2.在Manifest中配置BroadReceiver監測斷網,action裡面是網絡連接變化時候來觸發這個Receiver,如下所示:


    
        
    

這個方法的缺點就是需要在Activity中注冊廣播,在APP中就不大適用,因為一個Application中不可能只有一個Activity,而且我們也不可能每一個都去注冊一邊,太麻煩了,所以有了以下的方法。

Service+BroadcastReceiver

上圖

這裡寫圖片描述

主要就是找一個可以獨立於眾多Activity的載體去承載BroadcastReceiver
,實現對整一個Application的網絡監控。<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxoMyBpZD0="原理">原理

原理其實就是在程序的後台創建一個看不見的服務(Service),在Service中注冊一個廣播(BroadcastReceiver),當網路發生變化的時候就可以產生一個ConnectivityManager.CONNECTIVITY_ACTION的事件,只要我們監聽這個事件就可以實現實時監聽網絡變化了。

配置權限

在AndroidManifest中添加訪問網絡的權限和監控網絡變化的權限

    
當然,也不要忘記在中配置一下

    
        
            

            
        
    
    

    

源碼

這裡包含了5個文件,NetworkStateService、NetWorkUtils、NetWorkErrorActivity、getConnect和MainActivity

NetworkStateService

package com.notzuonotdied.monitor_network_changes;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;

/**
 * Created by Notzuonotdied on 2016/10/31.
 * 檢測網絡的Service服務
 */
public class NetworkStateService extends Service {
    private ConnectivityManager connectivityManager;
    private NetworkInfo info;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                info = connectivityManager.getActiveNetworkInfo();
                if (info != null && info.isAvailable()) {
                    String name = info.getTypeName();
                    intent.setClass(context, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                } else {
                    intent.setClass(context, NetWorkErrorActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    /**
     * 注冊BroadcastReceiver
     * */
    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, mFilter);
    }

    /**
     * 當被銷毀的時候,我們要把BroadcastReceiver注銷
     * */
    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
}

NetWorkUtils

package com.notzuonotdied.monitor_network_changes;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

/**
 * Created by Notzuonotdied on 2016/10/31.
 * 網絡狀態判斷
 */
public class NetWorkUtils {
    public Context context = null;

    public NetWorkUtils(Context context) {
        this.context = context;
    }

    /**
     * 判斷是否聯網
     */
    public static boolean isConnectNET(final Context context) {
        final ConnectivityManager conManage = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo networkInfo = conManage.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            return true;
        } else {
            Toast.makeText(context, "斷網了,請檢查網絡~", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

}

getConnect

package com.notzuonotdied.monitor_network_changes;

import android.support.annotation.Nullable;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Notzuonotdied on 2016/11/2.
 * 從客戶端獲取數據
 */
public class getConnect {
    @Nullable
    public static String doGet(String mURL) throws IOException {
        HttpURLConnection httpURLConnection;
        BufferedReader reader = null;
        StringBuffer stringBuffer = null;
        try {
            httpURLConnection = (HttpURLConnection) new URL(mURL).openConnection();
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");

            // 數據流
            reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            stringBuffer = new StringBuffer();

            String line;
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        if (stringBuffer == null) {
            return null;
        }
        return stringBuffer.toString();
    }
}

MainActivity

package com.notzuonotdied.monitor_network_changes;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;

/**
 * 2016年11月2日 09:15:39
 * */

public class MainActivity extends AppCompatActivity {

    private android.widget.Button btn;
    private android.widget.TextView tv;

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

    /**
     * 初始化Service進行監聽網絡
     */
    private void initService() {
        Intent i = new Intent(this, NetworkStateService.class);
        startService(i);
    }

    /**
     * 初始化響應事件
     */
    private void initListener() {
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (NetWorkUtils.isConnectNET(MainActivity.this)) {
                    new getData().execute();
                }
            }
        });
    }

    /**
     * 初始化UI
     */
    private void initView() {
        this.tv = (TextView) findViewById(R.id.tv);
        this.btn = (Button) findViewById(R.id.btn);
    }

    /**
     * 為了不讓主線程堵塞,影響用戶體驗,使用異步任務來訪問網絡
     */
    class getData extends AsyncTask {

        @Override// 在子線程中doSomething
        protected String doInBackground(Void... voids) {
            String str = null;
            try {
                str = getConnect.doGet("http://www.csdn.com");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

        @Override// 獲取數據完成,返回到主線程來更新主線程
        protected void onPostExecute(String s) {
            tv.setText(s);
            super.onPostExecute(s);
        }
    }

}

NetWorkErrorActivity

這裡是當網絡出現錯誤的時候,顯示錯誤提示的Activity,這只是個小小的思路,各位看官也可以自己定義成其他的。
package com.notzuonotdied.monitor_network_changes;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class NetWorkErrorActivity extends AppCompatActivity {

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

源碼下載

如果覺得不錯,可以star下,THX~ GitHub下載-Monitor_network_changes

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved