'WiFi disconnects in service runs in background when App goes in background in android

I am facing one issue that when app goes in background NetworkCapabilities shows null and gives following error and when app comes in foreground again it works fine. how to resolve this issue?

2022-04-30 18:32:42.378 27295-32157/com.example.nseoc W/System.err: java.net.UnknownHostException: Unable to resolve host "url//": No address associated with hostname
2022-04-30 18:32:42.378 27295-28940/com.example.nseoc I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
2022-04-30 18:32:42.379 27295-32157/com.example.nseoc W/System.err:     at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:124)
2022-04-30 18:32:42.379 27295-32157/com.example.nseoc W/System.err:     at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
2022-04-30 18:32:42.379 27295-32157/com.example.nseoc W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:1152)
2022-04-30 18:32:42.379 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.Dns$1.lookup(Dns.java:41)
2022-04-30 18:32:42.379 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
2022-04-30 18:32:42.379 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
2022-04-30 18:32:42.379 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
2022-04-30 18:32:42.379 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:192)
2022-04-30 18:32:42.379 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:144)
2022-04-30 18:32:42.379 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:106)
2022-04-30 18:32:42.379 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:400)
2022-04-30 18:32:42.380 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:333)
2022-04-30 18:32:42.380 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
2022-04-30 18:32:42.380 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
2022-04-30 18:32:42.380 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:90)
2022-04-30 18:32:42.380 27295-32157/com.example.nseoc W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:30)
public class GoogleService extends JobService {

@Override
    public void onDestroy() {
         stopped = true;
        super.onDestroy();

@Override
    public boolean onStartJob(JobParameters jobParameters) {
        Log.i("Demo", "Thread id: "+Thread.currentThread().getId()+", Time: "+ new Date()+" OnStartJob");
       
        doBackgroundWork();
        return true;
    }

    private void doBackgroundWork() {

        new Thread((Runnable) ()->{
            InputStream inputStream;
            Log.i("Demo", "Thread id: "+Thread.currentThread().getId()+", Time: "+ new Date()+" Runnable");
            String wWebsite = "http://www.google.com";
            isServiceOn = true;
            while (isServiceOn){
                try {
                    ConnectivityManager connectivityManager = (ConnectivityManager)getApplicationContext().getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
                    NetworkCapabilities capabilities  = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
                    boolean isAvailable = false;

                    if (capabilities!=null){
                        if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
                            isAvailable = true;
                        }

                    }

                    URL googleUrl = new URL(wWebsite);
                    HttpsURLConnection connection=(HttpsURLConnection)googleUrl.openConnection();
                    connection.setReadTimeout(10000);
                    connection.setConnectTimeout(20000);
                    connection.setRequestProperty("Content-length", "0");
                    connection.setUseCaches(false);
                    connection.setAllowUserInteraction(false);
                    connection.setRequestMethod("GET");
                    connection.connect();
                    Log.i("Demo", "Thread id: "+Thread.currentThread().getId()+", Time: "+ new Date()+" Ineternet connection");

                    if (connection.getResponseCode()==201||connection.getResponseCode()==200){
                        // Do data parsing and processing 
                    }



                    Thread.sleep(60000);

                    Log.i("Demo", "Thread id: "+Thread.currentThread().getId()+", Time: "+ new Date()+" DoBackgroundwork");
                } catch (InterruptedException | IOException | JSONException | ParseException e) {
                    e.printStackTrace();
                }
            }
            
        }).start();
}

   @Override
    public boolean onStopJob(JobParameters jobParameters) {
        Log.i("Demo", "Thread id: "+Thread.currentThread().getId()+", Time: "+ new Date()+" OnStopJob");
        Intent broadcastIntent = new Intent("my.custom.action.restart");
        broadcastIntent.putExtra("stop",false);
        sendBroadcast(broadcastIntent);
     
        return true;
    }



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source