Alarm Manager not starting after 60 seconds - java

I'm trying to set my alarm manager working, just simple schedule, firing toast every minute, but it's not working, what's wrong with the code?
Main Activity :
public void klik(View view) {
startalarm();
}
public void startalarm(){
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent;
PendingIntent pendingIntent;
intent = new Intent(this, AlarmToastReciever.class);
pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
manager.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+3000,+60000,pendingIntent);
}
}
AlarmToastReciever class :
public class AlarmToastReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent){
Toast.makeText(context,"GOWNO", Toast.LENGTH_SHORT).show();
}
}

As stated in documentation
As of Android 4.4 (API Level 19), all repeating alarms are inexact. Note that while setInexactRepeating() is an improvement over setRepeating(), it can still overwhelm a server if every instance of an app hits the server around the same time. Therefore, for network requests, add some randomness to your alarms, as discussed above.
You can use "setInexactRepeating()" or set an exact one time alarm then set next alarm in On Receive method
Also make sure you added your receiver to the manifest file, between application tag, like
<receiver android:name=".AlarmToastReciever"
android:enabled="true">
<intent-filter>
</intent-filter>
</receiver>

Use this code to initialize alarm manager.
public void setupAlarm() {
final Calendar calNow = Calendar.getInstance();
final Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, calNow.get(Calendar.HOUR_OF_DAY));
calSet.set(Calendar.MINUTE, calNow.get(Calendar.MINUTE) + 1);
calSet.set(Calendar.SECOND, calNow.get(Calendar.SECOND));
final Intent intent = new Intent(this, UploadStarterReceiver.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,
intent, 0);
final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(),
60 * 1000, pendingIntent);
}

Related

What else is needed to setup an alarm in Android?

I'm trying to make an app that schedules an alarm at a certain time in which the user is suppose to take their medication. I have done everything that most guides and the documentation say it's required to setup the alarm. Here is the method I call when the user presses the button:
private void scheduleAlarm() {
Intent intentAlarm = new Intent(this, AlarmReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this, alarmeID, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmeTime.getTimeInMillis(), pIntent);
}
Here is the AlarmReceiver.class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringtone = RingtoneManager.getRingtone(context, notification);
ringtone.play();
}
}
and I have put these two lines in the manifest:
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<receiver android:name=".services.AlarmReceiver"/>
And yet, my application is not working. The alarm doesn't go off. What am I doing wrong? What else is needed?
You are currently playing alarm ringtone from BroadcastReceiver. Instead of doing that, you can open an Activity and start playing alarm tone from there. You can use stop() method to stop it (may be from button click within the activity).
BroadcastReceiver
#Override
public void onReceive(Context context, Intent intent) {
//start activity
Intent i = new Intent(CurrentActivity.this, NextActivity.class);
context.startActivity(i);
}
NextActivity.class
//Start your ringtone here
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringtone = RingtoneManager.getRingtone(context, notification);
ringtone.play();
//Somewhere inside button click
{
ringtone.stop();
}
Just copy pasting this won't work. I believe you can take concept from
here and implement as per your requirement.
And currently there is no any related code that will stop your ringtone.
Okay I am not really sure wither you are asking how to stop the alarm ? or that the alarm is not working at all after the user presses the button but anyhow.
I replaced The alarm with a repeated alarm and launched it using onCreate method and I closed the app and waited for the alarm to go off and it did!
And here is my code just in case:
private void scheduleAlarm() {
Intent intentAlarm = new Intent(this, AlarmReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this, uniqueID, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// alarmManager.set(AlarmManager.RTC_WAKEUP, 10000, pIntent);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, 1000, pIntent);
}
Everything else I copied and pasted from your code above.
Edit: If you are seeking the repeated alarm then this the page to go to:
https://developer.android.com/training/scheduling/alarms.html
note: my virtual device API is 24
Change the code as below -
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000*60, pIntent);
May be your alarmeTime.getTimeInMillis() is not properly set. You can try the above line. It fires an alarm after 1 min.

Alarm not going off when app killed

