不推荐使用ConnectivityManager.CONNECTIVITY_ACTION [英] ConnectivityManager.CONNECTIVITY_ACTION deprecated

查看:2021
本文介绍了不推荐使用ConnectivityManager.CONNECTIVITY_ACTION的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android N中,官方网站上提到针对Android N的应用不会收到CONNECTIVITY_ACTION广播".并且还提到了JobScheduler可以用作替代.但是JobScheduler不能提供与CONNECTIVITY_ACTION广播完全相同的行为.

In Android N, it is mentioned on the official website that "Apps targeting Android N do not receive CONNECTIVITY_ACTION broadcasts". And it is also mentioned that JobScheduler can be used as an alternative. But the JobScheduler doesn't provide exactly the same behavior as CONNECTIVITY_ACTION broadcast.

在我的Android应用程序中,我正在使用此广播了解设备的网络状态.我想在CONNECTIVITY_ACTION广播的帮助下了解此状态是CONNECTING还是CONNECTED,它最适合我的要求.

In my Android application, I was using this broadcast to know the network state of the device. I wanted to know if this state was CONNECTING or CONNECTED with the help of CONNECTIVITY_ACTION broadcast and it was best suited for my requirement.

现在已不赞成使用它,有人可以建议我获取当前网络状态的另一种方法吗?

Now that it is deprecated, can any one suggest me the alternative approach to get current network state?

推荐答案

不推荐使用后台应用程序接收网络连接状态更改的功能.

What will be deprecated is the ability for a backgrounded application to receive network connection state changes.

David Wasser 所述,如果实例化了应用程序组件(未销毁),您仍然可以获得有关连接更改的通知),并且您有

As David Wasser said you can still get notified of connectivity changes if the app component is instantiated (not destroyed) and you have registered your receiver programmatically with its context, instead of doing it in the manifest.

或者您可以改用 NetworkCallback .特别是,您将需要覆盖 onAvailable 用于更改连接状态.

Or you can use NetworkCallback instead. In particular, you will need to override onAvailable for connected state changes.

让我快速起草摘要:

public class ConnectionStateMonitor extends NetworkCallback {

   final NetworkRequest networkRequest;

   public ConnectionStateMonitor() {
       networkRequest = new NetworkRequest.Builder()
           .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
           .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
           .build();
   }

   public void enable(Context context) {
       ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
       connectivityManager.registerNetworkCallback(networkRequest, this);
   }

   // Likewise, you can have a disable method that simply calls ConnectivityManager.unregisterNetworkCallback(NetworkCallback) too.

   @Override
   public void onAvailable(Network network) {
       // Do what you need to do here
   }
}

这篇关于不推荐使用ConnectivityManager.CONNECTIVITY_ACTION的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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