I am using this notifications code:
package com.example.mega;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Tech";
CharSequence message = "Check out our NEW COLLECTION !!";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.icon,
"Check out our NEW COLLECTION !!" , System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);
}
}
As you see I haven't yet added AlarmManager since I have no experience using it ,I am new to android.What should I add to the code to have show the notification every 24 hours ??
Calendar calendar = Calendar.getInstance();
// 8.00 (8 AM)
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(context, 0 , new Intent(context, Your_Class.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
This sets an alarm everyday at 8.00 AM
Or you can use https://github.com/commonsguy/cwac-wakeful. Take a look at the documentation on the link.
Take a look at this: Fire notification at every 24 hours and at exact time of 8 AM
And this: http://blog.blundellapps.com/notification-for-a-user-chosen-time/
Related
I tried to use the setRepeating of AlarmManager, and then I read that the method isn't working anymore in API 26+, so the another solution was to schedule each alarm when the previous is finish. How can I do that?
MainActivity.java
public class MainActivity extends AppCompatActivity {
calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour.getText().toString()));
calendar.set(Calendar.MINUTE, Integer.parseInt(minute.getText().toString()));
calendar.set(Calendar.SECOND, 00);
Intent intent = new Intent(getApplicationContext(), Notification_receiver.class);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
Notification_reciever.java
public class Notification_receiver extends BroadcastReceiver {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, MainActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, time, repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setChannelId(CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
.setContentTitle("Notification Title")
.setContentText("Notification Text")
.setAutoCancel(true);
notificationManager.notify(time, builder.build());
}
How can i create another alarm manager when the previous is finish?
You will need to schedule your next alarm, at the end of BroadcastReceiver
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
...
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextAlarmTimeInMillis(), pendingIntent);
Please note that, due to different battery saving mechanism implemented by different OEMs, AlarmManager is not guarantee to work all the time. Please refer to https://issuetracker.google.com/issues/122098785
In short, AlarmManager is the current best available mechanism, for timed notification to work, even without Internet connection. But, it is not gurantee to work all the time.
Here is example to make alarm every 2 minutes (tested on API 30)
move code to set alarm from MainActivity in own class
public class AlarmExecutor {
public static void makeAlarm(Context context, int minute) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, minute);
Intent intent = new Intent(context, Notification_receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Log.d("Testing", "make alarm at " + calendar.getTime().toString());
}
}
now you can add in
Notification_receiver.java after notificationManager.notify(time, builder.build());
MainActivity
following line
// make alarm in 2 minutes
AlarmExecutor.makeAlarm(context, 2);
that will make an alarm every 2 minutes.
And don't forget to register the receiver in Manifest
<application >
<receiver android:name=".yourReceiver" />
</application>
Introduction:
Through a ToggleButton I make my user to enable or disable the alarm reminder. The alarm remember my user to record their activity one hour after the last time he has entered the app also do not want the alarm to sound at night. This all works fine.
public void each_hour_alarm() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int hour = cal.get(Calendar.HOUR_OF_DAY);
if(hour <= 20 && hour >= 7) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = getBroadcast(getApplicationContext(), 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR, 1);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), broadcast);
stop_alarm_9am();
}else {
stop_each_hour_alarm();
alarm_9am();
}
}
The problem begins when I call a new method: alarm_9am();
The new method raises an alarm at 9 am if the user has not entered before the app. This is where I have the problem. The alarm sounds at 9am, but also, and this is my problem, it also sounds every time I log activity between 21h and 23: 59h.
I do not understand why this happens. Any ideas??
This is de code:
public void alarm_9am() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.buenosdias.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.buenosdias.category.DEFAULT");
PendingIntent broadcast = getBroadcast(getApplicationContext(), 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 1);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), broadcast);}
Code to stop alarm_9am();
public void stop_alarm_9am() {
Intent intentlocal = new Intent("android.media.buenosdias.action.DISPLAY_NOTIFICATION");
intentlocal.addCategory("android.intent.buenosdias.category.DEFAULT");
PendingIntent pilocal = getBroadcast(getApplicationContext(), 100, intentlocal, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pilocal);
pilocal.cancel();
}
And my AlarmReceiver;
public class AlarmReceiver_buenos_dias extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, v_agua.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(v_agua.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Good Morning")
.setContentText("Begin New Day")
.setTicker("Go to app")
.setSmallIcon(R.drawable.logo_launcher_a)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setStyle(new NotificationCompat.BigTextStyle().bigText(""))
.setAutoCancel(true)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}}
My issue is that the alarm sounds between 21h to 23:59 every time I enter in activity and i dont know why. I need not sound the alarm every time I log in activity between 21h and 23:59, I just want alarm_9am(); sounds at 9am
Thanks!
I want to show the user notifications everyday in the same time. For now I only have this code:
My TimeAlarm.class that shows the notifications:
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Nithin";
CharSequence message = "Crazy About Android...";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.ic_launcher,
"Crazy About Android...", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.test);
// r.play();
nm.notify(1, notif);
}
}
And initialization of the notifications to show every 5 seconds:
public void setRepeatingAlarm() {
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
(5 * 1000), pendingIntent);
}
Now my question is how should I modify this code to set the notification to repeat every day in certain time. Example every day in 14:36 o'clock?
The easy-but-inexact way is to change System.currentTimeMillis() to a calculation of 14:36 tomorrow, probably using a Calendar object:
Calendar cal=Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 14);
cal.set(Calendar.MINUTE, 36);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (cal.getTimeInMillis() < System.currentTimeMillis()) {
cal.add(Calendar.DAY_OF_YEAR, 1);
}
I say "easy-but-inexact" because Android 4.4 has changed the behavior of setRepeating() to be inexact, once your android:targetSdkVersion is 19 or higher. If you need exact alarms, you will need to use setExact() and do your own "repeating" (by calling setExact() again when the alarm goes off). You would still use the same Calendar sort of calculation, just on every setExact() call.
there're two problems here. I try to let user select a specific time to make app reminder users to use app. Once user set up a time say 8:00 pm. The notification should pop up every day. However, After I used
"NotificationManager" and "Notification"
first of all, there's nothing pop-up. For example, now is 1:19 am in AU, then, i set-up this app to 1:20 am to display the notification in the status bar as a test.
Secondly, if in my TabBar class i use
nm.cancel(getIntent().getExtras().getInt("NotifID"));
It will get a null pointer exception
Here is my code:
TabBar.class
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.cancel(getIntent().getExtras().getInt("NotifID"));
Notification.class
package com.example.tabpro;
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.view.View;
import android.widget.Button;
import android.widget.TimePicker;
public class SettingNotification extends Activity{
TimePicker timePicker;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_notification);
Button btnset = (Button) findViewById(R.id.btnSetAlarm);
btnset.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
timePicker = (TimePicker) findViewById(R.id.timePicker_settime);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
calendar.set(Calendar.SECOND, 0);
Intent i = new Intent("com.example.tabpro.DisplayNotification");
Intent i2 = new Intent(SettingNotification.this, TabBar.class);
i.putExtra("NotifID", 1);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), 0, i, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), displayIntent);
startActivity(i2);
}
});
}
}
DisplayNotification.class
package com.example.tabpro;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
public class DisplayNotification extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
int notifID = getIntent().getExtras().getInt("NotifID");
Intent i = new Intent("com.example.tabpro.TabBar");
i.putExtra("NotifID", notifID);
PendingIntent detailsIntent = PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.ic_launcher, "Time's up!", System.currentTimeMillis());
CharSequence from = "AlarmManager - Time's up!";
CharSequence message = "This is your alert, courtesy of the AlarmManager";
notif.setLatestEventInfo(this, from, message, detailsIntent);
finish();
}
}
You need to call notify() on your NotificationManager to actually show the Notification. Since you never call this method, your Notification is never shown.
Your NullPointerException is likely a different problem. For that, you should do some debugging yourself. First, you need to determine what is null. Then determine why it is null and fix it. In your code, the most likely candidates for causing the NPE in TabBar are nm, getIntent(), and getExtras().
Hope this helps :
You need to call notify() method to display notification in your notification tray of your device.
Below is the code for that:
Notification notification;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,new Intent(context, YourActivity.class), 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(yourappname).setWhen(0)
.setAutoCancel(true).setContentTitle(yourappname)
.setContentText(yourmessage).build();
notificationManager.notify(0, notification);
Is it possible to show calendar alert in android, so that on the specified date the alert should pop up and remind the user regarding the task.
Sorry, there isn't currently a calendar API in the SDK. You can however implement your own alarm with the AlarmManager showing your own UI at the time you schedule with it.
first of all to set the alert in calendar application you have to make the permit-ion :
Now, that the alarm receiver is set, lets take a look at the class that will set and cancel the alarms:
package SomeApp.SomeApp;
import java.util.Calendar;
import java.lang.String;
import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.os.Bundle;
import android.util.Log;
import android.content.Intent;
import android.widget.Toast;
/**
* When this code is run only one alert will be displayed even though 2 alerts were
* were setup (as one of them will be cancelled later on
*/
public class SomeApp extends ListActivity {
/* for logging - see my tutorial on debuggin Android apps for more detail */
private static final String TAG = "SomeApp ";
protected Toast mToast;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.alert_list);
try {
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(SomeApp.this, AReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+30000, sender); // to be alerted 30 seconds from now
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+15000, sende2); // to be alerted 15 seconds from now
/* To show how alarms are cancelled we will create a new Intent and a new PendingIntent with the
* same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567.
* Note: The intent and PendingIntent have to be the same as the ones used to create the alarms.
*/
Intent intent1 = new Intent(SomeApp.this, AReceiver.class);
PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0);
AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
am1.cancel(sender1);
} catch (Exception e) {
Log.e(TAG, "ERROR IN CODE:"+e.toString());
}
}
}
You will notice that this is only a "one-shot" alarm. If you want to set a repeating alarm, it is explained in Android's documentation. However, I will write on that too if there is demand for it. Now, let's examine the code. For setting an alarm, you will need 4 things:
The class that's setting the alarm
The class that will be called when the alarm "goes off"
The time at which the alarm should go off
A requestCode (which will use as a unique ID to identify the alarms) used in PendingIntent.
For cancelling an alarm, you need 3 things:
The class that set the alarm
The class that was to be called when the alarm "goes off"
The requestCode you used for PendingIntent object.
We have covered 2 things - the declaration of the receiver in our manifest file and the class that sets and cancels alarms. Now, we need to look at the class that will be called when the alarm goes off.
package someApp.someApp;
import java.util.Calendar;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.util.Log;
import android.widget.Toast;
/** All receiver classes must extend BroadcastReceiver */
public class AReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context con, Intent in) {
try {
/* Display an alert */
Toast.makeText(con, "hello my jello ", Toast.LENGTH_LONG).show();
} catch (Exception r) {
Toast.makeText(con, "You were supposed to do something"
+" now but I can't retrieve what it was.",
Toast.LENGTH_SHORT).show();
Log.e("ALARM_RECEIVER", r.toString());
}
}
}
AND YOU are able to use this other ans also...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 0);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 01);
cal.set(Calendar.SECOND, 0);
setAlarm(cal);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 30);
setAlarm(cal);
//etc
}
public void setAlarm(Calendar cal) {
try {
Intent intent = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); // to be alerted 30 seconds from now
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sende2); // to be alerted 15 seconds from now
/* To show how alarms are cancelled we will create a new Intent and a new PendingIntent with the
* same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567.
* Note: The intent and PendingIntent have to be the same as the ones used to create the alarms.
*/
Intent intent1 = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0);
AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
am1.cancel(sender1);
} catch (Exception e) {
Log.e(TAG, "ERROR IN CODE:"+e.toString());
}
}