Android:如何在api级别28的应用程序级别监视网络更改

时间:2019-08-28 06:17:01

标签: android broadcastreceiver jobservice android-connectivitymanager

我是否需要使用Brodacast接收器,但是这里的问题是每次我注册它时都会被调用。如果我使用工作服务,我会在每次活动中安排它。相同的是,我希望在应用程序级别使用一个互联网列表器,仅在网络状态更改时才被调用。怎么做?

下面是我完成的代码

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class ConnectionStateMonitor extends ConnectivityManager.NetworkCallback {

    private static final String TAG = "ConnectionStateMonitor";
    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) {
        Log.d(TAG,"internet is connected");
        // Do what you need to do here
    }
}

问题是上述代码是我启用它后一直都在调用它

0 个答案:

没有答案