I am working on an application that will show a notification when the alarm is triggered. The notification will show only when the application is still running however I wish the notification will stay even when the application is closed so when the user select the notification it will run the application again. Is there any way on doing it? Any help will be greatly appreciated. I will also appreciated any examples or tutorials provided. Thank you very much.
How about that I'm using
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
and I want to push notification in future by alarmMenager
It works while app is still running, while I call allarm menager to set notify in futer and close app my notification didn't show.
WHat i have to do ?
here u got my event sender:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, HOUR_OF_DAY);
cal.set(Calendar.MINUTE, MINUTE);
//cal.add(Calendar.SECOND, SECOND_OF_DAY);
Intent intent = new Intent(UnityPlayer.currentActivity, TimeAlarm.class);
intent.putExtra("alarm_status", statusMessage);
intent.putExtra("alarm_title", title);
intent.putExtra("alarm_content", content);
Log.i("SenderEvent ", "przygotowane dane");
PendingIntent sender = PendingIntent.getBroadcast(UnityPlayer.currentActivity.getApplicationContext(), REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
And Reciever:
Bundle bundle = intent.getExtras();
String statusMessage = bundle.getString("alarm_status");
String title = bundle.getString("alarm_title");
String content = bundle.getString("alarm_content");
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif =new Notification();//R.drawable.ic_launcher,statusMessage, System.currentTimeMillis());;
//notif.largeIcon = bitmap;
notif.icon =2130837504;
notif.tickerText=statusMessage;
notif.when= System.currentTimeMillis();
/*
new Notification(0,
statusMessage, System.currentTimeMillis());*/
notif.setLatestEventInfo(context, title, content, contentIntent);
nm.notify(NOTIFY_ME_ID, notif);
Whats wrong with that to push notification in the future while app is close ?
First you need to create your notification using a service. I had this same question before. I was using phonegap, and creating the notifications from a plugin, but it turns out only services can run in the background. In the service I then add my code to create the notification, and for the intent I use a broadcast receiver.
notificationManager = (NotificationManager) context.getSystemService(android.content.ContextWrapper.NOTIFICATION_SERVICE);
note = new Notification(imageResource, tickerText, System.currentTimeMillis() );
// Intent notificationIntent = new Intent(context, path.to.class);
Intent notificationIntent = new Intent(context, package.path.to.receiver.class);
notificationIntent.setAction(Intent.ACTION_VIEW);
notificationIntent = notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
contentIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
note.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
As you can see in the code above I commented out getActivity, and changed it to getBroadcast. This being run in a service means you can get notifications while app is closed. For the intent in the receiver to be able to open your app if closed add
...
#Override
public final void onReceive(Context context, Intent intent) {
Log.v('TAG','TEST');
//start activity
Intent i = new Intent();
i.setClassName("package.path", "package.path.mainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
...
And xml
<receiver android:name="path.to.receiver" android:label="#string/app_name">
<intent-filter>
<action android:name="path.to.receiver.BROADCAST" />
</intent-filter>
</receiver>
I hope this helps
Related
I am creating a research app that should prompt the user 4 times a day to enter their mood - by sending a notification, which when clicked launches the correct Activity. I am able to schedule these notifications using AlarmManager, however only the last scheduled notification ever shows. So although I schedule them for 9AM, 2PM, 5PM, and 8PM, it only ever sends a notification at 8PM.
How can I get all of the scheduled notifications to show?
Here is my code for setting (one of) the alarms (from a notification manager class). Note that al alarms are set using the same instance of AlarmManager:
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), createPendingIntent(9, this));
Here is the createPendingIntent method (in the same notification manager class):
public static PendingIntent createPendingIntent(int hour, Context c){
Intent notificationIntent = new Intent(c, AlarmBroadcastReceiver.class);
notificationIntent.putExtra("time", hour);
PendingIntent pendingIntent = PendingIntent.getBroadcast(c, 0 , notificationIntent , PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
Here is the BroadcastReceiver for the alarm:
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationSender.createNotification(context);
}
}
And finally the createNotification method:
public static void createNotification(Context c){
Log.e("notif?", "creating");
Intent intent = new Intent(c, UpdateMoodActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
int notificationId = new Random().nextInt();
PendingIntent pendingIntent = PendingIntent.getActivity(c, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(c, "com.lizfltn.phdapp.notifChannelID")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("SoftMood")
.setContentText("Please record your mood")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(c);
notificationManager.notify(notificationId, builder.build());
}
Yes I know this isn't the best-practice way of doing things, or even the neatest, but unfortunately I need to get code working ahead of writing good code :P
I've tried various configurations of setting the alarm, e.g. using elapsed realtime instead of RTC, only setting the alarm, setting the exact alarm, etc, but there might be something fundamental I'm not understanding about how those work.
Any help appreciated!
Can you try with same id in pending intent and notify.?
Notification id in createNotification() method is random id.
int notificationId = new Random().nextInt();
and id used in createPendingIntent method is 0.
PendingIntent pendingIntent = PendingIntent.getBroadcast(c, 0 , notificationIntent , PendingIntent.FLAG_UPDATE_CURRENT);
Can you try with using same value for second parameter of getBroadcast?
Not sending notification at selected time, when I ran my code, directly showed notification
and showed error as well
Here is the error message: E/NotificationManager: notifyAsUser: tag=null, id=12345, user=UserHandle{0}
I thought the error message was due to Build.VERSION.SDK_INT, but after adding that, the error message is still there.
Place all of these under onCreate:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 13);
calendar.set(Calendar.MINUTE,9)
;
Intent intent = new Intent ();
intent.setAction("com.example.Broadcast");
PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// PendingIntent alarmIntent = PendingIntent.getBroadcast(this,0, intent,0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, contentIntent);
and here is the extend.
public class wakeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
setNotification(context);
}
protected void setNotification(Context context){
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
String ChannelId = "12345";
int uniID = 12345;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,ChannelId )
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("Hi")
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setContentText("Please Rate.");
builder.setContentIntent(contentIntent);
//
// Send notification to your device
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("com.myApp");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"com.myApp",
"My App",
NotificationManager.IMPORTANCE_DEFAULT
);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
manager.notify(uniID, builder.build());
}
}
Can someone please help me with this?
You are very confused.
In your code you call NotificationManager.notify(). This will show the Notification immediately.
You do:
Intent intent = new Intent(this, MainActivity.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this,0, intent,0);
This won't work. You have created a PendingIntent which will be sent via broadcast using an Intent that is for an Activity! What do you want to happen? Do you want an Activity to be launched or do you want a BroadcastReceiver to be triggered?
I think what you want to do is as follows:
Create an Intent for a BroadcastReceiver, wrap that in a PendingIntent using getBroadcast() and pass that to the AlarmManager so that the broadcast Intent will be set at some future time.
Create a class that extends BroadcastReceiver. In onReceive() create the Notification and call NotificationManager.notify() to post the Notification. In the Notification you can set a PendingIntent that opens your Activity so that if the user clicks on the Notification your Activity will be launched. To do this, call PendingIntent.getActivity() and pass an Intent that contains MainActivity.class.
Have a trouble trying to get an alarm manager to work with a notification inside. This is to give the user of the app, a notification on a certain point.
My alarm is setup inside a fragment, with the code as following.
Intent notificationIntent = new Intent(getContext(), DeviceBootReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
int hour = Integer.parseInt(vars.getShowRapport().getFinishTime().split(":")[0]);
int min = Integer.parseInt(vars.getShowRapport().getFinishTime().split(":")[1]);
vars.getShowRapport().getFinishDate().setHours(hour);
vars.getShowRapport().getFinishDate().setMinutes(min);
long futureInMillis = System.currentTimeMillis()+1000*60;
//long futureInMillis = vars.getShowRapport().getFinishDate().getTime();
AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
getFragmentManager().beginTransaction().replace(R.id.makeRapportFragment,fragment).addToBackStack(null).commit();
In my manifest i have
<receiver android:process=":remote" android:name=".DeviceBootReceiver">/receiver>
And finally in my receiver called DeviceBootReceiver i have.
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ejservicebookincon)
.setContentTitle("Rapport finishing")
.setContentText("Rapport on item should be done.");
Intent notificationIntent = new Intent(context, ServiceRapportMain.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
Don't know where my problem is, and my receiver never seems to be activated, so can't check if that part work as of yet. Would like help if someone could point out, where my problem is. And just as a heads up i'm working in Android Studio.
As i wrote in the comment above, the error i had was that i used AlarmManager.ELAPSED_REALTIME_WAKEUP where then one i should have used here was AlarmManager.RTC_WAKEUP
am trying to schedule a notification with desired time and un the below code my desired time if after 10 seconds but i don't know why its showing up the notification instantly , am i doing anything wrong ? or missing anything please correct me if am wrong anywhere , and am using BlueStacks Emulator for testing (built version 4.4.2 Api 19)
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);
// why its showing up instantly insted of after 10 seconds
//alarmManager.setExact(AlarmManager.RTC_WAKEUP,20,broadcast);
Intent intent = new Intent(this , MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent , PendingIntent.FLAG_UPDATE_CURRENT);
Intent switchIntent = new Intent(this, switchButtonListener.class);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, 0);
notification.setSmallIcon(R.drawable.ok);
notification.setWhen(20);
notification.setTicker("you've got a meesage");
notification.setContentTitle("new message");
notification.setContentText("wanna take a ride?");
// notification.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(uniqueID, notification.build());
notification showing up instantly
When you call notificationManager.notify() in your last line, it displays the notification immediately.
I assume that you wanted to use an AlarmManager to display a notification and you don't quite understand what it does. An AlarmManager is used schedule an Intent to be broadcasted. An Intent can be used to perform a variety of task such as starting an Activity or Service. As far as i know it is not possible to use an Intent to display notification.
What you should be looking at is to use postDelayed() method in Handler class. For example:
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
// Create your notification using NotificationCompat.Builder
// and call notificationManager.notify()
}
};
handler.postDelayed(r, /*time to delay for in ms*/);
Edit: If you really want to use AlarmManager and broadcast to display a notification, you will need to extend a BroadcastReceiver and have it listen for your PendingIntent broadcast. Next, you will schedule the PendingIntent to be broadcasted using AlarmManager. When the AlarmManager fire off the PendingIntent after 10 seconds, your BroadcastReceiver will receive the broadcast and call notificationManager.notify() to display the notification. This is quite a roundabout way of displaying notification.
I am using alarm manager to display multiple local notification. The notification works fine, but the sequence of notification is happens only after i clear it from notification bar. The sequence is not happened.
code to pending intent
Intent intent = new Intent(this, TimeAlarm.class);
for(int i=0;i<milliSec.size();i++){
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,intent, PendingIntent.FLAG_ONE_SHOT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),(milliSec.get(i)), pendingIntent);
System.out.println("Calling Alaram...");
Code to display notification
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Sample Notification";
CharSequence message = "Notification different milliseconds ...";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
Notification notif = new Notification(R.drawable.ic_launcher, "Notification Test...", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.flags= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
}
How to do multiple notification sequence without clearing the existing message from notification. Thanks in advance
use this line of code
nm.notify( System.currentTimeMillis(), notif);
You have set it to 1 so every time it overrites notification
You always passing same requestcode in intent. so just need to change request code.
PendingIntent contentIntent = PendingIntent.getActivity(context, request_code, new Intent(), 0);
also need to change notify id.
nm.notify(change_notify_id, notif);