Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Thread vs AlarmManager

Ok, so I'm developing an Android App with news. When user runs App for the first time, a separate thread runs, then a infinite while( true ) loop starts, inside a loop a connector downloads text from the Internet to the notification and sends this notification, then sleeps for 8 hours. Which way is better to make it working best, a thread with way as above or alarm manager? Or, maybe there is a different and better way?

For now I've done two ways for testing, both work good, but I have no idea how to check which one is more efficient, which won't be killed by android, which eats less resources, etc.

And second question, is there any way to restore the loop when someone kill app? I was testing with Advanced Task Killer Free and an app Flashy (Flash Player Loader). I killed the Flashy, but 5 seconds later app was running again, so it propably is possible, but how?

And for those who think I'm developing annoying ad - no, App which I'm developing just reads news from the Internet.

Hope somebody helps, Thanks in advance.

like image 991
Radosław Wójciak Avatar asked Feb 15 '23 03:02

Radosław Wójciak


2 Answers

Thread vs AlarmManager

AlarmManager

As per Android doc

The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.

So the advantage you get here is you can perform specific task in future even if you application is not in running state.( Here you can proudly call yourself good android citizen since you are not residing in android memory to get your task done).You just tell android I want to get this task executed at particular time,Android will automatically start your application at that particular time even If it is not running.

If you want to acheive same thing with thread then your thread should be alive till the time task does not start executing.( The disadvantage will be android will not kill the thread till the time process is alive and your tread will unnecessary eat up memory).

Hope this will clear your doubt.

like image 160
Vipul Avatar answered Feb 24 '23 07:02

Vipul


In your case I would definitely use the alarm manager. As a general rule of thumb, if your application "sleeps" and routinely checks for new content in long intervals (8 hours is a long time), you should use the alarm manager.

This way your app doesn't need to run in the background, thus battery life is conserved, and the application's functionality will not be affected by Android killing the service in cases of low memory.

Regarding your second question - if the Android system kills a service due to low memory, it will restart it as soon as possible. However if you kill the service manually then it should not be restarted, even if it is possible through some hack.

like image 31
Josh Liberty Avatar answered Feb 24 '23 08:02

Josh Liberty