András Ujvári András Ujvári - 1 month ago 23
Android Question

Android: Repeated HTTP requests

What is the easiest way to make a repeated HTTP request (i.e every 45 min) ?
I dont want to use any push up notifications
I've already tried AlarmManager, but it didn't work.
Forground Service can be good way, but it might may consume too much battery.

Answer

Call this metod from your MainActivity:

private void setNotifyAlarm() {
        long _alarm;
        Calendar now = Calendar.getInstance();
        Calendar wakeupcall = Calendar.getInstance();
        wakeupcall.setTimeInMillis(System.currentTimeMillis());
        wakeupcall.set(Calendar.HOUR_OF_DAY, 15);
        wakeupcall.set(Calendar.MINUTE, 30);

        if (wakeupcall.getTimeInMillis() <= now.getTimeInMillis())
            _alarm=wakeupcall.getTimeInMillis() + (AlarmManager.INTERVAL_DAY+1);
        else
            _alarm=wakeupcall.getTimeInMillis();


        al = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        notif= new Intent(this,NotifyService.class);
        fintent = PendingIntent.getService(this,0,notif,0);
        al.setRepeating(AlarmManager.RTC_WAKEUP,_alarm,"45 minutes in Miliseconds", fintent);

Create Service for http requuest: NotifyService.java

public class NotifyService extends Service {


    private NotificationManager mNotificationManager;
    PowerManager powerManager;
    PowerManager.WakeLock wakeLock;

    @Override
    public void onCreate() {
        super.onCreate();
        powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NOTIFY");

    }

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

    private void handleSERVICE(Intent intent){
        new NotifyTASK().execute();
    }

    private class NotifyTASK extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            {
            DO your HTTP CALLS

            }
            stopSelf();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }

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

    @Override
    public void onDestroy() {
        wakeLock.release();
    }
}

Now add this in Manifest file:

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
 <uses-permission android:name="android.permission.WAKE_LOCK"/>

<service android:name=".NotifyService" android:exported="true" android:enabled="true"/>

This code start service at specified time intervals. Hope this help you, if you need more code then tell me.