Androidで終わりのないバックグラウンドサービスを作りたいと思います。これを行うには、AlarmManager
とシンプルを使用していますService
Alarmmanger
ブロードキャストで受信したブロードキャストレシーバサービスが動作しているかどうかを確認しています。Androidのバックグラウンドサービスは、最近のタスクリストからアプリが終了すると起動しません。
私のサービスコードが
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate ();
Log.e ("My service ", "oncreate");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
scheduleAlarm();
super.onTaskRemoved (rootIntent);
}
// Setup a recurring alarm every half hour
public void scheduleAlarm() {
// Construct an intent that will execute the ServiceAlarmReceiver
Intent intent = new Intent("com.hmkcode.android.USER_ACTION");
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, ServiceReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
long firstMillis = System.currentTimeMillis()+5000; // alarm is set right away
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTCWAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
6000, pIntent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e ("My Service:", " on Start Command");
return START_STICKY;
}
}
ブロードキャストレシーバー
public class ServiceReceiver extends WakefulBroadcastReceiver {
public static final int REQUEST_CODE=12355;
public ServiceReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// check service is running or not
if (isMyServiceRunning (MessageService.class,context)){
// don nothing
}
else {
// launch the service
if (isConnectedToInternet (context)) {
Intent serviceIntent = new Intent (context, MyService.class);
context.startService (serviceIntent);
}
}
Log.e ("hello","wer are in Receiver");
// throw new UnsupportedOperationException ("Not yet implemented");
}
}
私のマニフェストです:
<receiver
android:name=".Services.ServiceReceiver"
android:enabled="true"
android:exported="true"
android:process=":remote">
<intent-filter>
<action android:name="com.hmkcode.android.USER_ACTION" />
</intent-filter>
</receiver>
<service
android:name=".Services.MyService"
android:enabled="true"
android:stopWithTask="false"
android:process=":remote"
>
</service>
それはアプリがフォアグラウンドまたはバックグラウンドにあるときはうまくいきましたが、問題Androidの最近のタスクリストからアプリをスワイプすると、 ppはサービスと私の放送レシーバーが再びそれを再開することができないように殺されましたか?私はAlarmmanger
をonTaskRemoved
に再スケジューリングしていますが、まだサービスが再開していません。
また、START_STICKY
からonStartCommand()
に戻ってきました。これにより、リソース制限のために停止する必要がある場合でも、システムはサービスを再開します。
マニフェストファイルの<service>
タグに"stopWithTask"=false
も使用されます。それは影響もありませんでした。