使用AsyncTask和Service检查阈值,每5秒钟报警一次

时间:2011-04-25 20:28:09

标签: android service android-asynctask alarmmanager

我正在编写一个需要每5秒钟完成一些工作的应用程序,如果这些计算高于阈值,则应该启动Intent,这将加载一个新的Activity(或者如果可能的话,活动将由过程本身)。

到目前为止,我正在使用Wrox的专业Android 2应用程序开发书中的方法,该书指出使用AlarmManager和AsyncTask刷新数据。 http://www.wrox.com/WileyCDA/WroxTitle/Professional-Android-2-Application-Development.productCd-0470565527,descCd-DOWNLOAD.html - >示例项目 - >第9章地震4

这是我到目前为止所做的:

  1. Activity.onCreate启动服务

  2. 来自已启动服务的
  3. onCreate方法使用PendingIntent设置警报参数(尚未启动)。

  4. 启动服务的onStartCommand创建警报并创建AsyncTask(带执行)

  5. AsynchTask.doInBackground执行一些计算,如果已经通过了阈值,它会广播一个新的Intent并尝试停止警报,如果未通过阈值则不会执行任何操作。

  6. 服务从AsyncTask的onPostExecute停止。

  7. BroadcastReceiver的onReceive方法从2处理PendingIntent并启动这样的服务:

    Intent startIntent = new Intent(context,MyService.class);

    context.startService(startIntent);

  8. 现在警报没有停止,我不太确定这是处理这种需求的最佳架构,您可以分享的任何体验? 我知道其他选项,如IntentService,Handlers Handler,Timers,但这也是一种干净的方式,但......它的性能是否很高? 最好的祝福。吉列尔莫。

2 个答案:

答案 0 :(得分:1)

在java中查看这个类

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html

我认为你可以使用!!

答案 1 :(得分:0)

使用可以启动闹钟的PendingIntent,你可以在AlarmManager中调用cancel(),它会停止。