2

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;
}
}
Vishal Chhodwani
  • 2,567
  • 5
  • 27
  • 40
Chaitanya Parashar
  • 692
  • 2
  • 12
  • 21
  • Use `NOT_STICKY` service. – Piyush Aug 02 '17 at 07:35
  • 2
    I don't see any json exceptions, only `UnknownHostException`, which means that you app has no access to the internet when device sleeps. That may be caused by wifi is going to sleep mode, when device screen is off. You way want to acquire wakelock to prevent device from sleeping, but your users may hate you for your app draining battery this way, if you forget to release wakelock after you don't need it. – Vladyslav Matviienko Aug 02 '17 at 07:35
  • Can i solve this problem if i use mobile data?.if not then how other apps are using internet when it is going to sleep mode? @VladMatvienko – Chaitanya Parashar Aug 02 '17 at 07:42
  • I think it should work on mobile data. Other apps may acquire wakelock, and not let the device sleep deep. – Vladyslav Matviienko Aug 02 '17 at 08:01
  • I'm really really looking for a question like this – Bharat Aug 04 '17 at 06:05
  • keep in mind that sometimes our device do not grant permission to background activity because of power saving then we have to grant permission manually. – Chaitanya Parashar Aug 04 '17 at 06:19

1 Answers1

2

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

mrg
  • 322
  • 1
  • 5