1

我有由 AlarmManager 启动的服务喜欢这个

Intent in = new Intent(SecondActivity.this,BotService.class);
                    PendingIntent pi = PendingIntent.getService(SecondActivity.this, 9768, in,PendingIntent.FLAG_UPDATE_CURRENT);

                    AlarmManager alarms = (AlarmManager) SecondActivity.this.getSystemService(Context.ALARM_SERVICE);
                    alarms.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),pi);

当服务启动时,它会再次设置 AlarmManager,我这样做是因为我需要以随机间隔重复服务。

这是通过以下方式完成的:

Intent in = new Intent(BotService.this, BotService.class);
            PendingIntent pi = PendingIntent.getService(BotService.this, 9768,
                    in, PendingIntent.FLAG_UPDATE_CURRENT);

            AlarmManager alarms = (AlarmManager) BotService.this.getSystemService(Context.ALARM_SERVICE);
            alarms.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+ (attack_interval * MINS) + attack_interval_min, pi);

我的服务可能会持续一段时间,如果服务没有运行,如何通过 AlarmManager 启动服务?

如果它正在运行,我需要再次设置 AlarmManager,因为否则我的服务将无法重新启动。谢谢您的回答。如果有什么不清楚的请询问。

4

2 回答 2

1

您可能希望改为实现IntentService;如果该方法适合您的需求,您将摆脱所有生命周期的麻烦。

另外,为什么不通过setInexactRepeating或 setRepeating 设置重复警报?当然,只有当您确定 IntentService 的运行时间不会超过警报间隔,或者您有其他合理的机制可以在 IntentService 仍在运行时忽略警报时,您才会这样做。

更新:如果您还询问如何最初启动您的服务......好吧,这取决于。许多人将BOOT_COMPLETED广播视为解决所有问题的方法。但是,它会阻止用户将您的应用程序移动到 SD 卡。如果您只能在应用程序运行后重复运行您的服务,那么您的应用程序可以启动此操作。BOOT_COMPLETED否则,如果您查看系统发送的哪些其他事件可能与您的服务相关,例如互联网连接的变化,您仍然可以避免陷阱。如果你决定,你可以在这里BOOT_COMPLETED找到一个例子。

于 2013-02-01T09:27:02.413 回答
0

如果您查看文档。当服务启动时,它有一个 startID,这可用于确定在给定时间运行的服务实例的数量。

参考:

public int onStartCommand (Intent intent, int flags, int startId)

Added in API level 5
Called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request. Do not call this method directly.

For backwards compatibility, the default implementation calls onStart(Intent, int) and returns either START_STICKY or START_STICKY_COMPATIBILITY.

If you need your application to run on platform versions prior to API level 5, you can use the following model to handle the older onStart(Intent, int) callback in that case. The handleCommand method is implemented by you as appropriate:
于 2013-02-01T09:20:36.610 回答