久しぶりに質問させていただきます。今serviceを使ってバックグラウンドで通知をする処理を実装している最中です。ですが、カウントダウンしている途中にアプリを一度落とすとそれ以降作動しなくなります。
java
1public class backGroundTimer extends Service { 2 3 private Handler handler = new Handler(); 4 private Runnable run; 5 private int count = 0; 6 NotificationManagerCompat manager; 7 8 @Override 9 public void onCreate() { 10 super.onCreate(); 11 } 12 13 @Override 14 public int onStartCommand(Intent intent, int flags, int startId) { 15 16 17 18 run = new Runnable() { 19 @Override 20 public void run() { 21 handler.removeCallbacks(run); 22 handler.postDelayed(run, 1000); 23 count++; 24 if(count == 5) { 25 sendNotification(); 26 stopSelf(); 27 } 28 } 29 }; 30 handler.postDelayed(run,1000); 31 return super.onStartCommand(intent, flags, startId); 32 } 33 34 35 @Override 36 public void onDestroy() { 37 super.onDestroy(); 38 manager.cancel(0); 39 stopSelf(); 40 } 41 42 private void sendNotification() { 43 Intent intent = new Intent(this,MainActivity.class); 44 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); 45 46 manager = NotificationManagerCompat.from(this); 47 Notification notification = new NotificationCompat.Builder(this) 48 .setAutoCancel(true) 49 .setContentTitle("タイトル") 50 .setContentText("コメント") 51 .setSmallIcon(R.mipmap.icon) 52 .setContentIntent(pendingIntent) 53 .setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE) 54 .build(); 55 manager.notify(1, notification); 56 } 57 58 @Override 59 public IBinder onBind(Intent intent) { 60 return null; 61 } 62} 63
必要ない部分は省きました。このようなコードになっております。MainActivityでButtonをクリックすることでこのサービスをスタートさせています。その後5秒間カウントし、5秒後に通知を呼び出しています。普通に動かしている分にはなにも異常はないのですが、5秒間のカウントしている最中にこのアプリを落とすとそれ以降正常に作動しなくなります。OnDestroy()の中で途中でも終了させるようにする処理を書けばいいのかと思い、Stopself()をいれてみたのですが変わりませんでした。雑な説明で申し訳ないのですがアドバイスのほどよろしくお願いしますm(-_-)m
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/05/01 04:22
2017/05/01 04:29
2017/05/01 04:37
2017/05/01 06:21
2017/05/01 08:08
2017/05/01 08:52