Android Studioを使っていて、分からないことがあったので質問していただきます。
理想の流れは以下のような感じです。
1.サービスが起動する{ここはすでに完成済み。} 2.「1秒」ごとにNofticationが更新されていく。 3.サービスが停止する{ここはすでに完成済み。}
なんですが、2.「1秒」ごとにNofticationが更新されていく。(つまりサービスの中身)ができない状態です。
サービスは以下の内容です。
Java
1package battery.vsmorse.com.myapp01; 2 3 4import android.app.Notification; 5import android.app.NotificationManager; 6import android.app.PendingIntent; 7import android.app.Service; 8import android.content.Intent; 9import android.graphics.Bitmap; 10import android.graphics.BitmapFactory; 11import android.os.IBinder; 12 13import android.support.v7.app.NotificationCompat; 14import java.util.Timer; 15import java.util.TimerTask; 16 17public class TestService extends Service { 18 private Timer timer = null; 19 private int count = 0; 20 21 @Override 22 public void onCreate() { 23 super.onCreate(); 24 } 25 26 @Override 27 public int onStartCommand(Intent intent, int flags, int startId) { 28 29 NotificationCompat.Builder builder = new NotificationCompat.Builder( 30 getApplicationContext()); 31 32 // LargeIcon の Bitmap を生成 33 Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.coda); 34 35 // NotificationBuilderを作成 36 37 // ステータスバーに表示されるテキスト 38 Intent notificationIntent = new Intent(this, MainActivity.class); 39 40 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 41 42 // アイコン 43 builder.setSmallIcon(R.drawable.coks); 44 // Notificationを開いたときに表示されるタイトル 45 builder.setContentTitle("TestApp"); 46 47 builder.setContentIntent(contentIntent); 48 // Notificationを開いたときに表示されるアイコン 49 builder.setLargeIcon(largeIcon); 50 // 通知するタイミング 51 builder.setWhen(System.currentTimeMillis()); 52 // 通知時の音・バイブ・ライト 53 builder.setDefaults (Notification.DEFAULT_VIBRATE 54 | Notification.DEFAULT_LIGHTS); 55 // タップするとキャンセル(消える) 56 builder.setAutoCancel(false); 57 58 timer = new Timer(); 59 timer.schedule( new TimerTask(){ 60 @Override 61 public void run(){ 62 // Notificationを開いたときに表示されるサブタイトル 63 builder.setContentText(count); 64// NotificationManagerを取得 65 NotificationManager manager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE); 66 // Notificationを作成して通知 67 int NOTIFICATION_CLICK = 001; 68 startForeground(NOTIFICATION_CLICK, builder.build()); 69 count++; 70 } 71 }, 0, 1000); 72 73 return super.onStartCommand(intent, flags, startId); 74 } 75 76 @Override 77 public void onDestroy() { 78 super.onDestroy();// timer cancel 79 if( timer != null ){ 80 timer.cancel(); 81 timer = null; 82 } 83 } 84 85 @Override 86 public IBinder onBind(Intent intent) { 87 return null; 88 } 89 } 90 91
コンパイルは通りますが、
これを実行すると、実機で
myapp01は予期しない動作をしたので終了します。 logcat--- 10-01 19:21:37.187 7216-7226/battery.vsmorse.com.myapp01; W/art: Suspending all threads took: 5.196ms
という画面が出て、強制終了させられてしまいます。
AndroidStudio2、
Android5.1を使っています。
あなたの回答
tips
プレビュー