Android - alarm clock with Notification using AlarmManager - java

I'm creating an alarm clock using AlarmManager and I have some troubles:
How to stop sounding of notification when I open Notification?
How to make alarm for a certain day of week (or the whole week), not for the certain date?
private void restartNotify()
{
Calendar calendar = Calendar.getInstance();
// current Month - 1
calendar.set(Calendar.MONTH, 5);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.DAY_OF_MONTH, 28);
calendar.set(Calendar.HOUR_OF_DAY, 1);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.PM);
Intent timeIntent = new Intent(MainActivity.this, TimeNotification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, timeIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
public class TimeNotification extends WakefulBroadcastReceiver
{
#Override
public void onReceive(final Context context, Intent intent)
{
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class AlarmService extends IntentService
{
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent)
{
sendNotification("Wake Up! Wake Up!");
}
private void sendNotification(String msg)
{
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Alarm").setSmallIcon(R.drawable.abc_btn_radio_material)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alamNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alamNotificationBuilder.build());
}

Related

Cannot send daily notfication on android with java

I'm trying 1 month now to make a feature witch sends to the user one notification daily at the time the user has selected but when the onTimeSet() called i'm getting only this error below and the Notification is not coming to the user
I try these solutions below:
removing all code from onTimeSet() & startAlarm() inside my activity
changing this to SetNotificationActivity.this
Invalidate chaches / restart
Error:
E/InputDispatcher: Window handle Window{838da5a u0 com.george.igrow/com.george.igrow.SetNotificationActivity} has no registered input channel
SetNotificationActivity.java:
public class SetNotificationActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_notification);
final Button setAlarm = findViewById(R.id.buttonAlarm);
final Button skip_btn = findViewById(R.id.button4);
setAlarm.setOnClickListener(v -> {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
});
skip_btn.setOnClickListener(v -> {
finish();
startActivity(new Intent(SetNotificationActivity.this, HomeActivity.class));
});
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
startAlarm(c);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
if (c.before(Calendar.getInstance()))
c.add(Calendar.DATE, 1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
startActivity(new Intent(SetNotificationActivity.this, HomeActivity.class));
}
}
AlertReceiver.java:
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, SplashScreenActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
// Send notification for the current Alarm
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
//nb.setContentIntent(pendingIntent);
notificationHelper.getManager().notify(1, nb.build());
}
}

android alarmManager setRepating time delay problem

I want to send a notification with the alarm manager in my application. I am using the setRepeating method because it should be in intervals. but notifications always come delayed.
For example, I would like to receive a notification at 12:14. but notification is coming sometimes 12:17, sometimes 12:20
Thanks in advance
Note: doze mode off
For Example:
thatDay Sat Apr 25 16:30:00 GMT+03:00 2020
today Sat Apr 25 16:07:44 GMT+03:00 2020
thatDay.getTimeInMillis() = 1587821400000
#Override
protected void onStop() {
if (notification) {
Calendar thatDay = Calendar.getInstance();
Calendar today = Calendar.getInstance();
int today_month_day = today.get(Calendar.DAY_OF_MONTH);
int today_month = today.get(Calendar.MONTH);
int today_year = today.get(Calendar.YEAR);
thatDay.setTime(new Date(0));
thatDay.set(Calendar.DAY_OF_MONTH, today_month_day);
thatDay.set(Calendar.MONTH, today_month);
thatDay.set(Calendar.YEAR, today_year);
thatDay.set(Calendar.HOUR_OF_DAY, 8);
thatDay.set(Calendar.MINUTE, 0);
thatDay.set(Calendar.SECOND, 0);
thatDay.set(Calendar.MILLISECOND, 0);
Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.HOUR_OF_DAY) < 23 && calendar.get(Calendar.HOUR_OF_DAY) > 7) {
if (calendar.get(Calendar.MINUTE) < 30) {
thatDay.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY));
thatDay.set(Calendar.MINUTE, 30);
} else {
thatDay.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + 1);
}
} else if (thatDay.getTimeInMillis() - today.getTimeInMillis() < 0) {
thatDay.set(Calendar.DAY_OF_MONTH, today_month_day + 1);
} else {
thatDay.set(Calendar.DAY_OF_MONTH, today_month_day);
}
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("NotificationID", 6);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 7, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Objects.requireNonNull(alarmManager).setRepeating(AlarmManager.RTC_WAKEUP, thatDay.getTimeInMillis(), waterList[waterCheck], pendingIntent);
super.onStop();
}
#SuppressLint("BatteryLife")
#RequiresApi(api = Build.VERSION_CODES.M)
private void requestBattery() {
Intent intent = new Intent();
String packageName = context.getPackageName();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (!(Objects.requireNonNull(pm).isIgnoringBatteryOptimizations(packageName))) {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivityForResult(intent, BATTERY_PERMISSION);
}
}
This is because setRepeating is only fired, when something else is happening in the background. Mainly this is due to battery saving. The best way to set a repeating alarm is to use setExact and set another alarm once the first one was fired.
Alarmmanager:
public class AlarmManagerSetup {
public static Boolean alarmActivated;
public static Long milliSeconds;
public void startAlarm(Calendar c, Context context, Database database) {
android.app.AlarmManager alarmManager = (android.app.AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, 0);
c.setTimeInMillis(milliSeconds);
//compares to the current time and only adds when it is later than now
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
if (Build.VERSION.SDK_INT >= 23) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
} else if (Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
}
And inside the Alert Receiver you do this:
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Context appContext = context.getApplicationContext();
CalendarSearch calendar = new CalendarSearch(context);
calendar.calendar();
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification(appContext);
notificationHelper.getManager().notify(1, nb.build());
AlarmManagerSetup alarmManager = new AlarmManagerSetup();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(milliSeconds);
c.add(Calendar.DATE, 1);
milliSeconds = c.getTimeInMillis();
alarmManager.startAlarm(c, appContext, database);
}

