I would like to create two different notifications (with different title, text, content...etc.) and issue them at two different time of the day.
That's my MainActivity code:
First notification:
receiver.putExtra("which", 0);
PendingIntent pendingIntent = PendingIntent.getBroadcast(CountdownActivity.this, 0, receiver,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, after30minutes, pendingIntent);
Second notification:
receiver.putExtra("which", 1);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(CountdownActivity.this, 0, receiver,0);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager2.set(AlarmManager.RTC_WAKEUP, (endInSeconds*1000)-(1800*1000), pendingIntent2);
receiver is an intent between this class and receiver class (that extends broadcast receiver).
That's my NotificationReceiver (extends BroadcastReceiver) code:
#Override
public void onReceive(Context context, Intent intent)
{
Intent intentService = new Intent(context, NotificationService.class);
context.startService(intentService);
}
Finally, that's my NotificationService (extends Service) code:
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
//preparazione variabili
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
countdown = new Intent(this.getApplicationContext(), CountdownActivity.class);
pendingIntent = PendingIntent.getActivity( this.getApplicationContext(),0, countdown,PendingIntent.FLAG_UPDATE_CURRENT);
//costruzione notifica
if(intent.getExtras().getInt("which") == 0) //1 ora
{
notification = new Notification.Builder(getApplicationContext())
.setAutoCancel(true)
.setContentTitle("1 ora")
.setContentText("contenuto")
.setLargeIcon(bm)
.setSmallIcon(R.drawable.ic_launcher)
.setSound(alarmSound)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setLights(Color.BLUE, 3000, 3000)
.setContentIntent(pendingIntent)
.build();
}
else if(intent.getExtras().getInt("which") == 1) //mezz'ora
{
notification = new Notification.Builder(getApplicationContext())
.setAutoCancel(true)
.setContentTitle("Ole")
.setContentText("contenuto")
.setLargeIcon(bm)
.setSmallIcon(R.drawable.ic_launcher)
.setSound(alarmSound)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setLights(Color.BLUE, 3000, 3000)
.setContentIntent(pendingIntent)
.build();
}
//operazioni finali
countdown.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
EDIT
I solved putting a countdown in my NotificationService class.
Where you call notificationManager.notify(0, notification);, you should pass a unique ID instead of 0. So, for instance, it would be sufficient to pass the value of intent.getExtras().getInt("which"). Mostly, I declare these IDs as a public static final int in the class.
As the docs state for NotificationManager#notify(int, android.app.Notification):
Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
http://developer.android.com/reference/android/app/NotificationManager.html
Related
How would I stop the foreground service using the notification it creates in the class?
Intent stopnotificationIntent = new Intent(this, HelloIntentService.class);
//Not sure which is the current action to set
stopnotificationIntent.setAction("ACTION.STOPFOREGROUND_ACTION");
PendingIntent pIntent = PendingIntent.getService(this, 0, stopnotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.addAction(0, "Cancel", pIntent);
startForeground(1111, notificationBuilder.build());
the button is created from .addAction and I want to stop that current foreground service
String ACTION_STOP_SERVICE= "STOP";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (ACTION_STOP_SERVICE.equals(intent.getAction())) {
Log.d(Statics.LOG_TAG,"called to cancel service");
stopSelf();
}
Intent stopSelf = new Intent(this, HelloIntentService.class);
stopSelf.setAction(ACTION_STOP_SERVICE);
PendingIntent pStopSelf = PendingIntent
.getService(this, 0, stopSelf
,PendingIntent.FLAG_CANCEL_CURRENT); // That you should change this part in your code
notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentText("Bla Bla Bla")
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingNotificationIntent)
.addAction(R.drawable.xxxx,"Close", pStopSelf)
.setSound(null)
.build();
startForeground(REQUEST_CODE, notification);
}
I send notifications per 24 hours. It works perfect. I have AlarmReceiver class and i set my alarm repeatedly in my setAlarm() method. The problem is when i logout and re-login(same or different account and without closing app), app is not send notification at all. When i close the app and re-run it works again.
Why it isn't working when i logout and re-login. Any thoughts? Thank you, best regards.
AlarmReceiver Class
public void onReceive(Context context, Intent intent) {
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Selamlar")
.setContentText("bildirim geldi!")
.setSound(alarmSound)
.setWhen(when)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notificationManager.notify(0, builder.build());
}
I'm trying to change the time stamp shown for an Android notification, but I'm always getting the current time instead. Right now I'm creating my notification like this:
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(context.getApplicationContext(), CHANNEL_ID)
...
notificationBuilder.setShowWhen(true)
notificationBuilder.setWhen(exactNotificationTime);
I thought this would be sufficient, but I'm still getting the current time displayed; my phone is a Huawei with Android 6.0 (API level 23). My project is configured with minSdkVersion = 23 and targetSdkVersion = 27.
You need to add time in millisecond in setWhen()
notificationBuilder.setWhen(System.currentTimeMillis())
instead of currentTimeMillis give the time you want.
If you want to show notification at a specific time you may need to use alarm manager as shown below.
First create alarm manager with the time you want to show notification
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Intent notifyIntent = new Intent(getApplicationContext(),showNotification.class);
notifyIntent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
PendingIntent pendingIntent = PendingIntent.getBroadcast(etApplicationContext(),0,notifyIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),1000 * 60 * 60 * 24, pendingIntent);
Then in showNotification class
public class showNotification extends BroadcastReceiver {
public showNotification() {
}
#Override
public void onReceive(Context context, Intent intent) {
sendNotification(context);
}
private void sendNotification(Context context) {
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(context, SecondActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "101";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
#SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_MAX);
//Configure Notification Channel
notificationChannel.setDescription("Game Notifications");
notificationChannel.enableLights(true);
notificationChannel.setVibrationPattern(new long[]{200});
notificationChannel.enableVibration(false);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title.get("Title of notification"))
.setContentText(subText.get("Sub text of notification"))
.setAutoCancel(true)
.setSound(defaultSound)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MAX);
notificationManager.notify(1, notificationBuilder.build());
}
}
Hi i am using IntentService to show notifications to user based on their time set which is stored in notificationCalendar variable. I start service using AlarmManager and when app is in background(Pressed home button) or running i receive notification but when app is swiped from recent apps no notification is received.
I searched for solutions online for not allowing service to destroy so i return START_STICKY in service onStartCaommand and in manifest i have added stopWithTask=false.
I am testing it on MI phone with API level 22.
Here's my code:
private void sendNotification(){
Intent intent = new Intent(this, NotificationService.class);
PendingIntent alarmIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, notificationCalendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
}
Service class to show notifications:
public class NotificationService extends Service {
private static final int NOTIFICATION_ID = 1;
public NotificationService() {
super();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
processStartNotification();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void processStartNotification() {
// Do something. For example, fetch fresh data from backend to create a rich notification?
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Habit Time")
.setContentText("Hey time for your habit")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setSound(alarmSound)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notificationManager.notify(NOTIFICATION_ID, mNotifyBuilder.build());
}
#Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
}
//Manifest file
<service
android:name=".notification.NotificationService"
android:enabled="true"
android:stopWithTask="false"/>
On some phones, you need to add your app to the list of apps allowed to run in the background. Some Huawei, LG and Xiaomi phones have this. If your app is not in this list, swiping the task from the list of recent tasks will kill any background processes and not restart them.
Look in Settings->Battery->Manage Apps Battery Usage
I have set up a notification which will be shown 4 hours after the App being destroyed.
But as I am destroying the App, the notification is coming immediately and also after 4 hours.
Here's my Main Activity's onDestroy():
#Override
public void onDestroy() {
super.onDestroy();
Intent myIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 3600*1000*4, 3600*1000*4, pendingIntent);
}
and here's my AlarmReceiver.class:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent mainIntent = new Intent(context, Main.class);
NotificationManager notificationManager
= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
android.app.Notification noti = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(context, 0, mainIntent,
PendingIntent.FLAG_UPDATE_CURRENT))
.setContentTitle("Title")
.setContentText("It's been so Long!!!")
.setSubText("Please return back to App & Learn more Duas.")
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setVibrate(new long[] {700,700,700,700})
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Important Notification")
.setWhen(System.currentTimeMillis())
.build();
notificationManager.notify(0, noti);
}
}
I want that Notification should be shown after every 4 hours & not immediately of App being destroyed.
Any help would be highly Appreciated.
Thanks in Advance.
It is because of small mistake
just change this line
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 3600*1000*4, 3600*1000*4, pendingIntent);
TO this
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis()+(3600*1000*4)), 3600*1000*4, pendingIntent);