I'm trying to send an android notification but it keeps failing at the mbuilder.build() part. I do have an alert dialog right after in the same method. I'm posting my code below
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.noteiconcon)
.setContentTitle("Finished search")
.setContentText("We found your account");
System.out.println("failed after setText");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
System.out.println("failed after result intent");
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
System.out.println("taskstackbuilder passed");
stackBuilder.addParentStack(MainActivity.class);
System.out.println("stackbuilder.appParentstack passed");
stackbuilder.addNextIntent(resultIntent);
System.out.println("stackbuilder.addnextintent passed");
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
System.out.println("pending intent passed");
mBuilder.setContentIntent(resultPendingIntent);
System.out.println("mbuilder.setcontentintent passed");
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
System.out.println("notification manager passed");
// mId allows you to update the notification later on.
mNotificationManager.notify(mId,mBuilder.build());
System.out.println("notificationManager.notify passed"+ mId);
I already added the meta data task but the log cat says.
Bogus static initialization, type 4 in field type Landroid/support/v4/app/NotificationCompat$NotificationCompatImpl; for Landroid/support/v4/app/NotificationCompat; at index 1
Like I said I added the meta data tag and this is being called in an asychtask after an alert dialog. Ive commented out the alert dialog but it still works.
If I drop the last line .notify it doesn't crash but obviously doesn't send a notification.
I had to use a different notification method which it accepted the notification then.
// Set the icon, scrolling text and timestamp
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String MyText = "Finished searching";
Notification mNotification = new Notification(R.drawable.passicon, MyText, System.currentTimeMillis() );
//The three parameters are: 1. an icon, 2. a title, 3. time when the notification appears
String MyNotificationTitle = "Finished Searching";
String MyNotificationText = "We can't find your password.";
Intent MyIntent = new Intent(this, MainActivity.class);
PendingIntent StartIntent = PendingIntent.getActivity(getApplicationContext(),0,MyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//A PendingIntent will be fired when the notification is clicked. The FLAG_CANCEL_CURRENT flag cancels the pendingintent
mNotification.setLatestEventInfo(getApplicationContext(), MyNotificationTitle, MyNotificationText, StartIntent);
int NOTIFICATION_ID = 1;
notificationManager.notify(NOTIFICATION_ID , mNotification);
//We are passing the notification to the NotificationManager with a unique id.
Related
I'm using example code to create a notification, which I then want to handle in onNewIntent() if my App is already running. However, onNewIntent() was not being called. I searched for a few hours and no one seemed to have a proper answer--just some workarounds.
I had to search forever to find the solution here: Android OnNewIntent not called and the answer is not actually explained.
Question
Can anyone explain why we need the lines:
resultIntent.setAction(Intent.ACTION_MAIN);
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
in order to receive the notification through onNewIntent()? The App launches just fine without them, but will always go through onCreate() instead.
Example Code
public void createNotification(String s){
// The id of the channel.
String CHANNEL_ID = "my_channel_01";
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon_missing)
.setContentTitle(getString(R.string.notification_channel_name))
.setContentText(R.string.text);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.setAction(Intent.ACTION_MAIN);
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your app to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mNotificationId is a unique integer your app uses to identify the
// notification. For example, to cancel the notification, you can pass its ID
// number to NotificationManager.cancel().
Notification n = mBuilder.build();
n.flags = n.flags | Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(1, n);
}
I am working on an application in which a notification has to fired after some time. The code for firing a notification is in a method. I want to execute this method after some time the application has been exited. I tried Alarm Manager, it runs fine but it needs an intent. I don't want to show an activity , I just want to show notification in status bar. Is there any other way to do this? The method I want to run is fireNotification. Using Alarm Manager seems logical but It can fire an Intent not a method. I need some way to run this method when application is not running.
private void fireNotification(long Id, String Title)
{
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(Title)
.setContentText("Tap here to view")
.setSound(soundUri)
.setAutoCancel(true);
Intent resultIntent = new Intent(this, ViewActivity.class);
resultIntent.putExtra("noteId", noteId);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(ViewNoteActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = safeLongToInt(safeLongToInt(Id));
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
public static int safeLongToInt(long l) {
if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
throw new IllegalArgumentException
(l + " cannot be cast to int without changing its value : Notification ID.");
}
return (int) l;
}
I have a problem. What I want to do is, I just want to display a message in notification bar at frequent time of interval. For that I used two notification methods they are:
Notification notification = new Notification(icon, message, when);
......
notification.setLatestEventInfo(context, title, subTitle, intent);
Currently I am using API level 19. So I came to know above ones are deprecated. I was suggested to use Notification.builder. But after using that I am not getting proper output. Can anyone show me the code how to use Notification.Builder for above 2 statements...
Any help will be appreciated.
you can use this...
public static void createNotification(Context context, Long data) {
Random rnd = new Random();
int i = rnd.nextInt();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.app_icon)
.setContentTitle("Logo").setContentText("text");
mBuilder.setAutoCancel(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, activity.class);
resultIntent.putExtra(StringUtils.SESSIONID, data);
// The stack builder object will contain an artificial back stack for
// the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(activity.class);
// stackBuilder.editIntentAt(index);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(i, mBuilder.build());
Notification noti = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setSubText(subTitle)
.setContentIntent(pendingIntent)
.build();
This is example is from here: Notification.Builder
To set the time you could use the method setWhen(long timestamp);
I've made an app which manage sms, I've created the notifications but when I click on them it starts another activity, I would like to know how to check if an activity has been stopped and resume it.
Here is the code used to create the pendingintent:
private void createNotification(SmsMessage sms, Context context){
final NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
String contentTitle = "";
// construct the Notification object.
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(contentTitle)
.setContentText(sms.getMessageBody())
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(getIconBitmap())
.setNumber(nmessages);
builder.setAutoCancel(true);
//(R.drawable.stat_sample, tickerText,
// System.currentTimeMillis());
// Set the info for the views that show in the notification panel.
//notif.setLatestEventInfo(this, from, message, contentIntent);
/*
// On tablets, the ticker shows the sender, the first line of the message,
// the photo of the person and the app icon. For our sample, we just show
// the same icon twice. If there is no sender, just pass an array of 1 Bitmap.
notif.tickerTitle = from;
notif.tickerSubtitle = message;
notif.tickerIcons = new Bitmap[2];
notif.tickerIcons[0] = getIconBitmap();;
notif.tickerIcons[1] = getIconBitmap();;
*/
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, BasicActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
// Ritardo in millisecondi
builder.setContentIntent(resultPendingIntent);
nm.notify(R.drawable.ic_drawer, builder.build());
You need to set flags in your PendingIntent's ...like FLAG_UPDATE_CURRENT.
Here is all on it.
http://developer.android.com/reference/android/app/PendingIntent.html
Edit 1: I misunderstood the question.
Here are links to topics that had the same issue but are resolved:
resuming an activity from a notification
Notification Resume Activity
Intent to resume a previously paused activity (Called from a Notification)
Android: resume app from previous position
Please read the above answers for a full solution and let me know if it works.
Add this line to the corresponding activity in manifest file of your app.
android:launchMode="singleTask"
eg:
<activity
android:name=".Main_Activity"
android:label="#string/title_main_activity"
android:theme="#style/AppTheme.NoActionBar"
android:launchMode="singleTask" />
Try with this.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(mContext.getString(R.string.notif_title))
.setContentText(mContext.getString(R.string.notif_msg));
mBuilder.setAutoCancel(true);
// Set notification sound
Uri alarmSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
Intent resultIntent = mActivity.getIntent();
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resultIntent.setAction(Intent.ACTION_MAIN);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
The only solution that actually worked for me after doing a lot of search is to do the following :
here you are simply launching of the application keeping the current stack:
//here you specify the notification properties
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).set...(...).set...(..);
//specifying an action and its category to be triggered once clicked on the notification
Intent resultIntent = new Intent(this, MainClass.class);
resultIntent.setAction("android.intent.action.MAIN");
resultIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//building the notification
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, builder.build());
If the aforementioned solution didn't work, try to change the activity launch mode in your androidManifest.xml file from standard to singleTask.
<activity>
...
android:launchMode="singleTask
...
</activity>
This will prevent the activity from having multiple instances.
I want to add a tap action (exit (finish)) to a notification.
I'm making a simple app with several classes, and I want them all finished when I tap the notification.
Here is my notification code:
mMN = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification n = new Notification();
n.icon = R.drawable.ic_launcher;
n.tickerText = "Tap this notification to exit";
n.when = System.currentTimeMillis();
Intent nid = new Intent(MainActivity.this, stopservice.class);
PendingIntent ci = PendingIntent.getActivity(this, 0, nid,PendingIntent.FLAG_UPDATE_CURRENT);
CharSequence ct = "TAP";
CharSequence tt = "Tap here to exit";
n.setLatestEventInfo(this,ct,tt,ci);
mMN.notify(NOTIFICATION_ID, n);
I'm making a reference to stopservice class (where it is my stop service code) on Intent nid, but I'm not quite sure if it's a correct reference.
hope that my question is clear.
You should be using a notification builder:
mMN = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent nid = new Intent(MainActivity.this, stopservice.class);
// If you were starting a service, you wouldn't using getActivity() here
PendingIntent ci = PendingIntent.getActivity(MainActivity.this, NOTIFICATION_ID, nid, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(MainActivity.this);
builder.setContentTitle("TAP")
.setContentText("Tap here to exit")
.setTicker("Tap this notification to exit")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(ci)
.setAutoCancel(true); // auto cancel means the notification will remove itself when pressed
mMN.notify(NOTIFICATION_ID, builder.getNotification());
Your code is set to launch the Activity "stopservice" (which technically should be "StopService" with naming conventions), are you sure that class is an Activity?
Also, make sure your Activity is registered in your app's manifest:
<activity android:name="[package-name].stopservice" android:label="#string/app_name"/>