import android.app.Service;

import android.content.Intent;

import android.os.AsyncTask;

import android.os.IBinder;

import android.util.Log;


import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;


public class BackgroundNetworkService extends Service {


    private static final String TAG = "BackgroundNetworkService";


    @Override

    public void onCreate() {

        super.onCreate();

        Log.d(TAG, "Service created");

    }


    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d(TAG, "Service started");


        // Perform network operation in a background thread

        new NetworkTask().execute();


        // Return START_STICKY to ensure the service restarts if it's killed by the system

        return START_STICKY;

    }


    @Override

    public IBinder onBind(Intent intent) {

        return null;

    }


    @Override

    public void onDestroy() {

        super.onDestroy();

        Log.d(TAG, "Service destroyed");

    }


    // Example AsyncTask to perform network operation

    private class NetworkTask extends AsyncTask<Void, Void, String> {


        @Override

        protected String doInBackground(Void... voids) {

            try {

                // Example: Perform a GET request to fetch data from a URL

                URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");

                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                try {

                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

                    StringBuilder stringBuilder = new StringBuilder();

                    String line;

                    while ((line = bufferedReader.readLine()) != null) {

                        stringBuilder.append(line).append("\n");

                    }

                    bufferedReader.close();

                    return stringBuilder.toString();

                } finally {

                    urlConnection.disconnect();

                }

            } catch (IOException e) {

                Log.e(TAG, "Error fetching data", e);

                return null;

            }

        }


        @Override

        protected void onPostExecute(String result) {

            // Handle the result here (update UI, save data, etc.)

            if (result != null) {

                Log.d(TAG, "Received data: " + result);

                // Example: Update UI or process data received from the network

            }

        }

    }

}


Comments