How to make AlarmBootReceiver send notification at specified time?

I have an AlarmResiver class, it sends notifications if the user has set the time and the toggle switch is on. But this class is bad in that when the device reboots, notifications are no longer received. Then I decided to create an AlarmBootResiver class that will send notifications after the device is rebooted. Now this class is working, but it sends notifications immediately after turning on the device. How to make the AlarmBootResiver send notifications at the time set by the user in the AlarmResiver class ?
AlarmActivity code:
public class AlarmActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
private EditText mondayText;
public SwitchCompat mondaySwitch;
SharedPreferences sPref;
String timeText = "";
final String SAVED_TEXT = "saved_text";
boolean switch_On_Off;
public static final String PREFS_NAME = "Switch_On_Off_check";
final Calendar c = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
mondayText = findViewById(R.id.monday_time);
mondaySwitch = findViewById(R.id.switch_monday);
// load SharedPref save text in mondayText and save switch On else Off
loadText();
loadSwitchCheck();
mondaySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (mondaySwitch.isChecked()) {
startAlarm(c);
bootStartAlarm(c);
}
saveSwitchCheck();
}
});
mondayText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
}
});
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
updateTimeText(c);
saveText();
mondaySwitch.setChecked(false);
bootStopAlarm(c);
}
private void updateTimeText(Calendar c) {
timeText = "";
timeText += DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());
mondayText.setText(timeText);
}
public void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
public void bootStartAlarm(Calendar c) {
PackageManager packageManager = AlarmActivity.this.getPackageManager();
ComponentName componentName = new ComponentName(AlarmActivity.this, AlarmBootReceiver.class);
packageManager.setComponentEnabledSetting(componentName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmBootReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
public void bootStopAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmBootReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
PackageManager packageManager = AlarmActivity.this.getPackageManager();
ComponentName componentName = new ComponentName(AlarmActivity.this, AlarmBootReceiver.class);
packageManager.setComponentEnabledSetting(componentName,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
My AlertReciever
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
notificationHelper.getManager().notify(1, nb.build());
}
}
My AlarmBootReciever
public class AlarmBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Objects.equals(intent.getAction(), "android.intent.action.BOOT_COMPLETED")) {
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
notificationHelper.getManager().notify(1, nb.build());
}
}
}
My Manifest file
<receiver android:name=".AlertReceiver"/>
<receiver
android:name=".AlarmBootReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.REBOOT" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.QUICKBOOT_POWERON" />
<uses-permission android:name="android.permission.VIBRATE" />
My NotificationHelper
public class NotificationHelper extends ContextWrapper {
public static final String channelID = "channelID";
public static final String channelName = "Channel Name";
private NotificationManager mManager;
public NotificationHelper(Context base) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel();
}
}
#TargetApi(Build.VERSION_CODES.O)
private void createChannel() {
NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
getManager().createNotificationChannel(channel);
}
public NotificationManager getManager() {
if (mManager == null) {
mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
return mManager;
}
public NotificationCompat.Builder getChannelNotification() {
Intent resultIntent = new Intent(this, DashBoardActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
return new NotificationCompat.Builder(getApplicationContext(), channelID)
.setContentTitle("ЭЙ ТЫ!")
.setContentText("Пора на тренировку!")
.setSmallIcon(R.drawable.ic_training)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent);
}
}
You can use a BroadcastReceiver for this. This code will work, even if you restart your device or lock the device, the PowerManager does that for you. See here for more information https://developer.android.com/reference/android/os/PowerManager
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(YOUR DRAWABLE)
.setContentTitle("YOUR TITLE")
.setAutoCancel(true)
.setLights(0xFFFF0000, 500, 500)
.setColor(context.getResources().getColor(R.color.red))
.setDefaults(NotificationCompat.DEFAULT_SOUND)
.setContentText("THIS IS THE CONTENT OF THE NOTIFICATION");
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
#SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
wakeLock.acquire();
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.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().
mNotificationManager.notify(0, mBuilder.build());
}
}
You can trigger AlarmReceiver using this in MainActivity for example where you can set your time of trigger, see comment.
public void doNotification() {
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, AlarmReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// InexactRepeating allows Android to optimize the energy consumption //ms, s, min
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24 * 30, pending); //every month
}

