I have code which is to be run daily; for this I'm trying to use AlarmManager. This is my code for triggering alarms:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this, AlarmReciever.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pi); // cancel any existing alarms
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, pi);
}
This part of the code is calling AlarmReciever class as expected, but I want the code in the AlarmReciever class to be executed only once daily. It's being called multiple times. How do I restrict it?
This is the AlarmReciever class:
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("in alarm reciever class");
}
}
I'm trying to perform some business logic in the onReceive() method.
In the manifest.xml file:
<receiver android:name="com.xyz.reciever.AlarmReciever"></receiver>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
are declared.
I believe the code you should be using to set your alarm would be this:
Intent i = new Intent(this, AlarmReciever.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); // <- HERE!!
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pi); // cancel any existing alarms
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, pi);
since your AlarmReciever is a BroadcastReceiver. Use PendingIntent.getBroadcast().
If you have much work to do in your receiver's onReceive() method, you might also delegate it to an IntentService. See this answer if you decide to do that.
Related
I am new to android programming. What am i doing wrong? AlarmReceiver class not triggering...I want to trigger repeatedly the AlarmReceiver.class ...
I used the code from this page https://developer.android.com/training/scheduling/alarms#precision
OnCreate at MainActivity.java i have the following code
AlarmManager alarmManager = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this,AlarmReceiver.class);
//Check if the PendingIntent already exists
PendingIntent pendingIntent =
PendingIntent.getService(this, 6661, intent,
PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null && alarmManager != null) {
//cancel here if you want
}
//Run every 60 seconds!
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60000,
60000, pendingIntent);
The AlarmReceiver.java class includes the following code...
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Log.i("logit","testing...");
}
}
Do you have an entry in your manifest for the receiver like that?
<receiver android:name=".AlarmReceiver"></receiver>
I want use String start = "16:00"; in specific time, start another activity.
I must use String start = "16:00"
MainActivity.class
String start = "16:00";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAlarmTime(this);
}
private void setAlarmTime(Context context) {
String[] strStart = start.split(":") // delete ":"
Calendar cal_start = Calendar.getInstance();
cal_start.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strStart[0])); // hour
cal_start.set(Calendar.MINUTE, Integer.parseInt(strStart[1])); //minute
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
alarm.set(AlarmManager.RTC, cal_start.getTimeInMillis(), pIntent);
}
I want while the app is running, current time 4 o'clock , start AlarmActivity.class .
But it does not work.
How to every specific time start another activity on android?
#update
private void setAlarmTime(Context context) {
String[] strStart = start.split(":");
Calendar cal_start = Calendar.getInstance();
cal_start.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strStart[0]));
cal_start.set(Calendar.MINUTE, Integer.parseInt(strStart[1]));
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
alarm.set(AlarmManager.RTC_WAKEUP, cal_start.getTimeInMillis(), pendingIntent);
this source not work.
not work alarmManager.
Please consider to use AlarmManager.RTC_WAKEUP if you need to wake up the device even if it goes off.
alarm.set(AlarmManager.RTC_WAKEUP, cal_start.getTimeInMillis(), pIntent);
AlarmManager.RTC will NOT wake the device up.
Reference: https://developer.android.com/reference/android/app/AlarmManager.html#RTC
Btw, you do not need to pass the context reference to method:
PendingIntent pIntent = PendingIntent.getActivity(this /*can use this as it is a context already */ , 0, intent, 0);
Update:
Please also set the second and millisecond of the cal_start; otherwise it will be the values that you get the calendar instance.
cal_start.set(Calendar.SECOND, 0);
cal_start.set(Calendar.MILLISECOND, 0);
Update 2:
It works in my side, you may try to add
<uses-permission android:name="android.permission.WAKE_LOCK" />
in Manifests.
Btw, if you want this alarm repeat every day
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal_start.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pIntent);
Add this permission in your manifest
<uses-permission android:name="android.permission.WAKE_LOCK" />
register your receiver class in the application tag in the manifest file
<receiver android:name=".AlarmActivity" />
Resister your alarm that will trigger AlarmActivity at a specific time in your case its 16:00
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Intent intent = new Intent(getApplicationContext(), AlarmActivity.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Make sure your register class extend BroadcastReceiver like this
class AlarmActivity extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Do whatever you want
// you can generate notifications here
// or can start your application activity you want
}
}
I'm making an app which uses an AlarmManager and a Broadcast Receiver to generate a notification everyday at 8:20 AM.
One issue which I'm facing is that every time I open the app after 8:20 AM, the notification is generated.
I guess this is because I have called the receiver in the onCreate() method.
Is there a way to make sure that the receiver is registered only once?
Here is my code :
public class MainActivity extends AppCompatActivity
{
AlarmManager alarmManager;
private PendingIntent alarmIntent;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 00);
calendar.set(Calendar.MINUTE,30);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
}
public class AlarmReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context,"Alarm Raised",Toast.LENGTH_SHORT).show();
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
PendingIntent pendingIntent=PendingIntent.getActivity(context,0,intent1,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.ic_account_circle_black_18dp);
builder.setContentTitle("Tracker");
builder.setContentText("Turn on Gps");
builder.setPriority(Notification.PRIORITY_MAX);
builder.setDefaults(Notification.DEFAULT_SOUND);
builder.setLights(0x0000FF,3000,2000);
builder.setContentIntent(pendingIntent);
notificationManager.notify(56, builder.build());
}
}
The second parameter of setInexactRepeating indicates that when should the AlarmManager start its task. So if you give it a time in past it will fire once immediately. You must check if the calendar.getTimeInMillis() is before now and add a day to it if so.
So you should simply change this part of your code
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
to this:
long timeToStart = calendar.getTimeInMillis();
if(System.currentTimeMillis() < timeToStart){
timeToStart += 24 * 60 * 60 * 1000; // one day
}
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeToStart, AlarmManager.INTERVAL_DAY, alarmIntent);
I have class for call myService with alaram Manager. From mainActivity this is my code to set alarm manager.
Intent downloader = new Intent(context, AlarmReceiver.class);
downloader.putExtra("limit", limit.getSelectedItem().toString());
downloader.putExtra("delay",perMin.getSelectedItem().toString());
downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); `pendingIntent = PendingIntent.getBroadcast(context, 0, downloader,PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int delay = Integer.parseInt(perMin.getSelectedItem().toString());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,10 * 1000, delay * 1000, pendingIntent);
and here my alarm receiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent update = new Intent(context, IntervalService.class);
Log.i(tag, "Call service from Alaram Receiver");
context.startService(update);
}}
I know when i want to cancel alarm manager from main activity easily call alarmManager.cancel(pendingIntent) but i want to cancel alarm manager to complete my service task and after that set again like as above.
Just modified your code,
public void setAlarmManager(boolean cancel){
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,downloader,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int delay = Integer.parseInt(perMin.getSelectedItem().toString());
if(!cancel)
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,10 * 1000, delay * 1000, pendingIntent);
else
alarmManager.cancel(pendingIntent);
}
call this function when needed,
to Start: setAlarmManager(false);
to Cancel: setAlarmManager(true); //Call this function in Service
Try, this may work. Thanks.
I have defined my Android alarm and BroadcastReceiver as follows. My hope was that I want the alarm to go off two minutes later and every 15 minutes subsequently. This does not seem to be happening. Why is this?
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + 2);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(getApplicationContext(), DailyNotificationReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);
public class DailyNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("received", "received");
}
}
As discussed in the comments, the BroadcastReceiver was not registered.
Please register the BroadcastReceiver in the manifest