Search code examples
androiddeviceshutdownandroid-intentserviceapplication-shutdown

IntentService onHandleIntent behaviour on device shutdown


What would be the behaviour of onHandleIntent on device shutdown?

I know on IntentService, the service keeps running as long as onHandleIntent didn't finish its job.

so coming to think about it its a general question about services behaviour on device shutdown, will they "wake" up once we start up the device again?

if not, theres a way to do so? I want my intentservice to keep running until onHandleIntent finished, no matter what happened.

EDIT: I will add my code for better understanding. I'm trying to save request on SQLite and keep running until that table is empty, then the service will shut down. so incase of device shutdown, I will still continue from the same spot I was before the shudown. P.S - I try to use executor for better performances (its a test and not proven yet) and if someone got better suggestion I’d love to hear them cause Im new in this subject

onHandleIntent

@Override
protected void onHandleIntent(Intent intent) {
    helper = new DBHelper(getApplicationContext());
    executor = Executors.newFixedThreadPool(5);
    File file;
    Log.e("requestsExists",helper.requestsExists()+"");
    while (helper.requestsExists()) {
        ArrayList<String> requestArr = helper.getRequestsToExcute(5);
        //checks if the DB requests exists
        if (!requestArr.isEmpty()) {
            //execute them and delete the DB entry
            for(int i = 0; i < requestArr.size(); i++) {
                file = new File(requestArr.get(i));

                Log.e("file",file.toString());
                Future<String> future = executor.submit(new MyThread(file,getApplicationContext()));

                Log.e("future object", future.toString());
                try {
                    long idToDelete = Long.parseLong(future.get());
                    Log.e("THREAD ANSWER", future.get() + "");
                    helper.deleteRequest(idToDelete);
                } catch (InterruptedException e) {
                    Log.e("future try", "");
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    executor.shutdown();
}

MyThread

public class MyThread implements Callable {

    private File _file;
    private Context context;
    private DBHelper helper;

    public MyThread(File file, Context context) {
        this._file = file;
        this.context = context;
    }

    @Override
    public String call() throws Exception {
        HttpClient client = Utility.getNewHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost post = new HttpPost("http://192.168.9.62/mobile_api/timeline/moment/upload");
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            FileBody fileBody = new FileBody(_file);
            builder.addPart("content", fileBody);
            builder.addPart("type", new StringBody("file", ContentType.TEXT_PLAIN));
            builder.addPart("title", new StringBody("service test", ContentType.TEXT_PLAIN));
            builder.addPart("userType", new StringBody("user", ContentType.TEXT_PLAIN));
            builder.addPart("uid", new StringBody(MyInfiActivity.friends_uid, ContentType.TEXT_PLAIN));
            builder.addPart("momentId", new StringBody("1", ContentType.TEXT_PLAIN));
            builder.addPart("storyId", new StringBody("8", ContentType.TEXT_PLAIN));
            Utility.addCookiesToPost(post);

            post.setEntity(builder.build());
            client.execute(post, localContext);
        } catch (IOException e) {
            Log.e("Callable try", post.toString());
        }
        return "1";
    }
}

Solution

  • I'll try to go point by point to answer your question

    What would be the behaviour of onHandleIntent on device shutdown?

    Since the device is going to be totaly turned off, all services will be forced and stopped including your IntentService.
    You can subscrive to ACTION_SHUTDOWN to know when the device is going to be turned off and do some stuff before it actually goes off.

    public class ShutdownHandlerReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            //Handle here, but don't make actions that takes too long
        }    
    }
    

    Also you will have to add this to the manifest

    <receiver android:name=".ShutdownHandlerReceiver">
      <intent-filter>
        <action android:name="android.intent.action.ACTION_SHUTDOWN" />
      </intent-filter>
    </receiver>
    

    Will they "wake" up once we start up the device again?

    No they will not, because they have already disposed and stuff like that, but you can subscribe to ACTION_BOOT_COMPLETED to know when the device is ready. From the doc:

    Broadcast Action: This is broadcast once, after the system has finished booting. It can be used to perform application-specific initialization, such as installing alarms. You must hold the RECEIVE_BOOT_COMPLETED permission in order to receive this broadcast.

       public class BootedReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            //Handle here, you can start again your stopped intentservices
        }    
    }
    

    And in the manifest:

    <receiver android:name=".BootedReceiver">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
      </intent-filter>
    </receiver>
    

    And then you can restart the quee of your intenter service, and I guess this is the best way to go for it.