Clear notification of an android app (Java) - java

I have a notification in my music app with following code:
void showNotification(int playPauseBtn){
Intent intent = new Intent(this, PlayerActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
Intent prevIntent = new Intent(this, NotificationReceiver.class)
.setAction(ACTION_PREVIOUS);
PendingIntent prevPending = PendingIntent.getBroadcast(this, 0, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, NotificationReceiver.class)
.setAction(ACTION_PLAY);
PendingIntent pausePending = PendingIntent.getBroadcast(this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(this, NotificationReceiver.class)
.setAction(ACTION_NEXT);
PendingIntent nextPending = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
byte[] picture = null;
picture = getAlbumArt(musicFiles.get(position).getPath());
Bitmap thumb = null;
if (picture != null){
thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
}
else{
thumb = BitmapFactory.decodeResource(getResources(), R.drawable.musicicon);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_2)
.setSmallIcon(playPauseBtn)
.setLargeIcon(thumb)
.setContentTitle(musicFiles.get(position).getTitle())
.setContentText(musicFiles.get(position).getArtist())
.addAction(R.drawable.ic_skip_previous, "Previous", prevPending)
.addAction(playPauseBtn, "Pause", pausePending)
.addAction(R.drawable.ic_skip_next, "Next", nextPending)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(mediaSessionCompat.getSessionToken()))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build();
startForeground(2, notification);
notificationManager =
(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(2, notification);
}
I have created separate class(ApplicationClass) for creating notification channel.
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel1 =
new NotificationChannel(CHANNEL_ID_1,
"Channel(1)", NotificationManager.IMPORTANCE_HIGH);
channel1.setDescription("Channel 1 Desc..");
NotificationChannel channel2 =
new NotificationChannel(CHANNEL_ID_2,
"Channel(2)", NotificationManager.IMPORTANCE_HIGH);
channel1.setDescription("Channel 2 Desc..");
//HERE ABOVE DOUBT
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel1);
notificationManager.createNotificationChannel(channel2);
}
}
}
And also, I have a class (NotificationReceiver) for receiving notification action:
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String actionName = intent.getAction();
Intent serviceIntent = new Intent(context, MusicService.class);
if (actionName != null){
switch (actionName){
case ACTION_PLAY:
serviceIntent.putExtra("ActionName", "playPause");
context.startService(serviceIntent);
break;
case ACTION_NEXT:
serviceIntent.putExtra("ActionName", "next");
context.startService(serviceIntent);
break;
case ACTION_PREVIOUS:
serviceIntent.putExtra("ActionName", "previous");
context.startService(serviceIntent);
break;
}
}
}
}
My notification functions(play, pause & next) works properly, but my problem is that, I am unable to clear notification. I tried many times but I could not get it right.

try this
void showNotification(int playPauseBtn){
Intent intent = new Intent(this, NotifAction.class);
//add this to get IdNotif.for all intent
intent.putextra("NotifId",notifId);
//
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
Intent prevIntent = new Intent(this, NotifAction.class)
.setAction(ACTION_PREVIOUS);
PendingIntent prevPending = PendingIntent.getBroadcast(this, 0, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, NotifAction.class)
.setAction(ACTION_PLAY);
PendingIntent pausePending = PendingIntent.getBroadcast(this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(this, NotifAction.class)
.setAction(ACTION_NEXT);
PendingIntent nextPending = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
byte[] picture = null;
picture = getAlbumArt(musicFiles.get(position).getPath());
Bitmap thumb = null;
if (picture != null){
thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
}
else{
thumb = BitmapFactory.decodeResource(getResources(), R.drawable.musicicon);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_2)
.setSmallIcon(playPauseBtn)
.setLargeIcon(thumb)
.setContentTitle(musicFiles.get(position).getTitle())
.setContentText(musicFiles.get(position).getArtist())
.addAction(R.drawable.ic_skip_previous, "Previous", prevPending)
.addAction(playPauseBtn, "Pause", pausePending)
.addAction(R.drawable.ic_skip_next, "Next", nextPending)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(mediaSessionCompat.getSessionToken()))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build();
startForeground(notifId, notification);
notificationManager =
(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notifId, notification);
}
set notifId for eachNotification and make this class for handle all action in notification.
note :
To set each event for each notification button, you first rationalize all actions to the NotifAction class, and from there define click events for each using the class.
create class for HandleAction:
public class NotifAction extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Bundle extra = intent.getExtras();
if (extra != null) {
if (action.equals("YourActionName")) {
clearNotification(extra.getInt("YourNotifId",0),context);
Toast.makeText(context, "YourMessage!", Toast.LENGTH_SHORT).show();
} else
/// another event for each action
}
private void clearNotification(int id, Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
}
}

