概要
今回から備忘録として、Androidアプリの開発に使えるものを書いていきたいと思います。
今回は、通知を送信してみたいと思います。
通知を送信する
Intent i = new Intent(Service.this, MainActivity.class);
PendingIntent pendingIntent
= PendingIntent.getActivity(
this,
0,
i,
0);
Notification notification = new Notification.Builder(this)
.setContentTitle("通知")
.setContentText("テスト通知です!!")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.img)
.setAutoCancel(true)
.build();
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1000, notification);
簡単に説明します。
Intent i = new Intent(Service.this, MainActivity.class);
まず、最初の一行目は、Intentの定義です。
右にどこに飛ばすか、左に何処から飛ばすかを書きます。
PendingIntent pendingIntent
= PendingIntent.getActivity(
this,
0,
i,
0);
次は、Intentの引数の設定です。
thisはContext
0はRequestCodeと言って、簡単に言うと通知につけるそれぞれの番号です。
別の内容のものとかぶるといろいろ面倒くさいので、別々ものを付けておくことをお勧めします。
iは先程定義した、Intentを入れています。
今度の0はFlagです。機会があったら、詳しく説明します。
Notification notification = new Notification.Builder(this)
.setContentTitle("通知")
.setContentText("テスト通知です!!")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.img)
.setAutoCancel(true)
.build();
これは、通知の設定です。
setContentTitleは通知のタイトル
setContentTextは通知の内容。
setContentIntentは先程設定した、Intentです。
setSmallIconは通知アイコンです。
あまり複雑なものは指定できないので、簡単なものを指定しましょう。
setAutoCancelはタップした時に通知を自動で消すかです。
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1000, notification);
これは先程の物をすべて詰め込んで、通知を送信するところです。
1000というのは通知番号です。
これをそれぞれ設定すると、通知が送信されるはずです。
参考にしてみてください。