Alarm running every 5 seconds with AsyncTask and Service checking for a threshold
I'm writing an application which needs to make some work every 5 seconds, if those calculations are above a threshold an Intent should be launch which will load a new Activity (or maybe if it's possible the activity will be launched by the process itself).
So far, I'm taking the approach in Professional Android 2 Application Development book from Wrox, which states for refreshing data use an AlarmManager and AsyncTask. http://www.wrox.com/WileyCDA/WroxTitle/Professional-Android-2-Application-Development.productCd-0470565527,descCd-DOWNLOAD.html -> Example Projects -> Chapter 9 Earthquake 4
This is what I have so far:
Activity.onCreate launches a service
onCreate method from the launched service sets Alarm parameters with PendingIntent (doesn't launch it yet).
onStartCommand of the launched service creates the alarm开发者_Python百科 and creates the AsyncTask (with execute)
AsynchTask.doInBackground does some calculations and if the threshold has been passed, it broadcasts an new Intent and tries to stop the Alarm, if the threshold is not passed then nothing is done.
The service is stopped from onPostExecute of the AsyncTask.
onReceive method of a BroadcastReceiver handles the PendingIntent from 2) and launches the service like this:
Intent startIntent = new Intent(context, MyService.class);
context.startService(startIntent);
Right now the Alarm is not stopping, and I'm not quite sure this is the best architecture to handle this kind of needs, any experiences you can share? I know about other options like IntentService, Usage of Handlers, Timers, but this is a clean way as well, but...Is its performance high? Best Regards. Guillermo.
look at this class in java
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html
I think you can use!!
Using the PendingIntent which let you start your Alarm, you can call cancel() in AlarmManager and it will stop.
精彩评论