0

Basically what I want to have happen is for the service to run and spawn the http request in the background (Hence the Async task). I want the service to stop when there is an error with the connection. This will only run on the LAN and stop and restart when prompted from main with a new ip address and stop when the user exits the app.

I can make the service start and stop and update the ip just fine. The trouble comes when the ip address is no longer reachable. I get the errors, I catch them. I destroy the service and it just keeps on going...like a zombie...with indestructible limbs and a hunger for stupidity

Here is the service:

public class fanInfoService extends Service {

public String _ip = null;
public String _stopService = null;
public Long _startTime = (long) 0;

public fanInfoService() {
    super();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{ 
// get information from intent
  Bundle b = intent.getExtras();
  _ip = b.getString("ip");
  _stopService = b.getString("STOP");
  _startTime = b.getLong("startTime");


  if(_stopService != null){
      alarmCancel();
      onDestroy();
      System.out.println("stopping due to stopService");

  }else{
      //else set stopService to null and run as usual
      //_stopService = null;
      System.out.println("onhandle called again with " + _ip);
      try{
          new RequestTask().execute("http://"+ _ip +"/fanspd.cgi");
      }catch(RuntimeException e){
          System.out.println("we caught an error");
      }
     // RequestTask("http://"+ _ip +"/fanspd.cgi");
  }

  return START_NOT_STICKY;
}

@Override
public void onDestroy(){
  //if we want to stop service come here

  super.onDestroy();
  //super.stopSelf();
  System.out.println("Here we are stopping things on Destroy");

} 

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

private void scheduleNextUpdate()
{
Intent intent = new Intent(this, this.getClass());
Bundle b = new Bundle();
b.putString("ip", _ip);
b.putLong("startTime", _startTime);
intent.putExtras(b);

PendingIntent pendingIntent =
    PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);


// The update frequency should often be user configurable.  This is not.

long currentTimeMillis = System.currentTimeMillis();
long nextUpdateTimeMillis = currentTimeMillis + 2500;
Time nextUpdateTime = new Time();
nextUpdateTime.set(nextUpdateTimeMillis);

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

//Also stop if the signal comes to stop

if(_stopService != null){
    if(_stopService.equals("stop")){
        System.out.println("here I am Stopping the Refresh Thread " + _stopService);
        alarmCancel();
        onDestroy();
    }else{
        System.out.println("Somthings wrong in fanService _stopService");
    }
}else{
    //alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
    System.out.println("Here we set the repeat call");
    alarmManager.setInexactRepeating(AlarmManager.RTC, nextUpdateTimeMillis, 30, pendingIntent);
}
}

//Here is the async class to send http request
public class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            System.out.println("Client Side Error");
            e.printStackTrace();
            runErrorCode();
            return null;
        } catch (IOException e) {
            System.out.println("I-O side Error");
            e.printStackTrace();
            runErrorCode();
            onDestroy();
            return null;
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..

        //Take response and send back to Main for parseHTTP via intent
        Intent intent = new Intent("com.example.airscapefancontroller.android.action.broadcast");
        //System.out.println("Here is results " + result);
        Bundle extras = new Bundle();  
        extras.putString("RESULT", result);
        extras.putString("REFRESH", null);
        intent.putExtras(extras);

        sendBroadcast(intent);
        scheduleNextUpdate();
        onDestroy();
        System.out.println("I just posted results");

    }
}

  private void runErrorCode(){
      Intent intent = new Intent("com.example.airscapefancontroller.android.action.broadcast");
        //send a signal back to reset the stats
        Bundle extras = new Bundle();  
      extras.putString("RESULT", "refresh");
      intent.putExtras(extras);

      System.out.println("Here we are in error code ");
     // alarmCancel();
      sendBroadcast(intent);
      stopSelf();
      onDestroy();

  }


    private void alarmCancel(){
        Intent intent = new Intent(this, this.getClass());
        Bundle b = new Bundle();
        b.putString("ip", _ip);
        b.putLong("startTime", _startTime);
        intent.putExtras(b);

        PendingIntent pendingIntent =
            PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        alarmManager.cancel(pendingIntent);
        pendingIntent.cancel();
        onDestroy();
        System.out.println("We canceled the service and alarm");
    }

Here is the LogCat the device leaves the network:

