Android Notification(通知) サンプル

notification

開始したサービスから、通知を行い、通知をクリックしたら Activity を表示する。

https://github.com/pppiroto/KaigiUtil/tree/73bfa6c6a624207552066129b157353b159f2ca5

1.通知アイコン

通知アイコンを準備。

AndroidStudio から、res/drawable のコンテキストメニューから、New-Image Asset を選択、Icon Type に、Notification icons を指定

notification_icon

2.Notificationの作成

https://developer.android.com/guide/topics/ui/notifiers/notifications.html?hl=ja

  1. package info.typea.kaigiutil;
  2.  
  3. import android.app.NotificationManager;
  4. import android.app.PendingIntent;
  5. import android.app.Service;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.os.IBinder;
  9. import android.os.Vibrator;
  10. import android.support.v4.app.NotificationCompat;
  11. import android.support.v4.app.TaskStackBuilder;
  12. import android.widget.Toast;
  13.  
  14. public class SleepDefenderService extends Service {
  15. private Vibrator vibrator;
  16.  
  17. public SleepDefenderService() {
  18. }
  19.  
  20. @Override
  21. public IBinder onBind(Intent intent) {
  22. throw null;
  23. }
  24.  
  25. @Override
  26. public int onStartCommand(Intent intent, int flags, int startId) {
  27. vibrator = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE);
  28. if (!vibrator.hasVibrator()) {
  29. Toast.makeText(this, "no vibrator.", Toast.LENGTH_LONG).show();
  30. } else {
  31. Toast.makeText(this, "start vibe as service", Toast.LENGTH_SHORT).show();
  32. long pattern[] = {1000, 100};
  33. int repeatIndex = 0; // 繰り返し開始位置 -1の場合繰り返しなし
  34. vibrator.vibrate(pattern, repeatIndex);
  35. }
  36.  
  37. doNnotify();
  38.  
  39. return START_STICKY;
  40. }
  41.  
  42. /**
  43. * notifications
  44. */
  45. private void doNnotify(){
  46. // 通知を作成
  47. NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
  48. .setSmallIcon(R.drawable.ic_notification)
  49. .setContentTitle("Kaigi Util")
  50. .setContentText("Stop sleep defender for click here.")
  51. .setTicker("Sleep defender started.");
  52.  
  53. // Activity を起動
  54. Intent resultIntent = new Intent(this, ContentActivity.class);
  55. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  56. stackBuilder.addParentStack(ContentActivity.class);
  57. stackBuilder.addNextIntent(resultIntent);
  58. PendingIntent pendingIntent =
  59. stackBuilder.getPendingIntent(
  60. 0,
  61. PendingIntent.FLAG_UPDATE_CURRENT
  62. );
  63. builder.setContentIntent(pendingIntent);
  64.  
  65. int notificationId = 1;
  66.  
  67. NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
  68.  
  69. manager.notify(notificationId, builder.build());
  70. }
  71.  
  72. @Override
  73. public void onDestroy() {
  74. super.onDestroy();
  75. vibrator.cancel();
  76. Toast.makeText(this, "stop vibe as service", Toast.LENGTH_SHORT).show();
  77. }
  78. }

Follow me!

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です