简体   繁体   中英

How to Restart Android IntentService

I have an intent service which is processing long running task. But while processing if an exception occurs lets say SocketTimeOutException the service stops. How to catch the exception and restart the process.

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        String name = intent.getStringExtra("name");
        String packageName = intent.getStringExtra("packageName");
        String path = intent.getStringExtra("path");
        int downloadedSoFar = 0;

        Intent i = new Intent(getApplicationContext(), DownloadListViewApp.class);
        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, i, 0);
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle(name)
                .setContentText("Download in progress")
                .setSmallIcon(R.drawable.logo).setContentInfo("0%").setContentIntent(pi);
        mBuilder.setOngoing(true);

        try {
            url = new URL(IPClass.SERVERIP + path + "/" + packageName);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setReadTimeout(7000);
            int fileLength = connection.getContentLength();
            connection.connect();

            input = connection.getInputStream();
            output = new FileOutputStream("/sdcard/Android/appdata/tmp/downloadtmp/" + packageName, true);

            byte data[] = new byte[1024];
            int count;

            boolean continueLoop = true;
            while ((count = input.read(data)) > 0 && continueLoop) {
                    progressChange((int) (downloadedSoFar * 100L) / fileLength, packageName);
                    downloadedSoFar = downloadedSoFar + count;
                    output.write(data, 0, count);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (output != null) output.close();
                if (input != null) input.close();
            } catch (IOException ignored) {
            }
            if (connection != null) {
                connection.disconnect();
            }
        }

Ref :- https://stackoverflow.com/a/12776012/2705391 You can use this for your problem.

@Override
protected void onHandleIntent(Intent intent)
{
    try
    {
        // STOP SERVICE

        // DO YOUR WORK HERE
    }
    finally
    {
        // START SERVICE
    }

}

You can't stop intent service till its duty has completed, if you want to stop it then you should have to stop alarm manager in intent service like this.

    Intent DataSyncing = new Intent(getBaseContext(), DataSyncingScheduledReceiver.class);
    DataSyncing.setAction(DataSyncingScheduledReceiver.ACTION_DATASYNC_RECEIVER);
    PendingIntent DataSyncingIntent = PendingIntent.getBroadcast(getBaseContext(),1003, DataSyncing, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarmManagerdatasync = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManagerdatasync.cancel(DataSyncingIntent);
    DataSyncingIntent.cancel();

I think restarting a servise is not a solution you should handle it in catch

put your code to call api inside seperate function supose your function is like callAPI()

} catch (final java.net.SocketTimeoutException e) {
    // connection timed out...let's try again   
    callAPI()   
}

This creates a recursion by this your api will be called n time untill your api will give SocketTimeoutException so you will not need to restart your IntentService. it will remain onrun until your api executed

if you want to prevent this you have to specify and implement logic of nuberofAttempts as in volley volley inbuilt has retry policy you should read about it. else i sugest volley or retrofit to use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM