Alarm Manager Example
This is working code. It wakes CPU every 10 minutes until the phone turns off.
Add to Manifest.xml:
...
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
...
<receiver android:process=":remote" android:name=".Alarm"></receiver>
...
Code in your class:
package yourPackage;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;
public class Alarm extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
public void setAlarm(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}
public void cancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
Set Alarm from Service:
package yourPackage;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class YourService extends Service
{
Alarm alarm = new Alarm();
public void onCreate()
{
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
alarm.setAlarm(this);
return START_STICKY;
}
@Override
public void onStart(Intent intent, int startId)
{
alarm.setAlarm(this);
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
}
If you want to set alarm repeating at phone boot time:
Add permission and the service to Manifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
...
<receiver android:name=".AutoStart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
...
<service
android:name=".YourService"
android:enabled="true"
android:process=":your_service" >
</service>
And create a new class:
package yourPackage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AutoStart extends BroadcastReceiver
{
Alarm alarm = new Alarm();
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
alarm.setAlarm(context);
}
}
}
Android: How to use AlarmManager
"Some sample code" is not that easy when it comes to AlarmManager
.
Here is a snippet showing the setup of AlarmManager
:
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
In this example, I am using setRepeating()
. If you want a one-shot alarm, you would just use set()
. Be sure to give the time for the alarm to start in the same time base as you use in the initial parameter to set()
. In my example above, I am using AlarmManager.ELAPSED_REALTIME_WAKEUP
, so my time base is SystemClock.elapsedRealtime()
.
Here is a larger sample project showing this technique.
start a service with Alarmmanager at specific date and time and Repeating
it's better to use job scheduler or firebase dispatcher for your requirement
refer this links
https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129
https://github.com/firebase/firebase-jobdispatcher-android
Android: Alarm not being triggered through AlarmManager
This part of your code seems wrong:
notificationIntent.setAction("com.example.basicalarmsetter.MatchNotification");
You're using the class name here. You need to use the action of the broadcast receiver, the one you put in your intent filter, a.k.a:
notificationIntent.setAction("com.example.notificationtest.MatchNotification");
Another issue: You're creating two alarms, which is unnecessary, at here:
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, futureInMillis, pendingIntent);
assert alarmManager != null;
alarmManager.setExact(AlarmManager. ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
At this section, following lines are unnecessary:
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, futureInMillis, pendingIntent);
assert alarmManager != null;
The value RTC_WAKEUP is supposed to be used with System.currentTimeMillis()
, not SystemClock.elapsedRealtime()
.
The final of your MainActivity.java would look like this:
package com.example.basicalarmsetter;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
public class MainActivity extends AppCompatActivity {
private int uniqueId = 0;
// Schedules a notification in the future given the delay
@RequiresApi(api = Build.VERSION_CODES.O)
private void scheduleNotification(int matchId, long delay) {
// Construct the PendingIntent which will trigger our alarm to go off
Intent notificationIntent = new Intent();
notificationIntent.setAction("com.example.notificationtest.MatchNotification");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), matchId, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT) ;
long futureInMillis = SystemClock.elapsedRealtime() + delay;
// Set off our PendingIntent
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setExact(AlarmManager. ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
// Sets an Alarm at a future specified date
@RequiresApi(api = Build.VERSION_CODES.O)
private void setAlarm(long notificationDelay) {
try {
System.out.println("Setting alarm at " + notificationDelay + " seconds");
// Sets off a notification after 5 seconds
scheduleNotification(uniqueId, notificationDelay);
uniqueId++;
} catch (Exception ex) {
System.out.println("Cannot print alarm!");
System.out.println("Exception: " + ex.toString());
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAlarm(15000);
}
}
AlarmManager Repeat
Intent intent = new Intent(this, MyReceiver.class);
intent.putExtra("key", "Alert");
pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar=Calendar.getInstance();
// Calendar.set(int year, int month, int day, int hourOfDay, int minute, int second)
calendar.set(2013, Calendar.OCTOBER, 13, 18, 55, 40);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*1000, pendingIntent);
This param is interval in milliseconds between subsequent repeats of the alarm:
5*1000 = 5 second
Sample:
1year = 365(day)* 24(hour)* 60(min)* 60(second)* 1000(sec ->
milisecond);
// leap year 366day
The month value is 0-based, so it may be clearer to use a constant like Calendar.OCTOBER
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,intent.getStringExtra("key"),Toast.LENGTH_SHORT).show();
}
}
update:
Note: Beginning with API 19 (Build.VERSION_CODES.KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested. reference
i recommend use JobScheduler for android 21 or Firebase JobDispatcher for older devices instead of Alarm Manager
update: Google has released WorkManager as part of JetPack Schedule tasks with WorkManager
Using Alarm Manager at specific time
Here's a sample code of using the AlarmManager
, you will need to change date and time according to your needs. I put it for today at 23:59
// Pending intent to be fired when alarm occurrs. In this case, open the AlarmActivity
Intent intent = new Intent(getApplicationContext(), AlarmActivity.class);
PendingIntent alarmIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
// Set the alarm for today at 23:59
calendar = Calendar.getInstance(TimeZone.getTimeZone("IST"));
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
alarmIntent);
In the given date-time the Intent will be fired so you need to make you logic in the AlarmActivity. You could also change the intent to start a Service or fire a Broadcast message
My Alarm Manager does not work in background
You can try this, it worked for me
AlarmManager alarmManager= (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent scheduleServiceExecuterIntent = new Intent(this, ScheduledServiceExecuter.class);
scheduleServiceExecuterIntent.putExtra("state", "Main");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, request_code, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_HOUR, pendingIntent);
Related Topics
Remove HTML Tags from a String
Broadcast Receiver For Checking Internet Connection in Android App
Fast Bitmap Blur For Android Sdk
Android 5.0 - Add Header/Footer to a Recyclerview
Scanner Is Skipping Nextline() After Using Next() or Nextfoo()
How Does the Java 'For Each' Loop Work
Stringbuilder VS String Concatenation in Tostring() in Java
How to Solve "Java.Lang.Noclassdeffounderror"
Why Is 128==128 False But 127==127 Is True When Comparing Integer Wrappers in Java
Why Does Gson Fromjson Throw a Jsonsyntaxexception: Expected Begin_Object But Was Begin_Array
How to Send Http Request in Java
How to Allow All Network Connection Types Http and Https in Android (9) Pie
Override Back Button to Act Like Home Button
How to Ping External Ip from Java Android
What Causes a Java.Lang.Arrayindexoutofboundsexception and How to Prevent It
How to Append Text to an Existing File in Java