2017-03-31 6 views
0

Androidで終わりのないバックグラウンドサービスを作りたいと思います。これを行うには、AlarmManagerとシンプルを使用していますServiceAlarmmangerブロードキャストで受信したブロードキャストレシーバサービスが動作しているかどうかを確認しています。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はサービスと私の放送レシーバーが再びそれを再開することができないように殺されましたか?私はAlarmmangeronTaskRemovedに再スケジューリングしていますが、まだサービスが再開していません。

また、START_STICKYからonStartCommand()に戻ってきました。これにより、リソース制限のために停止する必要がある場合でも、システムはサービスを再開します。

マニフェストファイルの<service>タグに"stopWithTask"=falseも使用されます。それは影響もありませんでした。

答えて

0

アラームマネージャからPendingIntentを作成し、宣言的にではなくコードでインスタンス化することで成功しました。

public class HeartbeatReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     try{ 
      Log.i(MainService.TAG, "** Heartbeat onReceive **"); 
      if (!Utility.isMyServiceRunning(context)){ 
       Log.i(MainService.TAG, "Service is dead. Restarting..."); 
       context.startService(new Intent(context, MainService.class)); 
       return; 
      } 
     } 
    } 

    public void StartHeartbeat(Context context, int interval) { 
     this.CancelHeartbeat(context); 
     AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
     Intent i = new Intent(context, HeartbeatReceiver.class); 
     PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); 
     am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pi); 
    } 

    public void CancelHeartbeat(Context context) { 
     Intent intent = new Intent(context, HeartbeatReceiver.class); 
     PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); 
     AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
     alarmManager.cancel(sender); 
    } 
} 

受信者をApplicationクラスでプログラムで初期化します。インテントがマニフェストで作成されたときには動作していないようです。

public class MainApp extends Application { 
    @Override 
    public void onCreate(){ 
     super.onCreate(); 
     MainService.baseContext = getBaseContext(); 
     HeartbeatReceiver heartBeat = new HeartbeatReceiver(); 
     heartBeat.StartHeartbeat(MainService.baseContext, 60 * 1000 * 5); 

    } 
} 

は、次にこれは、私はそれが動作する理由を正確にはわからないが、私はアプリを殺すならば、それが正常に戻ってくるので、実験の結果、無意図

<receiver android:name="HeartbeatReceiver"/> 

とマニフェストでちょうど受信しました次のアラームが実行されたとき。希望が役立ちます。

関連する問題