LoginSignup
14
16

More than 5 years have passed since last update.

Androidアプリでステータスバーに通知を出すやりかた。

Last updated at Posted at 2015-12-16

通知をクリックしたときのインテントをつくる

Intent notificationIntent = new Intent(this, XXXActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0);

ステータスバーに現れる通知をタップしたときに作動するインテントを先に作っておく。
PendingIntentは指定したタイミングで発行できるIntentのよう。(この場合は、通知をタップしたら発行する感じ)

通知用のオブジェクトをつくる

・実際の通知を作るためのBuilderを作成

Notification.Builder builder = new Notification.Builder(this);

・実際に通知を発行するmanagerを作成

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

・通知の中身をbuilderに設定していく

builder.setSmallIcon(R.drawble.XXX_ICON);
builder.setContentTitle("TITLE iS XX");
builder.setContentText("Text is XX");
builder.setDefaults(Notification.PRIORITY_DEFAULT);
builder.setContentIntent(contentIntent)

etc・・・

このとき、一行目のSmallIconの設定を忘れると、通知が表示されません。エラーにもならないので、わけわからんかった。。
ちなみに、最後の行では、最初に作ったPendingIntentを設定して、通知がタップされたらこの場合は、XXXActivityが呼ばれるようになります。

通知

あとは、作った通知をマネージャーを使用して出力するだけです。

manager.notify(1,builder.build());

notifyメソッドの最初の引数は、通知を識別するためのInt型のID、二つ目は、先ほど作った通知です。

アイコンがめんどい

アイコン設定しないと、何も通知されないっていう罠が憎かったのですが、おかげでこんないいプラグインを見つけました。うれしい。

AndroidDrawbleImporter
http://qiita.com/verno3632/items/8f432fc40f4cd2dd5325

resフォルダ以下に画像を見ながら選択したアイコンを自動的に解像度ごとに設置してくれるすぐれもの。

以上です。

14
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
16