1

I read several threads about repeat asynchronous tasks in background, I first used this way: https://stackoverflow.com/a/6532298 but for some reasons, it seems that after sometime (several hours), it stopped.

So, now I am using this way, but I don't know if this is a good way to proceed:

BroadcastReceiver

public class RetrieveDataTaskBroadcast extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        SharedPreferences mSharedPreferences = context.getSharedPreferences(MY_PREF, 0);
        int delayInMs = mSharedPreferences.getInt("set_delay_refresh", 20)*60*1000; 
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, RetrieveDataService.class);
        PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
        am.cancel(pi);
        if (delayInMs > 0) {
            am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    SystemClock.elapsedRealtime() + delayInMs,
                    delayInMs, pi);
        }
    }

}

My service class:

public class RetrieveDataService extends Service implements OnRefreshInterface {

    private Context context;
    private PowerManager.WakeLock mWakeLock;
    private static final String TAG = "REFRESH_SERVICE";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void handleIntent(Intent intent) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        mWakeLock.acquire();

        //do the work
       callAsynchronousTask();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handleIntent(intent);
        return START_NOT_STICKY;
    }

    public void onDestroy() {
        super.onDestroy();
        mWakeLock.release();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        callAsynchronousTask();
    }

    public void callAsynchronousTask() {
        //My asynchronous task => execute a class that extends AsyncTask
        [...]
    }

    @Override
    public void onRefreshInterface(int cb_val1, int cb_val2) {
        //Callback when refresh is done
        [...]
    }
}

androidmanifest.xml:

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

...
    <service
        android:name="com.example.package.RetrieveDataService"
        android:enabled="true"
        android:label="Refresh Data">
    </service>

    <receiver
        android:name="com.example.package.RetrieveDataTaskBroadcast"
        android:enabled="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        </intent-filter>
    </receiver>

I also added a way to launch the service when the app starts: MainActivity:

@Override
    protected void onResume() {
        super.onResume();
        Thread t = new Thread(){
            public void run(){
                SharedPreferences mSharedPreferences = getSharedPreferences(PREF, 0);
                int delayInMs = mSharedPreferences.getInt("set_delay_refresh", 20)*60*1000; 
                AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                Intent i = new Intent(MainBaseActivity.this, RetrieveDataService.class);
                PendingIntent pi = PendingIntent.getService(MainBaseActivity.this, 0, i, 0);
                am.cancel(pi);
                am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                            SystemClock.elapsedRealtime() + delayInMs,
                            delayInMs, pi);
            }
        };
        t.start();
    }

Thank you for your help and advice.

Community
  • 1
  • 1
Thomas
  • 54
  • 5
  • Why are you creating a service when you can execute async tasks repeatedly with alarm manager – Passiondroid Jul 18 '15 at 06:43
  • I don't really know how to proceed to launch the repeated task when the device starts. That is why I use a service which is called by the BroadcastReceiver. – Thomas Jul 18 '15 at 07:05

1 Answers1

1

You dont need a service to launch the repeated task when the device starts. Your task will never run when the device is off.

You can set a repeating alarm using Alarm Manager. If the trigger time you specify is in the past when the device was off, the alarm triggers immediately when the device turns on.

Check this - https://developer.android.com/training/scheduling/alarms.html

Passiondroid
  • 1,573
  • 1
  • 16
  • 28