Related

notification doesn't cancel in android 6

notification in nexus 5 android 6 don't cancel and go away from it. but when i run it on diffrenet device with android 9 or more, notification goes away. please help me.
public void showNotification(int playPauseBtn)
{
Intent intent = new Intent(this, PlayerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent PrevIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PREVIOUS);
PendingIntent prevPending = PendingIntent.getBroadcast(this, NOTIFICATION_ID, PrevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PLAY);
PendingIntent pausePending = PendingIntent.getBroadcast(this, NOTIFICATION_ID, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_NEXT);
PendingIntent nextPending = PendingIntent.getBroadcast(this, NOTIFICATION_ID, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
byte[] picture;
picture = getTrackArt(musicFiles.get(position).getPath());
Bitmap thumb;
if (picture != null)
{
thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
} else
{
thumb = BitmapFactory.decodeResource(getResources(), R.drawable.musicnowplaying);
}
Notification notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID_2)
.setSmallIcon(playPauseBtn)
.setLargeIcon(thumb)
.setChannelId(CHANNEL_ID_2)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setOngoing(true)
.setContentTitle(musicFiles.get(position).getSongTitle())
.setContentText(musicFiles.get(position).getArtist())
.addAction(R.drawable.ic_skip_previous, "Previous", prevPending)
.addAction(playPauseBtn, "Pause", pausePending)
.addAction(R.drawable.ic_skip_next, "Next", nextPending)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(mediaSessionCompat.getSessionToken()))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build();
startForeground(NOTIFICATION_ID, notification);
}

Android studio notifications implemented but not showing

I have implemented android notifications in android studio. I was creating notification for a media player. following is the function for showing notifications
public void showNotification(int playPauseBtn)
{
Intent intent = new Intent(this, PlayerActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
Intent prevIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PREVIOUS);
PendingIntent prevPending = PendingIntent.getBroadcast(this, 0, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PLAY);
PendingIntent pausePending = PendingIntent.getBroadcast(this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_NEXT);
PendingIntent nextPending = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
byte[] picture = null;
try
{
picture = getAlbumArt(listSongs.get(position).getPath());
} catch (Exception ignored)
{
}
Bitmap thumb;
if (picture != null)
{
thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
} else
{
thumb = BitmapFactory.decodeResource(getResources(), R.drawable.icon_music);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_1).setSmallIcon(playPauseBtn)
.setLargeIcon(thumb)
.setContentTitle(listSongs.get(position).getTitle())
.setContentText(listSongs.get(position).getArtist())
.addAction(R.drawable.ic_baseline_skip_previous_24, "Previous", prevPending)
.addAction(R.drawable.ic_baseline_skip_next_24, "Next", nextPending)
.addAction(playPauseBtn, "pause", pausePending)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle().setMediaSession(mediaSessionCompat.getSessionToken()))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(true)
.setContentIntent(contentIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
Toast.makeText(PlayerActivity.this, "Nitification created", Toast.LENGTH_SHORT).show();
}
In the function parameter (playPauseBtn) I am sending the play icon or the pause icon depending upon weather the song is playing or is paused.
Function call is made like following:
showNotification(R.drawable.ic_baseline_pause_24);
OR
showNotification(R.drawable.ic_baseline_play_arrow_24);
But when ever I call this function the notification doesn't show up. I am also using the notification channel but still it is not working. I have also tried to debug the code but the code runs fine, still the notification doesn't show up. please advise
try this.
put this code in your Activity/fragment;
public void getNotification(){
int notifId =new Random().nextInt(500); //get random id
NotificationManager notificationManager;
Notification notification;
notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channelID = "1";
channelName = "news";
channelDesc = "news description";
NotificationChannel notificationChannel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription(channelDesc);
notificationChannel.enableLights(true);
notificationChannel.setSound(null, null);
notificationChannel.setLightColor(Color.GREEN);
notificationManager.createNotificationChannel(notificationChannel);
}
RingtoneManager.getRingtone(mContext,
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)).play();
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, channelID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("title Of MUSIC")
.setContentText("Content")
.setVibrate(new long[]{100, 500, 500, 500, 500})
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
Intent actionReadMessage = new Intent(mContext, NotifAction.class);
actionReadMessage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
actionReadMessage.setAction("Play");
actionReadMessage.putExtra("NotifId",notifId);
PendingIntent playPendingIntent = PendingIntent.getBroadcast(mContext, notifId, actionReadMessage,PendingIntent.FLAG_CANCEL_CURRENT);
Intent mainAction = new Intent(mContext, NotifAction.class);
mainAction.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAction.setAction("Pause");
mainAction.putExtra("NotifId",notifId);
PendingIntent PausePendingIntent = PendingIntent.getBroadcast(mContext, notifId, mainAction,PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(PausePendingIntent);
builder.addAction(R.mipmap.ic_launcher, "Play", playPendingIntent);
builder.addAction(R.mipmap.ic_launcher, "Pause", PausePendingIntent);
notification = builder.build();
notificationManager.notify(notifId, notification);
}
and create class NotifAction.class for handle all action:
public class NotifAction extends BroadcastReceiver {
private static final String TAG = "maybe";
private MediaPlayer mp;
#Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Bundle extra = intent.getExtras();
if (extra != null) {
int notifId = extra.getInt("NotifId");
if (action.equals("Play")) {
mp = MediaPlayer.create(context, R.raw.music);
handleMusicState(mp);
} else if (action.equals("Pause")) {
handleMusicState(mp);
setMessageRead(notifId, context);
} else {
Toast.makeText(context, "extra action !", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Empty extra !", Toast.LENGTH_SHORT).show();
}
}
private void setMessageRead(int id, Context context) {
// other method
clearNotification(id, context);
}
private void clearNotification(int id, Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
}
private void handleMusicState(MediaPlayer mediaPlayer) {
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
else mediaPlayer.start();
}
}
define this receiver to manifest:
note:in tag
<receiver android:name=".NotifAction">
<intent-filter>
<action android:name="Play" />
<action android:name="Pause" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
FIX
Donot use .setMediaSession(mediaSessionCompat.getSessionToken()) in .setStyle() in the code given in the question
simply just use
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle())