07-09 18:27:56.195: I/System.out(13375): we caught an error
07-09 18:27:56.250: I/System.out(13375): onhandle called again with 10.0.0.29
07-09 18:27:56.250: I/System.out(13375): we caught an error
07-09 18:27:56.257: I/System.out(13375): onhandle called again with 10.0.0.29
07-09 18:27:56.261: I/System.out(13375): we caught an error
07-09 18:27:56.281: I/System.out(13375): onhandle called again with 10.0.0.29
07-09 18:27:56.281: I/System.out(13375): we caught an error
07-09 18:27:56.312: I/System.out(13375): onhandle called again with 10.0.0.29
07-09 18:27:56.312: I/System.out(13375): we caught an error
07-09 18:27:56.343: I/System.out(13375): onhandle called again with 10.0.0.29
07-09 18:27:56.343: I/System.out(13375): we caught an error
07-09 18:27:56.378: I/System.out(13375): onhandle called again with 10.0.0.29
07-09 18:27:56.378: I/System.out(13375): we caught an error
07-09 18:27:56.402: I/System.out(13375): onhandle called again with 10.0.0.29
07-09 18:27:56.402: I/System.out(13375): we caught an error
07-09 18:27:56.414: I/System.out(13375): I-O side Error
07-09 18:27:56.414: W/System.err(13375): org.apache.http.conn.ConnectTimeoutException:     Connect to /10.0.0.29:80 timed out
07-09 18:27:56.414: W/System.err(13375):    at     org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)
07-09 18:27:56.414: W/System.err(13375):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159)
07-0 9 18:27:56.414: W/System.err(13375):   at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-09 18:27:56.414: W/System.err(13375):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-09 18:27:56.414: W/System.err(13375):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
07-09 18:27:56.417: I/System.out(13375): I-O side Error
07-09 18:27:56.417: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-09 18:27:56.417: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-09 18:27:56.417: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-09 18:27:56.417: W/System.err(13375):    at com.example.airscapefancontroller.fanInfoService$RequestTask.doInBackground(fanInfoService.java:137)
07-09 18:27:56.417: W/System.err(13375):    at com.example.airscapefancontroller.fanInfoService$RequestTask.doInBackground(fanInfoService.java:1)
07-09 18:27:56.417: W/System.err(13375):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
07-09 18:27:56.417: W/System.err(13375):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
07-09 18:27:56.417: W/System.err(13375):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
07-09 18:27:56.417: W/System.err(13375):    at   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
07-09 18:27:56.417: W/System.err(13375):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
07-09 18:27:56.421: W/System.err(13375):    at java.lang.Thread.run(Thread.java:1019)
07-09 18:27:56.421: I/System.out(13375): Here we are in error code 
07-09 18:27:56.437: W/System.err(13375): org.apache.http.conn.ConnectTimeoutException: Connect to /10.0.0.29:80 timed out
07-09 18:27:56.441: I/System.out(13375): onhandle called again with 10.0.0.29
07-09 18:27:56.441: I/System.out(13375): we caught an error
07-09 18:27:56.449: W/System.err(13375):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)
07-09 18:27:56.457: I/System.out(13375): I-O side Error
07-09 18:27:56.460: W/System.err(13375): org.apache.http.conn.ConnectTimeoutException: Connect to /10.0.0.29:80 timed out
07-09 18:27:56.460: I/System.out(13375): onhandle called again with 10.0.0.29
07-09 18:27:56.460: I/System.out(13375): we caught an error
07-09 18:27:56.464: I/System.out(13375): Here we are stopping things on Destroy
07-09 18:27:56.468: I/System.out(13375): Here we are stopping things on Destroy
07-09 18:27:56.468: I/System.out(13375): Here we are stopping things on Destroy
07-09 18:27:56.472: I/System.out(13375): Here we set the repeat call
07-09 18:27:56.472: I/System.out(13375): Here we are stopping things on Destroy
07-09 18:27:56.472: I/System.out(13375): I just posted results
07-09 18:27:56.472: W/System.err(13375):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)
07-09 18:27:56.472: W/System.err(13375):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159)
07-09 18:27:56.476: W/System.err(13375):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-09 18:27:56.480: I/System.out(13375): I-O side Error
07-09 18:27:56.480: W/System.err(13375):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-09 18:27:56.484: W/System.err(13375): org.apache.http.conn.ConnectTimeoutException: Connect to /10.0.0.29:80 timed out
07-09 18:27:56.484: W/System.err(13375):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159)
07-09 18:27:56.484: W/System.err(13375):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)
07-09 18:27:56.484: W/System.err(13375):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159)
07-09 18:27:56.488: W/System.err(13375):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-09 18:27:56.488: W/System.err(13375):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-09 18:27:56.488: W/System.err(13375):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
07-09 18:27:56.488: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-09 18:27:56.488: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-09 18:27:56.488: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-09 18:27:56.488: W/System.err(13375):    at com.example.airscapefancontroller.fanInfoService$RequestTask.doInBackground(fanInfoService.java:137)
07-09 18:27:56.488: W/System.err(13375):    at com.example.airscapefancontroller.fanInfoService$RequestTask.doInBackground(fanInfoService.java:1)
07-09 18:27:56.492: W/System.err(13375):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
07-09 18:27:56.496: W/System.err(13375):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
07-09 18:27:56.496: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-09 18:27:56.496: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-09 18:27:56.496: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-09 18:27:56.496: W/System.err(13375):    at com.example.airscapefancontroller.fanInfoService$RequestTask.doInBackground(fanInfoService.java:137)
07-09 18:27:56.500: W/System.err(13375):    at com.example.airscapefancontroller.fanInfoService$RequestTask.doInBackground(fanInfoService.java:1)
07-09 18:27:56.500: W/System.err(13375):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
07-09 18:27:56.503: W/System.err(13375):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
07-09 18:27:56.507: W/System.err(13375):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
07-09 18:27:56.511: I/System.out(13375): I-O side Error
07-09 18:27:56.519: W/System.err(13375):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
07-09 18:27:56.523: W/System.err(13375):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
07-09 18:27:56.523: W/System.err(13375):    at java.lang.Thread.run(Thread.java:1019)
07-09 18:27:56.523: I/System.out(13375): Here we are in error code 
07-09 18:27:56.523: W/System.err(13375):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-09 18:27:56.527: W/System.err(13375):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-09 18:27:56.527: W/System.err(13375):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
07-09 18:27:56.527: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-09 18:27:56.527: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-09 18:27:56.527: W/System.err(13375):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-09 18:27:56.527: W/System.err(13375):    at com.example.airscapefancontroller.fanInfoService$RequestTask.doInBackground(fanInfoService.java:137)
07-09 18:27:56.527: W/System.err(13375):    at com.example.airscapefancontroller.fanInfoService$RequestTask.doInBackground(fanInfoService.java:1)
07-09 18:27:56.531: W/System.err(13375):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
07-09 18:27:56.531: W/System.err(13375):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
07-09 18:27:56.550: W/System.err(13375):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)

