机器人如何获得指示何时丢失了互联网连接? [英] android how to get indicate when the internet connection is lost?

查看:109
本文介绍了机器人如何获得指示何时丢失了互联网连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个Android的应用程序,我希望得到一个通知,当互联网(WiFi或分组数据连接)连接丢失。在我的方法,我可以得到的连接,状态:

I'm developing an android application and I want to get a notification when the internet (wifi or packet data connection) connection is lost. 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:

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

我怎么会被自动通知时,连接丢失?

How could I be notified automatically when the connection is lost?

推荐答案

有关WIFI,你可以注册一个广播接收器为:

For WIFI you could register a broadcast receiver as:

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

您也可以注册清单中的接收器。

You can also register the receiver in the Manifest.

然后在您的接收器:

@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>

和您的 ConnectivityReceiver

public class ConnectivityReceiver extends BroadcastReceiver {

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

的onReceive 方法,你可以检查,如果您有互联网连接,或不使用的这个开发商文章

In the onReceive method you could check if you have internet connectivity or not using this developer article.

这篇关于机器人如何获得指示何时丢失了互联网连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