Android 确定并监控连接状态

Some of the most common uses for repeating alarms and background services is to schedule regular updates of application data from Internet resources, cache data, or execute long running downloads. But if you aren't connected to the Internet, or the connection is too slow to complete your download, why bother waking the device to schedule the update at all?

翻译:没网的话,没必要do work

You can use the ConnectivityManager to check that you're actually connected to the Internet, and if so, what type of connection is in place.

翻译:可以用ConnectivityManager检查网络状态

 

Determine if you have an internet connection

确定是否有网

 

There's no need to schedule an update based on an Internet resource if you aren't connected to the Internet. The following snippet shows how to use the ConnectivityManager to query the active network and determine if it has Internet connectivity.

下面示例如何查看网络状态

 

ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();

 

Determine the type of your internet connection

确定网络连接类型

It's also possible to determine the type of Internet connection currently available.

Device connectivity can be provided by mobile data, WiMAX, Wi-Fi, and ethernet connections. By querying the type of the active network, as shown below, you can alter your refresh rate based on the bandwidth available.

可以确定现在的网络连接类型。可以根据网络类型,来确定刷新频率

 

boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

 

Mobile data costs tend to be significantly higher than Wi-Fi, so in most cases, your app's update rate should be lower when on mobile connections. Similarly, downloads of significant size should be suspended until you have a Wi-Fi connection.

翻译:流量费比较高,所以要尽量在wifi下work

 

Having disabled your updates, it's important that you listen for changes in connectivity in order to resume them once an Internet connection has been established.

翻译:主要监听 网络连接的变化,没网的时候不干活,在有网的时候要接着干活。

 

Monitor for changes in connectivity

监听网络变化

 

Apps targeting Android 7.0 (API level 24) and higher do not receive CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver in their manifest. Apps will still receive CONNECTIVITY_ACTION broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

Andorid 7.0后清单文件中的广播接收器不再接收广播。动态注册的就还可以。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值