新人成長記録7th

こんにちは、poppyです

時刻指定でAndroidへ通知する機能を紹介していきます
今までBroadcastやServiceについては全くでしたが、実際に作成してみると少しですが理解できました
BroadcastやServiceは今後も必要となるので、徐々にですが理解を深めていきたいです

device-2016-08-08-173411

使用した主なクラス

時刻指定で通知するには、
PendingIntent
AlarmManager
Notification
を使用します

PendingIntent

PendingIntentは指定したタイミングで発行するIntent

投げる先によってメソッドが異なりgetActivityとgetBroadcast、getServiceがありますが、
今回はgetBroadcastメソッドを使用して、Broadcastを継承したクラスのonReceiveで受け取ります

PendingIntentのインスタンスを作る際は以下のようにしました

Intent intent = new Intent(this, MyBroadcastReceiver.class);
requestCode = メモ日付 + メモID;
PendingIntent pIntent = 
		PendingIntent.getBroadcast(this, int requestCode, 
				intent, PendingIntent.FLAG_UPDATE_CURRENT);

複数の通知を登録する場合には、requestCodeに同じ数値を使用すると上書きされてしまうために注意が必要です!
今回では、メモの日付と日付毎のIDでメモ毎のユニークなrequestCodeを作成しています

AlarmManager

AlarmManagerは指定した時間でイベントを発火させます
イベント発火時にPendingIntentを投げます
目覚ましや今回の私が作成するカレンダーアプリなど、時刻を指定して通知するアプリには必須のクラスですね!

インスタンスの生成は、以下のようにサービスから取得します

AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);

インスタンスの生成の次には実際にアラームのセットをしていきます

manager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);

アラームをスケジュールするためにはsetメソッドを使用します

これで指定時刻になればonReceiveにPendingIntentがBroadcastされるので、onReceiveの中で処理をしていきます

Notification

Notificationは通知を出すために使用します
そのために、onReceiveでイベントを受け取ってから通知を出すようにします
通知をタップした際にはアラームが通知したメモの詳細画面へと遷移するようにIntentを設定します

インスタンスや通知の詳細は以下のようにしました

Notification noti = new NotificationCompat.Builder(context)
				.setWhen(System.currentTimeMillis())
				.setTicker("予定の時間です!")
				.setContentTitle("通知")
				.setContentText(title)
				.setDefaults(Notification.DEFAULT_ALL)
				.setSmallIcon(R.drawable.normal)
				.setAutoCancel(true)
				.setContentIntent(sender)
				.build();
NotificationManager manager =
		(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(reqestID, noti);

Notificationクラスのインスタンス生成時に設定までしています

NotificationManagerで実際に通知を表示します

終わりに

IntentとPendingIntentの使い分けですが、現段階での理解は「やりたいことに使うメソッドで指定されている方を使えばよい」です
今回は、指定時刻の指定でイベントを発火させるためにAlartManagerを使いましたよね?
AlarmManagerのアラームをスケジュールするためのsetメソッドの引数は、以下のようにPendingIntentを必要としていますのでPendingIntentを使用しました

set(int type, long triggerAtMillis, PendingIntent operation)

 

火曜日担当:poppyからでした



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム