2017-08-19 6 views
1

私はユーザに通知するインテントサービスを持っています。アプリがアクティブであるか、それがバックグラウンドにあるときでも、状態を停止した場合Android、IntentServiceがアプリを終了すると死ぬ

@Override 
    protected void onHandleIntent(final Intent workIntent) { 
    for(int i = 0; i < 10; i++){ 
     try{ 
      Thread.sleep(2000); 
      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); 
      mBuilder.setSmallIcon(R.mipmap.ic_launcher); 
      mBuilder.setContentTitle(String.valueOf(i) + "times called!"); 
      mBuilder.setContentText("Hi, This is Android Notification Detail!"); 

      NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

      mNotificationManager.notify(i, mBuilder.build()); 
     }catch(InterruptedException ex){} 
    } 
} 

このアプローチは完璧に動作します:次のようにそのonHandleIntentです。

しかし、私は(左にスワイプ)アプリケーションを殺すと、サービスの実行が停止します。まだ終了していない場合でも。どのように私はこれを克服できますか?

答えて

0

あなたはIntentServiceをフォアグラウンドとして実行する必要があります。 Service.startForeground

@Override 
protected void onHandleIntent(final Intent workIntent) { 
for(int i = 0; i < 10; i++){ 
    try{ 
     Thread.sleep(2000); 
     NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); 
     mBuilder.setSmallIcon(R.mipmap.ic_launcher); 
     mBuilder.setContentTitle(String.valueOf(i) + "times called!"); 
     mBuilder.setContentText("Hi, This is Android Notification Detail!"); 

     NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     // here you can start it as foreground 
     startForeground(i, mBuilder.build()); 
    }catch(InterruptedException ex){} 
} 

あなたが通知を作成するためにiを使用している場合、あなたは良いされていない(あなたの場合には10種類の)複数の通知を作成します。 startForegroundではiの代わりに一定の値を使うことができます。 実際のアプリケーションでIntentServiceを使用する前に、それが正しい選択であることを確認してください。ここにアンドロイドのさまざまなタイプのスレッディングについての短い議論がありますThings to consider before running background tasks

+0

ありがとう、本当にトリックをしました。しかし、もう一つ質問があります。 forループを削除してtry/catchブロックを実行すると、コードが機能しません。それはなぜでしょうか? – QnARails

関連する問題