androidandroid-powermanager

Android updating file in background


I have a link, that allows me to download a calendar file (which can change). I want to re-download this file in the background to see if there is a change in relation to the last and send notification (I have to do some other stuff if an event doesn't exist any more).

The problem is, sometime it takes a very long time to update my file (several minutes and even several hours sometime), I'm sure to have a internet connection.

I use BroadcastReceiver and I already try ForgourndServicie, I tried to use PowerManager.WakeLock (I think we didn't need it in the onReceive of a BroadcastReceiver, may be I'm wrong).

I call my BroadcastReceiver with AlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + INTERVAL_UPDATE, INTERVAL_UPDATE, pendingIntent);, I got the permission <uses-permission android:name="android.permission.WAKE_LOCK"/>)

@Override
public void onReceive(Context context, Intent intent) {
    new Thread(() -> {
        //wake up CPU
        PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
        PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                                         "update:" + new CurrentDate().getTimeInMillis());
        wakeLock.acquire(30 * 1_000L /*30s*/);

        //do stuff and update my file

        //doesn't need CPU any more
        wakeLock.release();
    }).start();
}

in the AndroidManifext.xml

<receiver
    android:name="com.iutcalendar.service.BroadCastRecevierUpdate"
    android:enabled="true"/>

Any ideas? Is there an other solution to do what I want?


Solution

  • I fixed it by using Worker and WorkerManager https://developer.android.google.cn/topic/libraries/architecture/workmanager/basics?hl=en#kts