互联网状态更改事件通知Android

时间:2018-12-06 04:08:19

标签: android mvvm connection

我正在开发一个应用程序,只要有互联网连接,就可以在其中发送消息。连接管理器仅提供WiFi /移动连接状态。我可以ping任何站点以检查Internet连接。这意味着我需要不断轮询。是否有任何方法可以通过网络覆盖不良或网络连接(WiFi回传)不良通知活动恢复连接?

预先感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我相信这对您How to check internet access on Android? InetAddress never times out会有所帮助。最好的解决方案描述了两个选项。

希望这会有所帮助!

答案 1 :(得分:0)

我曾经需要这样的解决方案。因此,我精心设计了一个类,可以利用此站点中的代码来解决问题。我们将此类称为iChessNetwork

import android.content.*;
import android.net.*;
import android.net.wifi.*;
import android.os.*;
import android.widget.*;
import java.io.*;
import java.net.*;

public class iChessNetwork {

private Context mContext;
protected Watcher mWatcher;

public iChessNetwork(Context context, Watcher watcher) {
    mContext = context;
    mWatcher = watcher;
    init();
} 
public interface Watcher {
    public void Online();
}

private void init() {
    registerOnlineChecker();
}
public void stop() {
    unregisterOnlineChecker();
}

/*=========:INTERNET CHECK START ========*/
private BroadcastReceiver mOnlineChecker = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (isConnected()) {
            //Toast.makeText(mContext,"You are connected!",Toast.LENGTH_LONG).show();
            OnlineTester mOnlineTester = new OnlineTester();
            mOnlineTester.execute();
        }
    }
};

private void registerOnlineChecker() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    mContext.registerReceiver(mOnlineChecker, filter);
}

private void unregisterOnlineChecker() {
    mContext.unregisterReceiver(mOnlineChecker);
}

private boolean isConnected() {
    boolean isMobile = false, isWifi = false;

    ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] infoAvailableNetworks = cm.getAllNetworkInfo();

    if (infoAvailableNetworks != null) {
        for (NetworkInfo network : infoAvailableNetworks) {

            if (network.getType() == ConnectivityManager.TYPE_WIFI) {
                if (network.isConnected() && network.isAvailable())
                    isWifi = true;
            }
            if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
                if (network.isConnected() && network.isAvailable())
                    isMobile = true;
            }
        }
    }

    return isMobile || isWifi;
}


/*========= INTERNET CHECK END ==========*/


private class OnlineTester extends AsyncTask<Void,Void,Boolean> {

    public OnlineTester() {

    }

    @Override
    protected Boolean doInBackground(Void[] p1) {
        boolean online = false;
        try {
            HttpURLConnection urlConnection = (HttpURLConnection)
                (new URL("http://clients3.google.com/generate_204")
                .openConnection());
            urlConnection.setRequestProperty("User-Agent", "Android");
            urlConnection.setRequestProperty("Connection", "close");
            urlConnection.setConnectTimeout(1500);
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 204 &&
                urlConnection.getContentLength() == 0) {
                //Log.d("Network Checker", "Successfully connected to internet");
                online = true;
            }
        } catch (IOException e) {
            online = false;
        }
        return online;
    }

    @Override
    protected void onPostExecute(Boolean online) {
        // TODO: Implement this method
        super.onPostExecute(online);
        if(online) {
            if(mWatcher != null) {
                mWatcher.Online();
            }
        }
    }
 }
};

您可能会注意到,该类中有一个接口。基本上,我想从我的Activity类之一中了解“活动的”互联网连接是否可用。因此,我在interface的{​​{1}}上方实现了以下内容:

Activity

现在,我们已经准备好出发了。因此,我让它从public class YourActivity extends Activity implements iChessNetwork.Watcher { private iChessNetwork mNetwork; @Override public void Online() { // It's online now - do your connection } 类的某个位置(通常在onCreate(),一个Android应用程序的起点)运行:

Activity

从这一点开始,我开始跟踪“活动的”互联网连接,并在不需要时停止跟踪(通常在mNetwork = new iChessNetwork(this, this); 的{​​{1}}和onBackPressed()方法中,像这样:

onDestroy()

希望这对您和其他人有帮助。