通知データを更新したいのですが、見つけた唯一の方法は、同じIDで新しいデータを起動することです。
問題は、元のキャンセルがキャンセルされた場合、新しいものを上げたくないということです。通知が表示されているかキャンセルされているかを確認する方法はありますか?または、通知が存在する場合にのみ通知を更新する方法はありますか?
通知データを更新したいのですが、見つけた唯一の方法は、同じIDで新しいデータを起動することです。
問題は、元のキャンセルがキャンセルされた場合、新しいものを上げたくないということです。通知が表示されているかキャンセルされているかを確認する方法はありますか?または、通知が存在する場合にのみ通知を更新する方法はありますか?
これが私がそれを解決した方法です:
private boolean isNotificationVisible() {
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent test = PendingIntent.getActivity(context, MY_ID, notificationIntent, PendingIntent.FLAG_NO_CREATE);
return test != null;
}
これは私が通知を生成する方法です:
/**
* Issues a notification to inform the user that server has sent a message.
*/
private void generateNotification(String text) {
int icon = R.drawable.notifiaction_icon;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, text, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
//notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, MY_ID, notificationIntent, 0);
notification.setLatestEventInfo(context, title, text, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL; //PendingIntent.FLAG_ONE_SHOT
notificationManager.notify(MY_ID, notification);
}
クラスのdeleteIntentが使えると思いますNotification
。
通知がキャンセルされたとき、または通知トレイがクリアされたときに、ブロードキャスト (カスタム ブロードキャスト) を起動するために使用するアプリケーションの 1 つを覚えています。
に代わるものdeleteIntent
は、私自身のアプリで有益であることが証明されている次のとおりです。
基本的に、IntentService(またはその他のサービス)を開始する通知を使用してインテントを作成しonHandleIntent
、通知がアクティブかどうかを示すフラグを設定できます。
このインテントは、ユーザーが通知をタップしたとき(contentIntent)および/またはユーザーがリストから通知をクリアしたとき(deleteIntent)に発生するように設定できます。
それを説明するために、これが私が自分のアプリで行うことです。通知を作成するときに設定しました
Intent intent = new Intent(this, CleanupIntentService.class);
Notification n = NotificationCompat.Builder(context).setContentIntent(
PendingIntent.getActivity(this, 0, intent, 0)).build();
通知がタップされると、myCleanupIntentService
が起動され、(通知を作成したサービスで)フラグが設定されます。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onCreate(); // If removed, onHandleIntent is not called
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
OtherService.setNotificationFlag(false);
}
Kotlin で次のように確認できます。
val mNotificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notifications: Array<StatusBarNotification> = mNotificationManager.activeNotifications
if(notifications.isNotEmpty())
{
//you don't have notifications
}
else
{
//you have notifications
}