简体   繁体   English

android如何获取指示何时互联网连接丢失?

[英]android how to get indicate when the internet connection is lost?

I'm developing an android application and I want to get a notification when the internet (wifi or packet data connection) connection is lost. 我正在开发一个Android应用程序,我希望在互联网(wifi或分组数据连接)连接丢失时收到通知。 On my approach I can get the status of the connection as: 在我的方法中,我可以获得连接的状态:

private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

while having this in the Manifest: 在Manifest中有这个:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How could I be notified automatically when the connection is lost? 如何在连接丢失时自动通知我?

For WIFI you could register a broadcast receiver as: 对于WIFI,您可以将广播接收器注册为:

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);

You can also register the receiver in the Manifest. 您也可以在Manifest中注册接收器。

Then in your receiver: 然后在你的接收器中:

@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
        if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)){
            //do stuff
        } else {
            // wifi connection was lost
        }
    }
}

For any type of data connection listeners you could use the following receiver registered as: 对于任何类型的数据连接侦听器,您可以使用以下接收器注册为:

<receiver android:name=".receiver.ConnectivityReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
    </intent-filter>
</receiver>

and the in your ConnectivityReceiver : 和你的ConnectivityReceiver

public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
    }
}

In the onReceive method you could check if you have internet connectivity or not using this developer article . onReceive方法中,您可以使用此开发人员文章检查您是否具有Internet连接。

use following code: 使用以下代码:

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

public class NetworkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(final Context context, final Intent intent) {

            boolean IsConnected = NetworkUtil.getConnectivityStatusString(context);
           // Toast in here, you can retrieve other value like String from NetworkUtil
           // but you need some change in NetworkUtil Class
        }
    }

and NetworkUtil is: NetworkUtil是:

package classes;

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

public class NetworkUtil {

    public static int TYPE_WIFI = 1;
    public static int TYPE_MOBILE = 2;
    public static int TYPE_NOT_CONNECTED = 0;


    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        } 
        return TYPE_NOT_CONNECTED;
    }

    public static boolean getConnectivityStatusString(Context context) {
        int conn = NetworkUtil.getConnectivityStatus(context);
        boolean status = false ;
        if (conn == NetworkUtil.TYPE_WIFI) {
            status = true;
        } else if (conn == NetworkUtil.TYPE_MOBILE) {
            status = true; 
        } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
            status = false;
        }
        return status;
    }
}

and in manifest file: 并在清单文件中:

 <receiver
            android:name="receiver.NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

and this permission: 和这个权限:

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

You need to set up a broadcast receiver. 您需要设置广播接收器。

Add these as intent filters. 将这些添加为意图过滤器。

            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>

You should use BroadcastReceivers for your requirement. 您应该根据您的要求使用BroadcastReceivers Create a BroadcastReceiver which listen for network changes. 创建一个侦听网络更改的BroadcastReceiver。

Incase of any change in the network it will automatically fire the event and you can perform your operations regarding it. 如果网络发生任何变化,它将自动触发事件,您可以执行相关操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当 android 中的 Internet 连接丢失时通知用户 - Notify user when Internet connection is lost in android Android中如何处理没有互联网和丢失的连接? - How to handle with no Internet and lost connection in Android? 在 Android 上设置 Charles 代理时 Internet 连接丢失 - Internet Connection lost when setting Charles proxy on Android 当失去互联网连接时,如何将数据存储在列表中并重新发送 - when internet connection is lost how do store the data in a list and resend 当Android中有互联网连接时,如何首先通知应用程序? - How to make an application first get notifed when there is internet connection in Android? android可以区分丢失的互联网连接和没有互联网连接吗? - Can android differentiate between a lost internet connection and no internet connect? 当android有互联网连接时如何建议 - How to be advised when android has internet connection 断开Internet连接时,请妥善处理NPE并在OnPostExecute / AsyncTask中显示AlertDialog-Android / Java - Handle NPE Gracefully and Display AlertDialog in OnPostExecute / AsyncTask When Internet Connection Is Lost - Android / Java 当WIFI打开但没有数据连接时,如何在android中检查互联网连接? - How to check the Internet connection in android when WIFI is On but No Data Connection? 如何在Android中检测WiFi接入点是否刚刚失去互联网连接 - How to detect if WiFi access point has just lost internet connection in Android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM