This server suppose to be run 24/7
そんなことはできません。あなたが発見したように、これは用語の本当の意味では不可能です。それはまた、まったく良いデザインの選択ではありません。
常に実行する必要がある場合は、PARTIAL_WAKE_LOCK
viaを取得する必要がありますPowerManager
。これにより、CPU が常にオンになり、プログラムが実行されます。バッテリー寿命の衝撃的な低下に備えてください。
代わりにAlarmManagerを使用してください。AlarmManager を介してPendingIntentをスケジュールし、関連する時点でサービスを開始してその作業を行うことができます。完了したら、サービスを再度終了します。
以下は、今から 5 分後に YourService を開始するインテントを起動する AlarmManager の使用方法を示すサンプル コードです。
// get a calendar with the current time
Calendar cal = Calendar.getInstance();
// add 5 minutes to the calendar object
cal.add(Calendar.MINUTE, 5);
Intent intent = new Intent(ctx, YourService.class);
PendingIntent pi = PendingIntent.getService(this, 123, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);