Android How to keep Running the background service when app is killed by user?

I want a background service that keeps running always in a background? It is running on some phone but not running on customised OS phones like VIVO, OPPO MIUI etc? Service is Killed on these customised OS phone.
My Code is given below --
public class MyService extends Service
{
private static final String TAG = "MyService";
#Override
public void onStart(Intent intent, int startId)
{
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//call to onTaskRemoved
onTaskRemoved(intent);
//return super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
super.onDestroy();
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
60000,
pendingIntent);
}
}
#Override public void onTaskRemoved(Intent rootIntent)
{
Log.e("onTaskRemoved", "Called!");
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent);
}
super.onTaskRemoved(rootIntent);
}}
I have written a Broadcast Receiver that wake ups my service for every second but it is not working. My Broadcast Receiver as follows-
public class MyBroadCastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("MyBroadCastReceiver", "onReceive");
//if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
{
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("myFCMJob")
.build();
dispatcher.mustSchedule(myJob);
}
else
{
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
}}
I have started my service using Alarm Manager and have set the Alarm for every 5 seconds, my MainActivity.java file code is as below ---
public class MainActivity extends AppCompatActivity
{
Button btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStopService = findViewById(R.id.btnStopService);
//get FirebaseToken
getToken();
//start Service
startService();
//setReceiver();
btnStopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
}
});
}
private void getToken()
{
FirebaseId firebaseId=new FirebaseId();
String token_firebase=firebaseId.getFireBaseToken();
}
private void startService()
{
Intent myIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Log.e("TAG", "++++++++++222222++++++++");
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
//calendar.add(Calendar.SECOND, 10);
Calendar alarmStartTime = Calendar.getInstance();
Calendar now = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR_OF_DAY, 0);
alarmStartTime.set(Calendar.MINUTE, 0);
alarmStartTime.set(Calendar.SECOND, 5);
if (now.after(alarmStartTime)) {
Log.d("Hey","Added a day");
//alarmStartTime.add(Calendar.DATE, 1);
}
if (alarmManager != null) {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
alarmStartTime.getTimeInMillis(),
pendingIntent);
}
Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show();
}}
Thanks in Advance.
To keep your service and all your application running even if the phone goes into sleep mode, your service has to call startForeground() and show a non dismissable notification.
It is also convenient to acquire a partial WAKE LOCK.
on your onStartCommand()
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Constants.CHANNEL_NOTIFY_ID)
.setContentTitle("the content title")
.setContentText("the content text")
.setSmallIcon(R.drawable.myicon)
.setOngoing(true);
// you can add other options Builder has
startForeground(1234, mBuilder.build());

Setting Alarm for Particular Timings with Respect to Start Date and End Date of an Event in Android

