简体   繁体   中英

How can keep notification in notification area/ bar if device shutdown?

I am trying to implement push notifications and I got notifications too. But now I need to notifications in notification bar when switched on. Ie if I got notification when mobile is on at time we did not see notification that is in notification area, if device shutdown then when I switched on the mobile, at time need to get that notification on notification bar and I have also another requirement, ie if I remove notification in notification area then after 10 minutes I need get that notification in notification area/ bar.

How can I accomplish this?

  1. You need to save notification content some where such as SharePreference .
  2. You listen when device booted by using this intent, "android.intent.action.BOOT_COMPLETED", when broadcast receiver get fired, you read notication content from step 1, fire notification again.

Easy, right :)

You can use PendingIntent with FLAG_ONE_SHOT :

private void sendNotification(String from, String message) {
        Bundle bundle = new Bundle();
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra("INFO", bundle);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setContentTitle(from)
                .setSound(defaultSoundUri)
                .setContentText(message)
                .setSmallIcon(R.drawable.ic_notification)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

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

        notificationManager.notify(0, builder.build());
    }

And remember set WAKE_LOCK permission in your manifest file:

<uses-permission android:name="android.permission.WAKE_LOCK" />

To do stuff on boot register a BroadcastReceveiver to BOOT_COMPLETED in your manifest.

To do stuff after a certain time use AlarmManager .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM