Chaitanya Parashar
Chaitanya Parashar

Reputation: 742

how to continue service when device go to sleep?

I am new to android.I want to use my service for fetching the Json data from server.when I open my app then all works fine but when I exit my app or when my device go to sleep then there is a Json exception.how can I make my service run every-time in background. Please guide for solving this error.

error:-

     E/agdghdgdgdrgrdgrdg: dgdgd
     W/System.err: java.net.UnknownHostException: Unable to resolve host  
     "podgier-  
     woman.000webhostapp.com": No address associated with hostname
     W/System.err:     at         
     java.net.InetAddress.lookupHostByName(InetAddress.java:457)
     W/System.err:     at   
     java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
     W/System.err:     at 
     java.net.InetAddress.getAllByName(InetAddress.java:215)
     W/System.err:     at     
     org.apache.http.conn.DefaultClientConnectionOperator.openConnection
     (DefaultClientConnectionOperator.java:137)
     W/System.err:at org.apache.http.impl.conn.AbstractPoolEntry.open
     (AbstractPoolEntry.java:164)
     W/Systemerr:at 
     org.apache.http.impl.conn.AbstractPooledConnAdapter.open
     (AbstractPooledConnAdapter.java:119)
     W/System.err:     at    
     org.apache.http.impl.client.DefaultRequestDirector.execute
    (DefaultRequestDirector.java:360)
    W/System.err:at 
     org.apache.http.impl.client.AbstractHttpClient.execute
    (AbstractHttpClient.java:555)
    W/System.err:at  
    org.apache.http.impl.client.AbstractHttpClient.execute
   (AbstractHttpClient.java:487)
     W/System.err:at  
     org.apache.http.impl.client.AbstractHttpClient.execute
    (AbstractHttpClient.java:465)
    W/System.err:     at com.grover.jsonp.JSONParser.makeHttpRequest
   (JSONParser.java:62)
   W/System.err:at com.grover.jsonp.BackgroundService$gro.doInBackground
    (BackgroundService.java:50)
    W/System.err:     at   
    com.grover.jsonp.BackgroundService$gro.doInBackground
    (BackgroundService.java:41)
    W/System.err:at android.os.AsyncTask$2.call(AsyncTask.java:288)
    W/System.err:at java.util.concurrent.FutureTask.run
    (FutureTask.java:237)

   W/System.err:     at   
   android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
   W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker
   (ThreadPoolExecutor.java:1112)
   W/System.err:     at   

   java.util.concurrent.ThreadPoolExecutor
   $Worker.run(ThreadPoolExecutor.java:587)
   W/System.err:     at java.lang.Thread.run(Thread.java:818)
   W/System.err: Caused by: android.system.GaiException:     
   android_getaddrinfo    
   failed: EAI_NODATA (No address associated with hostname)
   W/System.err:     at libcore.io.Posix.android_getaddrinfo(Native   
   Method)
   W/System.err:     at   
   libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55) 
   W/System.err:     at     
   java.net.InetAddress.lookupHostByName(InetAddress.java:438)
   W/System.err:    ... 18 more
   E/Buffer Error: Error converting result java.io.IOException: Attempted  
   read   
   on closed stream.

BackgroundService.java

public class BackgroundService extends Service
{
public BackgroundService(){
}

private static String url ="https://podgier-woman.000webhostapp.com/table.php";
JSONParser jParser = new JSONParser();
ArrayList<String> bcv;

class gro extends AsyncTask<String, String, String> {
    protected void onPreExecute() {
        super.onPreExecute();

    }

    protected String doInBackground(String... args) {
        java.util.List<NameValuePair> pr = new ArrayList<NameValuePair>();

        JSONObject json = jParser.makeHttpRequest(url, "GET", pr);
        bcv = new ArrayList<String>();
        try {
            JSONArray code = json.getJSONArray("code");
            Log.d("list :",code.toString());
            for (int i = 0; i < code.length(); i++) {
                JSONObject c = code.getJSONObject(i);

                bcv.add(c.getString("name"));

                // adding each child node to HashMap key => value

                // adding contact to contact list
                JSONArray p = null;
            }
        }catch(JSONException e){

        }
        return null;

    }

    protected void onPostExecute(String file_url) {

        Log.v("sdg","sgfdg"+record.idName);

        if(record.idName < bcv.size()){
            int xx= bcv.size() - record.idName;

            Intent intent = new Intent(BackgroundService.this, record.class);

            PendingIntent pIntent = PendingIntent.getActivity(BackgroundService.this, (int) System.currentTimeMillis(),intent, 0);

            Log.d("SGsgzxv","dfgzdvv");
            Notification n = new Notification.Builder(getApplicationContext())
                    .setContentTitle("View "+xx+" updated data")
                    .setContentText("data pending ")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pIntent)
                    .setAutoCancel(true)

                    .addAction(R.mipmap.ic_launcher, "call", pIntent)
                    .addAction(R.mipmap.ic_launcher, "More", pIntent)
                    .addAction(R.mipmap.ic_launcher, "and more", pIntent)

                    .build();

            Uri so = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            n.sound = so;
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            nm.notify(0,n);
        }
        record.idName = bcv.size();
        bcv.clear();
    }
}

private static final String TAG = "BackgroundService";
private ThreadGroup myThreads = new ThreadGroup("ServiceWorker");


@Override
public void onCreate() {
    super.onCreate();
    Log.v(TAG, "in onCreate()");

}


@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    super.onStartCommand(intent, flags, startId);
    int counter = intent.getExtras().getInt("counter");



    Log.v(TAG, "in onStartCommand(), counter = " + counter +
            ", startId = " + startId);

    new Thread(myThreads, new ServiceWorker(counter), "BackgroundService")
            .start();


    return START_STICKY;
}


class ServiceWorker implements Runnable
{
    private int counter = -1;

    public ServiceWorker(int counter) {
        this.counter = counter;
    }

    public void run() {

        final String TAG2 = "ServiceWorker:" + Thread.currentThread().getId();
        // do background processing here...
        try {
            Log.e(TAG2, "sleeping for 5 seconds. counter = " + counter);

            while(true)
            {
                Thread.sleep(9000);
                Log.e("agdghdgdgdrgrdgrdg","dgdgd");
                new gro().execute();
            }
        } catch (InterruptedException e) {
            Log.e(TAG2, "... sleep interrupted");
        }
    }
}

@Override
public void onDestroy()
{

}
@Override
public IBinder onBind(Intent intent) {
    Log.v(TAG, "in onBind()");
    return null;
}
}

Upvotes: 2

Views: 256

Answers (1)

mrg
mrg

Reputation: 332

I don't recommend using a background service for such purposes. I know from experience that we are never sure that such a service will not be destroyed by the system.

To perform tasks (periodic, single) I recommend using Firebase Job Dispatcher. In my opinion, this is a more reliable mechanism when it comes to doing background work.

Here is an example of use, given by me: https://stackoverflow.com/a/44489327/8119117

Upvotes: 2

Related Questions