こんにちは。管理人のピヨ猫でーす。
Androidで通知機能(Notify)を実装する方法を紹介します。
1.通知機能について
Androidアプリには通知機能(Notify)があります。
スマホ端末の上に表示される「あいつ」です。
定期的にアプリの情報を表示してくれるお知らせ機能です。
お知らせを選択するとアプリを開くことが出来ます。
アプリを起動しなくても、お知らせがわかるので利用者にとってありがたい機能です。
2.通知機能の実装方法の注意点(OSバージョン差異)
通知機能を実装する前に注意点があります。
それは通知機能はAndroidのOSバージョンによって実装方法が異なることです。
AndroidのOSバージョンにより通知機能の実装に使えるライブラリ(API)が異なります。
APIレベルとOSバージョンの違いは以下の記事が参考となるので貼っときます。
https://so-zou.jp/mobile-app/tech/android/data/api-level/
通知機能のAPIはAPIレベル26(Oreo)で大幅改定が入っており、通知機能を実装する場合は、Oreo以前とOreoの両方の実装をする必要があります。
通知機能の実装方法
public class NotifyUtil {
public static NotificationCompat.Builder createBuilder(
Context context, Class> target,
String channelId, String chanelName,
String title, String message, int icon) {
if(Build.VERSION.SDK_INT < 26){
// APIレベル26より前の場合
NotificationCompat.Builder builder
= new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(icon);
Intent intent = new Intent(context, target);
intent.putExtra("DATA", "NONE");
intent.setFlags(
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
context, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
return builder;
} else {
// APIレベル26以降の場合
// チャネル設定
NotificationChannel channel = new NotificationChannel(
channelId, chanelName, NotificationManager.IMPORTANCE_DEFAULT);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
channel.enableVibration(true);
channel.enableLights(true);
channel.setShowBadge(false);
// Notification
NotificationManager nm = context.getSystemService(NotificationManager.class);
nm.createNotificationChannel(channel);
NotificationCompat.Builder builder
= new NotificationCompat.Builder(context, channelId)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(icon);
Intent intent = new Intent(context, target);
intent.putExtra("DATA", "NONE");
intent.setFlags(
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
context, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
return builder;
}
}
}
/**
* 通知実行処理
*/
public class XXX {
private void sendNotification() {
NotificationCompat.Builder builder = NotifyUtil.createBuilder(
getApplicationContext(),
MainActivity.class,
NotifyService.class.getName() + ".notify.chanel",
NotifyService.class.getSimpleName(),
getResources().getString(R.string.message_notify_alert_title),
getResources().getString(R.string.message_notify_alert),
R.drawable.ic_cat_icon
);
NotificationManagerCompat.from(getApplicationContext()).notify(
MyApp.REQUEST_NOTIFY_ALERT, builder.build());
}
}
通知機能の実装で困ったら
本家のAndroid Developersサイトを見るのが一番ですよー。
リンク貼っときまーす。
https://developer.android.com/guide/topics/ui/notifiers/notifications?hl=ja
本日は以上です。この記事が少しでもお役に立てば幸いです。