How am I supposed to implement an alarm to open the dismiss/snooze screen after the app is destroyed? My alarm works perfectly fine as long as the app stays up, here's how I schedule the alarm:
//instantiate calendar to call alarm on time match
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
//if time is set earlier than current (e.g set for 6:59pm, currently 7pm), do not play until next clock cycle/day
if(calendar.before(Calendar.getInstance())) {
calendar.add(Calendar.DATE, 1);
}
//cancel any currently pending intents if toggle button is toggled on
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT).cancel();
//add parameters to pass to activities that play the alarm
myIntent.putExtra("stream",stream);
myIntent.putExtra("seconds",snoozeSeconds);
myIntent.putExtra("link",ytLink);
//create pending intent to broadcast to activity that plays the alarm
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
alarmManager.setExact(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
And I use a receiver that's fairly simple:
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
//....
MainActivity.ringtone.play();
Intent alarmIntent = new Intent(context, AlarmActivity.class);
context.startActivity(alarmIntent); //start dismiss screen
As per your question, This is what i understand, Let me know if misunderstand your question
if you want to open/active your alaram after App close or device reboot
then you have add intent filter android.intent.action.BOOT_COMPLETED in your AlarmReceiver AndroidManifest.xml and you can manage the actions on your AlarmReceiver onReceive methond
Please check the following code
public void onReceive(Context context, Intent intent) {
if(intent == null){
return;
}
String action = intent.getAction();
if (action != null && action.equalsIgnoreCase("android.intent.action.BOOT_COMPLETED")) {
}
AlarmReceiver.completeWakefulIntent(intent);
}
Add intent filter actions in your AndroidManifest.xml file
<receiver android:name="com.monster.android.Services.AlarmReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
You can use stopService() method:
stopService(new Intent(MainMenu.this, AlarmActivity.class));

AlarmManager executed even if the time is wrong

I am using the following code to execute the Alarm at 10:30 AM and then keep executing every 8seconds, but the problem is, this code execute the Alarm manager even when the time is not 10:30.
I have tried everything but the code keep executing the Alarm regardless of what time is set,
public class MainActivity extends Activity {
private PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
startAt10();
}
public void startAt10() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
/* Set the alarm to start at 10:30 AM */
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 30);
/* Repeating on every 8 seconds interval */
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 8, pendingIntent);
}
}
and this is my AlarmReceiver class,
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "Welcome Back ! ", Toast.LENGTH_SHORT).show();
}
I have also added this in my AndroidManifest.xml,
<receiver android:name="com.example.test2.AlarmReceiver" android:enabled="true" >
</receiver>
How to make it to only execute at 10:30AM ?
Your code is correct. The alarm will start at 10:30 am and repeats at every 8 seconds. But once check the time in the device or emulator in which your app is running. If the time is already past then the alarm starts executing immediately.
If the time is not completed then once uninstall the application and run again it may work.

Using AlarmManager to perform a specific task in future

I am new to Android and I would appreciate any help on this.
I am trying to use Alarm Manager so that it would call my BroadcastReceiver class at a specific time in future set by DatePicker and TimePicker widgets.
However, i cannot get the broadcastreceiver class to perform its function.
below is the code that i put in the manifest file for the broadcastreceiver class to receive the broadcast message from OS:
<receiver android:name="androidapp.scheduler.MyBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.MYBROADCASTRECEIVER" >
</action>
</intent-filter>
</receiver>
And below is the code that i have put in my Next button's onclicklistener so that it would inform OS of the time of the call.
TimePicker myTp = (TimePicker)findViewById(R.id.tpTime);
cal.set(Calendar.YEAR,myDatePicker.getYear() );
cal.set(Calendar.MONTH, myDatePicker.getMonth());
cal.set(Calendar.DAY_OF_MONTH, myDatePicker.getDayOfMonth());
cal.set(Calendar.HOUR, myTp.getCurrentHour());
cal.set(Calendar.MINUTE, myTp.getCurrentMinute());
cal.set(Calendar.SECOND, 0);
Log.i("SCheduling", cal.getTime().toString());
Intent intent = new Intent(Scheduling.this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Scheduling.this, 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
Intent nextForm = new Intent(this,Sender.class);
nextForm.putExtra("contacts", contacts);
startActivity(nextForm);
Log.i("SCheduling", "everything set");
Finally, MybroadcastReceivers class code is shown below:
public class MyBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Log.i("brreceiver", "BroadcastReciever");
Toast.makeText(context, "schedule set!.",
Toast.LENGTH_LONG).show();
}
}
What am I missing here?
In the following statement change Scheduling.this to this.getApplicationContext()
PendingIntent pendingIntent = PendingIntent.getBroadcast(Scheduling.this, 234324243, intent, 0);
it seems the code was correct, the problem was with the Emulator. I still don't know what was wrong with the emulator but i tested the code again and it worked and i did receive the log's output.

