Detect CONNECTIVITY CHANGE in Android 7 and above when app is killed/in background

后端 未结 5 1662
礼貌的吻别
礼貌的吻别 2020-11-27 12:56

Problem:

So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other inf

5条回答
  •  萌比男神i
    2020-11-27 13:24

    Another approach which is simpler and easier when you use registerNetworkCallback (NetworkRequest, PendingIntent):

    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
    builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
    builder.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
    
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    Intent intent = new Intent(this, SendAnyRequestService.class);
    
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    if (connectivityManager != null) {
        NetworkRequest networkRequest = builder.build();
        connectivityManager.registerNetworkCallback(networkRequest, pendingIntent);
    }
    

    Which is SendAnyRequestService.class is your service class, and you can call your API inside it.

    This code work for Android 6.0 (API 23) and above

    Ref document is here

提交回复
热议问题