Thanks to Kaifei for the help. I grant the answer to you for breaking my coders block around the issue.

In case anyone has a similar issue this post was very helpful to me.

lq=1Helpful entry

I basically changed my whole service back to an IntentService and instantiating a global public static volatile boolean and setting it to shouldContinue = true;

This boolean dictates how and when recalls occur. It works perfectly

Community
  • 1
  • 1
FujiRoyale
  • 762
  • 10
  • 26
  • Welcome to Stack Overflow! Can you reduce your program to something simpler that still shows the problem? – user3553031 Jul 10 '14 at 01:55
  • Sure. The onStartCommand basically checks if I started the service with a string indicating stop. If not then run new RequestTask().execute("http://"+ _ip +"/fanspd.cgi"); (I placed that in a try catch branch to catch the error I get when the device is unplugged) After the async executes I post results back to the UI thread via a broadcast receiver and onPostEcecute. This all works fine if the IP I use in the new RequestTask().execute("http://"+ _ip +"/fanspd.cgi"); is live. If that disappears the system totall – FujiRoyale Jul 10 '14 at 02:12

2 Answers2

0

A service should terminate itself by calling the stopSelf() method. onDestroy() is called by Android OS.

Ref: http://www.vogella.com/tutorials/AndroidServices/article.html#service_stop

Kaifei
  • 1,568
  • 2
  • 13
  • 16
  • One would think but unfortunately it only feeds the beast. :) I do call onDestroy in multiple places but still nothing. This is a real stumper for me. So far as I can tell the service stops but a system loop keeps going. – FujiRoyale Jul 10 '14 at 02:27
  • Did you bind to the service (by calling bindService()) or start the service (by calling startService())? – Kaifei Jul 10 '14 at 02:32
  • I wish I had. I never expressly call bindService(). :( – FujiRoyale Jul 10 '14 at 02:36
  • Oh apparently you called startService(). So why you don't stop the service using stopSelf() as the official documentation says: http://developer.android.com/guide/components/services.html#Stopping – Kaifei Jul 10 '14 at 02:37
  • The other strange thing is that I can get the service to stop when I close out of my app and send a signal to the service to stop. without calling unBind() – FujiRoyale Jul 10 '14 at 02:38
  • I've tried and thought onDestroy sounded more fierce. :) – FujiRoyale Jul 10 '14 at 02:38
  • Actually, after looking at your post, is it possible that I could be spooling up multiple services? As another thought how to I get my service ID? – FujiRoyale Jul 10 '14 at 02:39
  • onDestroy() will not terminate the service, it is a callback function that lets Android OS inform you the service is being destroyed. http://developer.android.com/reference/android/app/Service.html#onDestroy() – Kaifei Jul 10 '14 at 02:41
  • Thank you. I switched all calls to onDestroy to stopSelf(). Still the same behavior. I also added a check to see if the service is running and stop it before spooling another. and still the service runs itself into a frenzy when the http returns an error. – FujiRoyale Jul 10 '14 at 04:22
  • :( Then I have no idea.. You shouldn't accept my answer and let other people look at it. Good luck! – Kaifei Jul 14 '14 at 03:20
0

In case anyone has a similar issue this post was very helpful to me.

Helpful entry

I basically changed my whole service back to an IntentService and instantiating a global public static volatile boolean and setting it to shouldContinue = true;

This boolean dictates how and when recalls occur. It works perfectly

Community
  • 1
  • 1
FujiRoyale
  • 762
  • 10
  • 26