ステータスバーに通知を出す
Android端末上部を下にドラッグすると、通知されたメッセージの一覧が表示される。
それらのメッセージは、アプリから簡単に操作できる。
それらのメッセージは、アプリから簡単に操作できる。
使用するクラス
NotificationManagerクラス と Notificationクラス、および Notification.Builderクラスを使用する。
BuilderでNotificationクラスを作成し、SystemサービスからNotificationManagerを取得し、Notificationを渡す。
BuilderでNotificationクラスを作成し、SystemサービスからNotificationManagerを取得し、Notificationを渡す。
ただし、Notification.Builder は API11以降でしか使えない。
その場合は、Notification クラスのコンストラクタを使用する。
その場合は、Notification クラスのコンストラクタを使用する。
サンプルコード
- 一連の流れは次のように行う。Notification のコンストラクタでも作成できるが API11以降では deprecated なので代わりに Notification.Builder を使う
Notification.Builder noticeBuilder = new Notification.Builder(this); noticeBuilder.setSmallIcon(android.R.drawable.ic_dialog_alert); noticeBuilder.setTicker("ticker"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) noticeBuilder.setSmallIcon(android.R.drawable.ic_dialog_alert); noticeBuilder.setContentTitle("title"); noticeBuilder.setContentInfo("info"); noticeBuilder.setContentText("text"); Notification notice = noticeBuilder.build(); NotificationManager manager = getSystemService(NOTIFICATION_SERVICE); manager.notify(1, notice); // 1 はアプリ内の通知uniqueID。削除時に指定
Notificationクラスのコンストラクタを使った場合は次のようになる。deperecated のコンストラクタを使用するが、以前のAPIレベルに対応するためには仕方ない。それに Builderのリリース以前は deperecated ではなかったと考えられる。
Notification notice = new Notification(android.R.drawable.ic_dialog_alert, "ticker", System.currentTimeMillis()); notice.setLatestEventInfo(this, "title", "text", null); ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(1, notice);
deprecated なメソッドは出来れば使いたくないけど、このケースでは仕方ないし Builder よりも遥かに簡単に通知が出せる。ただ Info に相当する文字は出せない。タブレットなどでも使用されることを想定するアプリなら、Notification用のユーティリティクラスを作り、APIレベルに応じて使い分けるようにするのが良い(と思う)。
その翌日、いろいろいじってたら android.support.v4.app.NotificationCompat 使ったらUtil要らなかったことが判明。
便利なので使ってください NotificationCompat
便利なので使ってください NotificationCompat
表示結果はこんな感じ
上は一瞬表示され、すぐに引っ込むTicker。下はステータスバーをドラッグしたところ。
サンプルコード(その他)
- 実行中のアプリから通知されたメッセージを全て削除する
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll();
- 通知をクリックするとアプリが表示される
Intent intent = new Intent(this, com.someproject.somepackage.MainActivity.class) ; PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,intent,PendingIntent.FLAG_ONE_SHOT); noticeBuilder.setContentIntent(pendingIntent);