开发者

i want to make my android app run in the background 24/7 unless closed by the user..what do i do..?

i want my app to run in the background as it has to开发者_运维百科 get the time every second..and do some task when the user sets a time and wants the app to do some task at that time..!!


Have you considered using the AlarmManager?

Android provides an AlarmManager service that will let you specify an Intent to send at a designated time. This intent is typically used to start an application at a preset time. (Note: If you want to send a notification to a sleeping or running application, use Handler instead.)


If you do something every second, it us unlikely the user's device will reach the 24 part without being plugged in to power.


Android apparently already contains a scheduling service so you don't need to create your own. Does this article help. Don't forget to follow up the links provided in that article.


I agree with every single person in this thread! AlarmManagers are your best friends when it comes to executing services at a certain interval. They are very easy to set up too, here's a very simple example of a repeating alarm:

//Get the alarm service
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

//Create the intents to launch the service again
Intent new_intent = new Intent(<The intent to set off>);
PendingIntent p_intent = PendingIntent.getBroadcast(this, 0, new_intent, 0);

//Create a repeating alarm
alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, <Time in milliseconds to set off first alarm>, <How long between each alarm in milliseconds>, p_intent);

Note that I'm using an inexact alarm to set of the alarm so it doesn't try to interrupt any other important services. It is possible to use an exact alarm but if your execution isn't really that important I highly suggest inexact alarms. You can find a lot more info below:

http://developer.android.com/reference/android/app/AlarmManager.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