Cancelling multiple notification by sending unique id to broadcast receiver

I create multiple notifications using AlarmManager. Each notification pop-ups correctly and I would like to cancel each of these notification separately. I have an AlarmReceiver that creates the notification and sets the unique id for it. I'm sending the unique id in the intent (via putExtra). This way, I can retrieve it in the NotificationReceiver and cancel the notification. However, it is not working.
Do you know why I always get the default value when I use intent.getIntExtra("UNIQUE_ID_NAME",0) ?
Is it a proper way to achieve the goal of cancelling these notifications ?
Here is my code:
MainActivity class:
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ReminderBroadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
long ctime = System.currentTimeMillis();
long tensec = 1000 * 5;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, ctime+tensec, 1000*10 , pendingIntent);
}
AlarmReceiver Class:
#Override
public void onReceive(Context context, Intent intent) {
int notification_id = generateRandom();
Intent activityIntent = new Intent(context, MainActivity.class);
activityIntent.putExtra(NotificationReceiver.UNIQUE_ID_NAME, notification_id);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent bYesIntent = new Intent(context, NotifReceiver.class);
bYesIntent.putExtra(NotificationReceiver.YES_ACTION_ID, "yesID");
PendingIntent actionYesIntent = PendingIntent.getBroadcast(context, 0, bYesIntent, 0);
Intent bNoIntent = new Intent(context, NotifReceiver.class);
bNoIntent.putExtra(NotificationReceiver.NO_ACTION_ID, "noID");
PendingIntent actionNoIntent = PendingIntent.getBroadcast(context, 0, bNoIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "channel1")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Notif")
.setContentText("Text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(contentIntent)
.addAction(R.mipmap.ic_launcher, "YES", actionYesIntent)
.addAction(R.mipmap.ic_launcher, "NO", actionNoIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(notification_id, builder.build());
}
public int generateRandom(){
Random random = new Random();
return random.nextInt(9999 - 1000) + 1000;
}
NotificationReceiver Class:
public class NotificationReceiver extends BroadcastReceiver {
public static String YES_ACTION_ID = "YesID";
public static String NO_ACTION_ID = "NoID";
public static String UNIQUE_ID_NAME = "notification_id";
#Override
public void onReceive(Context context, Intent intent) {
int notification_id= intent.getIntExtra(UNIQUE_ID_NAME,0);
System.out.println("Notif ID: " + notification_id); // here always is 0;
String actionYes = intent.getStringExtra(YES_ACTION_ID);
String actionNo = intent.getStringExtra(NO_ACTION_ID);
if(actionYes!=null){
Toast.makeText(context, "YES", Toast.LENGTH_SHORT).show();
}
if(actionNo!=null){
Toast.makeText(context, "NO", Toast.LENGTH_SHORT).show();
}
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notification_id);
}
}
I solved this problem by updating current intent and request code. Notifications are reusing the same Intent so adding FLAG_UPDATE_CURRENT should be used to be able to cancel all notification separately.
For contentIntent:
PendingIntent contentIntent = PendingIntent.getActivity(context, notification_id, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
For actionYesIntent
PendingIntent actionYesIntent = PendingIntent.getBroadcast(context, notification_id, bYesIntent, PendingIntent.FLAG_UPDATE_CURRENT);
For actionNoIntent:
PendingIntent actionNoIntent = PendingIntent.getBroadcast(context, notification_id, bNoIntent, PendingIntent.FLAG_UPDATE_CURRENT);
You are not adding notification_id for cases when Yes or No button is pressed,
Intent bYesIntent = new Intent(context, NotifReceiver.class);
bYesIntent.putExtra(NotificationReceiver.UNIQUE_ID_NAME, notification_id);
bYesIntent.putExtra(NotificationReceiver.YES_ACTION_ID, "yesID");
PendingIntent actionYesIntent = PendingIntent.getBroadcast(context, 0, bYesIntent, 0);
Intent bNoIntent = new Intent(context, NotifReceiver.class);
bNoIntent.putExtra(NotificationReceiver.UNIQUE_ID_NAME, notification_id);
bNoIntent.putExtra(NotificationReceiver.NO_ACTION_ID, "noID");
PendingIntent actionNoIntent = PendingIntent.getBroadcast(context, 0, bNoIntent, 0);

Activity shown immediatly instead of showing a notification

I'm trying to use the AlarmManager to send a notification to the user later in the day, whether he is using the application or not.
I basically pasted what I saw here : http://developer.android.com/guide/topics/ui/notifiers/notifications.html, but obviously something went wrong because instead of showing a notification, the AndroidLauncher Activity is shown.
Here is my code :
public void planNotification() {
AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, AndroidLauncher.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(AndroidLauncher.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
if (currentApiVersion >= 19)
am.setWindow(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, 5000, resultPendingIntent);
else
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 86400000, resultPendingIntent);
}
I'm still new to Intents and PendingIntents, so it may be a dumb mistake.
~~~ ~~~ EDIT : Thank you for your help ! Now that I understood that I need a BroadcastReceiver, I can't get it to work. It looks like onReceive() is never called.
Here is my Main Activity :
#Override
public void planNotification() {
AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
if (currentApiVersion >= 19)
am.setWindow(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, 5000, alarmIntent);
else
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, alarmIntent);
}
And my BroadcastReceiver :
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("ON RECEIVE");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(context, AndroidLauncher.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(AndroidLauncher.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(AndroidLauncher.notifId, mBuilder.build());
}
}
The way you have it, the alarm manager is directly using your resultIntent.
You should move your notification creation code to a BroadcastReceiver:
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, AndroidLauncher.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(AndroidLauncher.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
}
}
And use the AlarmManager to call the BroadcastReceiver:
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
if (currentApiVersion >= 19)
am.setWindow(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, 5000, alarmIntent);
else
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 86400000, alarmIntent);

The notification can't skip to another activity?

my code is
public class AlarmReceiver extends BroadcastReceiver {
public Notification mNotification = null;
public NotificationManager mNotificationManager = null;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "time up!", Toast.LENGTH_SHORT).show();
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotification = new Notification(R.drawable.icon, "tip!",
System.currentTimeMillis());
mNotification.contentView = new RemoteViews(context.getPackageName(),
R.layout.notification);
mNotification.contentView.setTextViewText(R.id.tv_tip, "click to see the description");
Intent notificationIntent = new Intent(context,NotificationTip.class);
notificationIntent.putExtra("description", intent.getStringExtra("description")) ;
//notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
mNotification.contentIntent = contentIntent;
mNotificationManager.notify(0, mNotification);
}
}
While when I click the item in notification ,I can't get to NotificationTip activity,so what's wrong with this code?
following line
Intent notificationIntent = new Intent(context,NotificationTip.class);
needs to be
Intent notificationIntent = new Intent("X");
Where X is the intent action name. this you have to add as intent filter in your android manifest file.

Categories

Resources