Android: How to use AlarmManager

I need to trigger a block of code after 20 minutes from the AlarmManager being set.
Can someone show me sample code on how to use an AlarmManager in ِAndroid?
I have been playing around with some code for a few days and it just won't work.
"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.
There are some good examples in the android sample code
.\android-sdk\samples\android-10\ApiDemos\src\com\example\android\apis\app
The ones to check out are:
AlarmController.java
OneShotAlarm.java
First of, you need a receiver, something that can listen to your alarm when it is triggered. Add the following to your AndroidManifest.xml file
<receiver android:name=".MyAlarmReceiver" />
Then, create the following class
public class MyAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
}
}
Then, to trigger an alarm, use the following (for instance in your main activity):
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 30);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);
.
Or, better yet, make a class that handles it all and use it like this
Bundle bundle = new Bundle();
// add extras here..
MyAlarm alarm = new MyAlarm(this, bundle, 30);
this way, you have it all in one place (don't forget to edit the AndroidManifest.xml)
public class MyAlarm extends BroadcastReceiver {
private final String REMINDER_BUNDLE = "MyReminderBundle";
// this constructor is called by the alarm manager.
public MyAlarm(){ }
// you can use this constructor to create the alarm.
// Just pass in the main activity as the context,
// any extras you'd like to get later when triggered
// and the timeout
public MyAlarm(Context context, Bundle extras, int timeoutInSeconds){
AlarmManager alarmMgr =
(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyAlarm.class);
intent.putExtra(REMINDER_BUNDLE, extras);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, timeoutInSeconds);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
pendingIntent);
}
#Override
public void onReceive(Context context, Intent intent) {
// here you can get the extras you passed in when creating the alarm
//intent.getBundleExtra(REMINDER_BUNDLE));
Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
}
}
What you need to do is first create the intent you need to schedule. Then obtain the pendingIntent of that intent. You can schedule activities, services and broadcasts. To schedule an activity e.g MyActivity:
Intent i = new Intent(getApplicationContext(), MyActivity.class);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),3333,i,
PendingIntent.FLAG_CANCEL_CURRENT);
Give this pendingIntent to alarmManager:
//getting current time and add 5 seconds in it
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5);
//registering our pending intent with alarmmanager
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), pi);
Now MyActivity will be launched after 5 seconds of the application launch, no matter you stop your application or device went in sleep state (due to RTC_WAKEUP option).
You can read complete example code Scheduling activities, services and broadcasts #Android
I wanted to comment but <50 rep, so here goes. Friendly reminder that if you're running on 5.1 or above and you use an interval of less than a minute, this happens:
Suspiciously short interval 5000 millis; expanding to 60 seconds
See here.
Some sample code when you want to call a service from the Alarmmanager:
PendingIntent pi;
AlarmManager mgr;
mgr = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(DataCollectionActivity.this, HUJIDataCollectionService.class);
pi = PendingIntent.getService(DataCollectionActivity.this, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() , 1000, pi);
You dont have to ask userpermissions.
An AlarmManager is used to trigger some code at a specific time.
To start an Alarm Manager you need to first get the instance from the System. Then pass the PendingIntent which would get executed at a future time that you specify
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
int interval = 8000; //repeat interval
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
You need to be careful while using the Alarm Manager.
Normally, an alarm manager cannot repeat before a minute. Also in low power mode, the duration can increase to up to 15 minutes.

Categories

Resources