I am having an Calendar Event with start date as (24hrs format) 27-Apr-2016 11:00:00 and end date as 29-Apr-2016 11:00:00. I am having three timings 10:45:00, 10:30:00 and 10:15:00 which are calculated for alerting the event prior to the actual set timings (i.e 15 mins, 30 mins and 45 mins early to the start date).
Also the alarm must repeat daily for the same prior timings till the end date is reached.
Here is how i tried to do it, How ever the below code does not invoke the alarm nor it repeats daily
In the MainActivity.java
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, Broadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(2016,03,27,11,00,00);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*15), pendingIntent); // subtract for 15 mins prior alarm time
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*30), pendingIntent); // subtract for 30 mins prior alarm time
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*45), pendingIntent); // subtract for 45 mins prior alarm time
In the Broadcast.java
Log.i("Alarm", "Alarm Manager is called");
Toast.makeText(context, new Date().toString(), Toast.LENGTH_SHORT).show();
How can I achieve this? Please help
Here is my sample code, Try this:
Modify the date and time as your need in the below code.
public static int REPEAT_NOTIFICATION1 = 201;
public static int REPEAT_NOTIFICATION2 = 202;
public static int REPEAT_NOTIFICATION3 = 203;
private void repeatNotification() {
final DateTime dateTime1 = DateTime.now();
dateTime1.hourOfDay().setCopy(7);
dateTime1.minuteOfHour().setCopy(30);
dateTime1.secondOfMinute().setCopy(00);
final Calendar calendarNotifiedTime1 = Calendar.getInstance();
calendarNotifiedTime1.set(Calendar.HOUR, dateTime1.getHourOfDay());
calendarNotifiedTime1.set(Calendar.MINUTE, dateTime1.getMinuteOfHour());
calendarNotifiedTime1.set(Calendar.SECOND, dateTime1.getSecondOfMinute());
calendarNotifiedTime1.set(Calendar.AM_PM, Calendar.AM);
final DateTime dateTime2 = DateTime.now();
dateTime2.hourOfDay().setCopy(12);
dateTime2.minuteOfHour().setCopy(30);
dateTime2.secondOfMinute().setCopy(00);
final Calendar calendarNotifiedTime2 = Calendar.getInstance();
calendarNotifiedTime2.set(Calendar.HOUR, dateTime2.getHourOfDay());
calendarNotifiedTime2.set(Calendar.MINUTE, dateTime2.getMinuteOfHour());
calendarNotifiedTime2.set(Calendar.SECOND, dateTime2.getSecondOfMinute());
calendarNotifiedTime2.set(Calendar.AM_PM, Calendar.PM);
final DateTime dateTime3 = DateTime.now();
dateTime3.hourOfDay().setCopy(6);
dateTime3.minuteOfHour().setCopy(30);
dateTime3.secondOfMinute().setCopy(00);
final Calendar calendarNotifiedTime3 = Calendar.getInstance();
calendarNotifiedTime3.set(Calendar.HOUR, dateTime3.getHourOfDay());
calendarNotifiedTime3.set(Calendar.MINUTE, dateTime3.getMinuteOfHour());
calendarNotifiedTime3.set(Calendar.SECOND, dateTime3.getSecondOfMinute());
calendarNotifiedTime3.set(Calendar.AM_PM, Calendar.PM);
Intent intent1 = new Intent(EmptyActivity.this, NotificationReceiver.class);
intent1.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime1.getHourOfDay() + ":" + dateTime1.getMinuteOfHour() + ":" + dateTime1.getSecondOfMinute());
Intent intent2 = new Intent(EmptyActivity.this, NotificationReceiver.class);
intent2.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime2.getHourOfDay() + ":" + dateTime2.getMinuteOfHour() + ":" + dateTime2.getSecondOfMinute());
Intent intent3 = new Intent(EmptyActivity.this, NotificationReceiver.class);
intent3.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime3.getHourOfDay() + ":" + dateTime3.getMinuteOfHour() + ":" + dateTime3.getSecondOfMinute());
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION1, intent3, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION2, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent3 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION3, intent3, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
cancelNotification(REPEAT_NOTIFICATION1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime1.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent1);
cancelNotification(REPEAT_NOTIFICATION2);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime2.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent2);
cancelNotification(REPEAT_NOTIFICATION3);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime3.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent3);
}
Cancel Notification:
public void cancelNotification(int requestCode) {
try {
Intent notificationIntent = new Intent(getApplicationContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
BroadCast Receiver:
public class NotificationReceiver extends BroadcastReceiver {
public static String NOTIFICATION_MESSAGE = "notificationMessage";
public static int REPEAT_NOTIFICATION1 = 201;
public static int REPEAT_NOTIFICATION2 = 202;
public static int REPEAT_NOTIFICATION3 = 203;
Context context;
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
//Assume StartDate = yesterday.
DateTime startDate = DateTime.now().minusDays(1);
//Assume EndDate = tomorrow
DateTime endDate = startDate.plusDays(2);
DateTime today = DateTime.now();
if (today.isBefore(endDate) || today.isEqual(endDate)) {
String message = intent.getStringExtra(NOTIFICATION_MESSAGE);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent notificationIntent = new Intent(context, EmptyActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
final DateTime dateTime = DateTime.now();
int color = 0xffffaa00;
// int color1 = context.getColor(R.color.notificatinBackgroundColor);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.festi_push_message_small);
builder.setContentIntent(pendingIntent);
builder.setContentTitle("Notification Sample");
builder.setAutoCancel(true);
builder.setContentText(message + ", Current Time : " + dateTime.getHourOfDay() + ":" + dateTime.getMinuteOfHour() + ":" + dateTime.getSecondOfMinute());
builder.setSound(soundUri);
builder.setLights(Color.RED, 1000, 1000);
builder.setColor(color);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(102938, notification);
} else {
cancelNotification(REPEAT_NOTIFICATION1);
cancelNotification(REPEAT_NOTIFICATION2);
cancelNotification(REPEAT_NOTIFICATION3);
}
}
public void cancelNotification(int requestCode) {
try {
Intent notificationIntent = new Intent(context, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Manifest.xml
<receiver android:name=".NotificationReceiver" />

Categories