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 に答える