I'm a beginner and I'm trying to show some status bar notification on the user.I found out that API23+ does not support the method setLatestInfo, so my compiler finds it as an error. What other method should I use instead of this to turn on notifications?
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import androidx.annotation.RequiresApi;
import static android.app.PendingIntent.getActivity;
import static android.content.Context.NOTIFICATION_SERVICE;
public class Settings extends AppCompatActivity {
Switch simpleswitch1;
Switch simpleswitch2;
private Notification notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleswitch1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Notify("Title", "Message");
}
});
simpleswitch2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
notification.defaults |= Notification.DEFAULT_SOUND;
}});}
private void Notify(String notificationTitle, String notificationMessage) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.notification, "New message", System.currentTimeMillis());
Intent notificationIntent = new Intent(Settings.this, Settings.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(Settings.this, notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(9999, notification);
}
}
setLatestEventInfo is deprecated, was removed in api 23. So if your SDK version is set to api 23+ you'll have this issue and you should use NotificationCompat.Builder instead.
An example :
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
private void Notify(String notificationTitle, String notificationMessage) {
Intent notificationIntent = new Intent(Settings.this, Settings.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification)
.setContentTitle("New message")
.setContentText("My notification")
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.build();
Notification notification = builder.getNotification();
notificationManager.notify(11 /*An identifier for this notification unique within your application.*/, notification);
}
I suggest to read the official documentation about notification here.
Related
Why is deleteIntent(PendingIntent) not called when notification is canceled?
I am doing this android tutorial on Notifications and in the 'extra challenge', am using deleteIntent.
However it is not invoked at all. Running in the emulator on API 27.
When I swipe the notification to cancel, the cancelNotification() method is not called.
In the docs, I see the watermark 'deprecated' on the page but it's not in the text.
Not sure if it's actually deprecated or if I am using deleteIntent() wrongly.
https://codelabs.developers.google.com/codelabs/android-training-notifications/#6
In the NotifyMe app, there is one use case in which the state of your
buttons does not match the state of the app: when a user dismisses a
notification by swiping it away or clearing the whole notification
drawer. In this case, your app has no way of knowing that the
notification was canceled and that the button state must be changed.
Create another pending intent to let the app know that the user has
dismissed the notification, and toggle the button states accordingly.
Hint: Check out the NotificationCompat.Builder class for a method that
delivers an Intent if the user dismisses the notification.
package com.notifyme;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static final String PRIMARY_CHANNEL_ID = "primary_notification_channel";
private NotificationManager mNotifyManager;
private static final int NOTIFICATION_ID = 0;
private static final String ACTION_UPDATE_NOTIFICATION =
"com.example.android.notifyme.ACTION_UPDATE_NOTIFICATION";
private static final String ACTION_CANCEL_NOTIFICATION =
"com.example.android.notifyme.ACTION_CANCEL_NOTIFICATION";
private NotificationReceiver mReceiver = new NotificationReceiver();
public class NotificationReceiver extends BroadcastReceiver {
public NotificationReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case ACTION_UPDATE_NOTIFICATION:
updateNotification();;
break;
case ACTION_CANCEL_NOTIFICATION:
cancelNotification();
break;
}
}
}
public void createNotificationChannel() {
mNotifyManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >=
android.os.Build.VERSION_CODES.O) {
// Create a NotificationChannel
NotificationChannel notificationChannel = new NotificationChannel(PRIMARY_CHANNEL_ID,
"Mascot Notification", NotificationManager
.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Notification from Mascot");
mNotifyManager.createNotificationChannel(notificationChannel);
}
}
private Button button_notify;
private Button button_cancel;
private Button button_update;
public void sendNotification() {
Intent updateIntent = new Intent(ACTION_UPDATE_NOTIFICATION);
PendingIntent updatePendingIntent = PendingIntent.getBroadcast
(this, NOTIFICATION_ID, updateIntent, PendingIntent.FLAG_ONE_SHOT);
Intent cancelIntent = new Intent(ACTION_CANCEL_NOTIFICATION);
PendingIntent cancelPendingIntent = PendingIntent.getBroadcast
(this, NOTIFICATION_ID, cancelIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notifyBuilder = getNotificationBuilder();
notifyBuilder.addAction(R.drawable.ic_update, "Update Notification", updatePendingIntent);
notifyBuilder.setDeleteIntent(cancelPendingIntent);
mNotifyManager.notify(NOTIFICATION_ID, notifyBuilder.build());
setNotificationButtonState(false, true, true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_notify = findViewById(R.id.notify);
button_notify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendNotification();
}
});
createNotificationChannel();
button_update = findViewById(R.id.update);
button_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Update the notification
updateNotification();
}
});
button_cancel = findViewById(R.id.cancel);
button_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Cancel the notification
cancelNotification();
}
});
registerReceiver(mReceiver,new IntentFilter(ACTION_UPDATE_NOTIFICATION));
setNotificationButtonState(true, false, false);
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
public void updateNotification() {
Bitmap androidImage = BitmapFactory
.decodeResource(getResources(),R.drawable.mascot_1);
NotificationCompat.Builder notifyBuilder = getNotificationBuilder();
notifyBuilder.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(androidImage)
.setBigContentTitle("Notification Updated!"));
mNotifyManager.notify(NOTIFICATION_ID, notifyBuilder.build());
setNotificationButtonState(false, false, true);
}
public void cancelNotification() {
mNotifyManager.cancel(NOTIFICATION_ID);
setNotificationButtonState(true, false, false);
}
private NotificationCompat.Builder getNotificationBuilder(){
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent notificationPendingIntent = PendingIntent.getActivity(this,
NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(this, PRIMARY_CHANNEL_ID)
.setContentTitle("You've been notified!")
.setContentText("This is your notification text.")
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(notificationPendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setAutoCancel(true);
return notifyBuilder;
}
void setNotificationButtonState(Boolean isNotifyEnabled,
Boolean isUpdateEnabled,
Boolean isCancelEnabled) {
button_notify.setEnabled(isNotifyEnabled);
button_update.setEnabled(isUpdateEnabled);
button_cancel.setEnabled(isCancelEnabled);
}
}
Update: From CommonsWare's helpful answer below, I corrected the registration of the receiver to use multiple Actions for the same IntentFilter. However it still failed even though I tried all the different flags for the PendingIntent.
When you press the Update button in the notification and then swipe right, the buttons in the Activity do not reset their states because the PendingIntent is not firing.
Here is my updated code.
package com.onedropaflame.notifyme;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static final String PRIMARY_CHANNEL_ID = "primary_notification_channel";
private NotificationManager mNotifyManager;
private static final int NOTIFICATION_ID = 0;
private static final String ACTION_UPDATE_NOTIFICATION =
"com.example.android.notifyme.ACTION_UPDATE_NOTIFICATION";
private static final String ACTION_CANCEL_NOTIFICATION =
"com.example.android.notifyme.ACTION_CANCEL_NOTIFICATION";
private NotificationReceiver mReceiver = new NotificationReceiver();
public class NotificationReceiver extends BroadcastReceiver {
public NotificationReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case ACTION_UPDATE_NOTIFICATION:
updateNotification();;
break;
case ACTION_CANCEL_NOTIFICATION:
cancelNotification();
break;
}
}
}
public void createNotificationChannel() {
mNotifyManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >=
android.os.Build.VERSION_CODES.O) {
// Create a NotificationChannel
NotificationChannel notificationChannel = new NotificationChannel(PRIMARY_CHANNEL_ID,
"Mascot Notification", NotificationManager
.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Notification from Mascot");
mNotifyManager.createNotificationChannel(notificationChannel);
}
}
private Button button_notify;
private Button button_cancel;
private Button button_update;
public void sendNotification() {
Intent updateIntent = new Intent(ACTION_UPDATE_NOTIFICATION);
PendingIntent updatePendingIntent = PendingIntent.getBroadcast
(this, NOTIFICATION_ID, updateIntent, PendingIntent.FLAG_ONE_SHOT);
Intent cancelIntent = new Intent(ACTION_CANCEL_NOTIFICATION);
PendingIntent cancelPendingIntent = PendingIntent.getBroadcast
(this, NOTIFICATION_ID, cancelIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notifyBuilder = getNotificationBuilder();
notifyBuilder.addAction(R.drawable.ic_update, "Update Notification", updatePendingIntent);
notifyBuilder.setDeleteIntent(cancelPendingIntent);
mNotifyManager.notify(NOTIFICATION_ID, notifyBuilder.build());
setNotificationButtonState(false, true, true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_notify = findViewById(R.id.notify);
button_notify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendNotification();
}
});
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_CANCEL_NOTIFICATION);
intentFilter.addAction(ACTION_UPDATE_NOTIFICATION);
createNotificationChannel();
registerReceiver(mReceiver,intentFilter);
button_update = findViewById(R.id.update);
button_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Update the notification
updateNotification();
}
});
button_cancel = findViewById(R.id.cancel);
button_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Cancel the notification
cancelNotification();
}
});
setNotificationButtonState(true, false, false);
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
public void updateNotification() {
Bitmap androidImage = BitmapFactory
.decodeResource(getResources(),R.drawable.mascot_1);
NotificationCompat.Builder notifyBuilder = getNotificationBuilder();
notifyBuilder.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(androidImage)
.setBigContentTitle("Notification Updated!"));
mNotifyManager.notify(NOTIFICATION_ID, notifyBuilder.build());
setNotificationButtonState(false, false, true);
}
public void cancelNotification() {
mNotifyManager.cancel(NOTIFICATION_ID);
setNotificationButtonState(true, false, false);
}
private NotificationCompat.Builder getNotificationBuilder(){
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent notificationPendingIntent = PendingIntent.getActivity(this,
NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(this, PRIMARY_CHANNEL_ID)
.setContentTitle("You've been notified!")
.setContentText("This is your notification text.")
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(notificationPendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setAutoCancel(true);
return notifyBuilder;
}
void setNotificationButtonState(Boolean isNotifyEnabled,
Boolean isUpdateEnabled,
Boolean isCancelEnabled) {
button_notify.setEnabled(isNotifyEnabled);
button_update.setEnabled(isUpdateEnabled);
button_cancel.setEnabled(isCancelEnabled);
}
}
It appears as though you are not registering a receiver for ACTION_CANCEL_NOTIFICATION, just ACTION_UPDATE_NOTIFICATION.
Commonsware posted the correct answer about both actions needing to be registered.
However that was not sufficient. I corrected the registration of the receiver to use multiple Actions for the same IntentFilter. However it still failed even though I tried all the different flags for the PendingIntent. When you press the Update button in the notification and then swipe right, the buttons in the Activity do not reset their states because the PendingIntent is not firing.
Solution: I found that I had to set the cancelPendingIntent again during the updateNotification(). I do not know the reason why it is lost.
public void updateNotification() {
Bitmap androidImage = BitmapFactory
.decodeResource(getResources(),R.drawable.mascot_1);
NotificationCompat.Builder notifyBuilder = getNotificationBuilder();
notifyBuilder.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(androidImage)
.setBigContentTitle("Notification Updated!"));
// >>>>> SET AGAIN! >>>>>>>>>
Intent cancelIntent = new Intent(ACTION_CANCEL_NOTIFICATION);
PendingIntent cancelPendingIntent = PendingIntent.getBroadcast
(this, NOTIFICATION_ID, cancelIntent, PendingIntent.FLAG_ONE_SHOT);
notifyBuilder.setDeleteIntent(cancelPendingIntent);
// >>>>>>>>>>>>>>
mNotifyManager.notify(NOTIFICATION_ID, notifyBuilder.build());
setNotificationButtonState(false, false, true);
}
I'm having an issue with trying to run an activity when a notification is clicked.
How and where create a Pending Intent, which must run my app after i click on notification..? I dont have problems with notification. But my notification after click doesnt work. Please help, thanks ..............................................................................................................................................................................................................................................
package pl.wat.pz.myapplication;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
private static final String GROUP_UPDATES="group_updates";
private static final String CHANNEL_CONTENT="channel_content";
private static final int NOTIF_ID_CONTENT=1337;
private NotificationManager mgr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgr=getSystemService(NotificationManager.class);
if (mgr.getNotificationChannel(CHANNEL_CONTENT)==null) {
initContentChannel();
}
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actions, menu);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.settings) {
Intent i=new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
i.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
public void raiseContent(View view) {
Notification n=new NotificationCompat.Builder(MainActivity.this, CHANNEL_CONTENT)
.setContentTitle(getString(R.string.notif_content_title))
.setContentText(getString(R.string.notify_content_text))
.setSmallIcon(android.R.drawable.stat_sys_warning)
.build();
mgr.notify(NOTIF_ID_CONTENT, n);
}
private void initContentChannel() {
NotificationChannel channel=
new NotificationChannel(CHANNEL_CONTENT,
getString(R.string.channel_name_content),
NotificationManager.IMPORTANCE_LOW);
channel.setGroup(GROUP_UPDATES);
mgr.createNotificationChannel(channel);
}
}
You use of intent to your class to extend of FirebaseMessagingService and your intent code is like to below :
Intent intent = new Intent(context, yourClass.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
requestCode,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
// then set to notification
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(title);
bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
bigPictureStyle.bigPicture(bitmap);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(bigPictureStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Config.NOTIFICATION_ID_BIG_IMAGE, notification);
i am getting the notification in firebase but when i am clicking on the notification i am getting the MainActivity page i want to get Nextpage activity
i am not getting it can any one help please
here is the code below
MainActivity
package com.example.reema.firebase1;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
public class MainActivity extends ActionBarActivity {
private String TAG;
//private static final String TAG = ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tkn = FirebaseInstanceId.getInstance().getToken();
Toast.makeText(MainActivity.this, "Current token [" + tkn + "]",
Toast.LENGTH_LONG).show();
Log.d("App", "Token [" + tkn + "]");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
FireMsgService
package com.example.reema.firebase1;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FireMsgService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("Msg", "Message received [" + remoteMessage + "]");
// Create Notification
// Intent intent = new Intent(this, Nextpage.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//
//
// PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
// intent, PendingIntent.FLAG_ONE_SHOT);
//
// NotificationCompat.Builder notificationBuilder = new
// NotificationCompat.Builder(this)
// .setSmallIcon(R.drawable.firebase_icon)
// .setContentTitle("Message")
// .setContentText(remoteMessage.getNotification().getBody())
// .setAutoCancel(true)
// .setContentIntent(pendingIntent);
//
// NotificationManager notificationManager =
// (NotificationManager)
// getSystemService(Context.NOTIFICATION_SERVICE);
//
// notificationManager.notify(1410, notificationBuilder.build());
// Context context;
Context context = getApplicationContext();
int icon = R.drawable.firebase_icon;
CharSequence tickerText = "Call Blocker";
CharSequence title = "Call Blocker";
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, tickerText, when);
Intent notificationIntent = new Intent(context, Nextpage.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.firebase_icon)
.setContentTitle("Message")
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setContentIntent(intent);
//notification.setLatestEventInfo(context, title, tickerText, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
}
NextPage
package com.example.reema.firebase1;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Nextpage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
TextView textView = (TextView) findViewById(R.id.informationTextView);
textView.setText( "You clicked the button {0} times in the previous activity.");
}
}
The reason is you are creating a NotificationBuilder however you don't actually get your Notification from it. Alter your code such that:
Context context = getApplicationContext();
int icon = R.drawable.firebase_icon;
CharSequence tickerText = "Call Blocker";
CharSequence title = "Call Blocker";
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, Nextpage.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.firebase_icon)
.setContentTitle("Message")
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setContentIntent(intent);
Notification notification = notificationBuilder.build();
//notification.setLatestEventInfo(context, title, tickerText, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
I'm creating an app that has to show more than one notification. I was looking for information and I use this code in class:
Notification noti = new NotificationCompat.Builder(this)
I can show more than one notifications on the bar, but the problem is that when I click on it, it only shows the first one. I think it's because the id that the pending intent obtain is always the same, but I send a different one.
Notification Activity: Show a new notification when I click the button.
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
public class NotificationActivity extends Activity {
int notificationID = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_example);
}
public void onClick(View v){
displayNotification();
}
protected void displayNotification(){
Intent i = new Intent(this, NotificationView.class);
i.putExtra("notificationID", notificationID);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
CharSequence ticker ="Display";
CharSequence contentTitle = "Title";
CharSequence contentText = "Description";
Notification noti = new NotificationCompat.Builder(this)
.setContentIntent(pendingIntent)
.setTicker(ticker)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_launcher)
.addAction(R.drawable.ic_launcher, ticker, pendingIntent)
.setVibrate(new long[] {100, 250, 100, 500})
.build();
Log.d("Send Notification", "id: "+notificationID);
nm.notify(notificationID, noti);
notificationID++;
}
}
As you can see i increase the notificationID every time i click the button for send a different id.
Notification View: Shows the id of the notification.
import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
import android.widget.TextView;
public class NotificationView extends Activity {
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
txt= (TextView) findViewById(R.id.txt1);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
txt.setText("Notification ID: "+getIntent().getExtras().getInt("notificationID"));
// Cancel notification
nm.cancel(getIntent().getExtras().getInt("notificationID"));
}
}
Hhere only shows the id of the notification, but it's always 1.
Any idea about what happend? I'm testing it on a 2.3 device.
just put in order to solve the issue:
int num = (int) System.currentTimeMillis();
PendingIntent resultPendingIntent=PendingIntent.getActivity(this,num,resultIntent,Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
mNotificationManager.notify(num, mNotifyBuilder.build());*
1) PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, i, 0);
..............Your code ........................
nm.notify(1, noti);
2)PendingIntent pendingIntent2 = PendingIntent.getActivity(this, 2, i, 0);
..............Your code ........................
nm2.notify(2, noti);
3)PendingIntent pendingIntent3 = PendingIntent.getActivity(this, 3, i, 0);
..............Your code ........................
nm3.notify(3, noti);
4)................same as above
5)................same as above
I am making a sample app just for educational purposes, where I create a notification every minute. I also have a button to cancel the alarm.
What I do is that when the notification comes, I click it and click the unset button I have set to run unsetAlarm(). But it continues to bother me every minute.
How do I stop the notifications? Could it be that the activity is somehow duplicated? If this is the case, how do I ensure there is only one instance of the MainActivity?
MainActivity class
package no.perandersen.notifyontimeexample;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
private AlarmManager alarmManager;
private PendingIntent notifyIntent;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
public void setAlarm(View v) {
Intent myIntent = new Intent(MainActivity.this,
NotificationService.class);
notifyIntent = PendingIntent.getService(MainActivity.this, 0,
myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 1);
Log.v(TAG, "time for alarm trigger:" + calendar.getTime().toString());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1 * 60 * 1000, notifyIntent);
}
public void unsetAlarm(View v) {
alarmManager.cancel(notifyIntent);
Log.v(TAG, "cancelling notification");
}
}
NotificationService class
package no.perandersen.notifyontimeexample;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class NotificationService extends Service {
private NotificationManager nm;
private static final String TAG = "NotificationService";
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.v(TAG, "on onCreate");
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Log.v(TAG, "on onStartCommand");
Intent mainActivityIntent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, mainActivityIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("bothering you")
.setContentText("Just bothering you from example code")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults|= Notification.DEFAULT_LIGHTS;
nm.notify(0, notification);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
The problem is that to cancel an Alarm you need to recreate the PendingIntent exactly how you created it when you set the alarm. So change your unsetAlarm() to
public void unsetAlarm(View v) {
Intent myIntent = new Intent(MainActivity.this,
NotificationService.class);
notifyIntent = PendingIntent.getService(MainActivity.this, 0,
myIntent, 0); // recreate it here before calling cancel
alarmManager.cancel(notifyIntent);
Log.v(TAG, "cancelling notification");
}