Alarm not going off when app killed - java

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));

Related

what approach should i follow to make Timer service in android

I am working on an interval timer which make an alarm every interval (E.g. 30mins).
I want to make the timer work in background or when device is in sleep and show a notification,
I was told to use Intent Service but its deprecated. what should i use?
-I want to support until API 21
You need to create a BroadcastReceiver. For example, using AlarmManager:
int repeatTime = 30; //Repeat alarm time in seconds
AlarmManager processTimer = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, processTimerReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
//Repeat alarm every second
processTimer.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(),repeatTime*1000, pendingIntent);
And create your processTimerReciever class:
//This is called every second (depends on repeatTime)
public class processTimerReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
//Do something every 30 seconds
}
}
Remember to register into Manifest:
<receiver android:name="processTimer" >
<intent-filter>
<action android:name="processTimerReceiver" >
</action>
</intent-filter>
</receiver>
EDIT:
If your app use an internet connection, you can send every 30 mins a notification using Firebase

Alarm Manager not starting after 60 seconds

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);
}

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.

AlarmManager reset on reboot

I've an alarm which opens an activity at a time chosen by the user. If the user hits the start button, the alarm goes fine but it gets cancelled after reboot. I've looked everywhere and it says that I should use a service. Is it possible to keep the alarms on after the reboot without using service? I'm new to coding so can you please breakdown what I need to do. Thank you
public class MainActivity extends AppCompatActivity {
Button disable;
Button start;
TimePicker timePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePicker = (TimePicker) findViewById(R.id.timePicker);
disable = (Button) findViewById(R.id.disable_alarm);
start = (Button) findViewById(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
calendar.set(Calendar.MINUTE, timePicker.getMinute());
Intent intent = new Intent(getApplicationContext(),notification.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(), 120*1000, pendingIntent);
}
});
disable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),notification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
});
and Broadcast Receiver is
public class notification extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent scheduledIntent = new Intent(context, pop_up2.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);}}
Thanks
All of the active alarms are cancelled after phone is shutdown. In order to reset the alarms you need to use a separate broadcast receiver that will receive only boot completed action. The receiver then starts service that will reset all your alarms in background. Best one for you is IntentService, because it ends itself when the work is done. Of course you need to store the information about alarms somewhere in order to remember which ones to reset. You can use, for example, SQLite to store them.
In your manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
and
<receiver android:name="developer.marat.apps.days.Alarms.BootCompletedReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="developer.marat.apps.days.Alarms.RestartAlarmsService"/>
Special receiver:
public class BootCompletedReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent i = new Intent(context, RestartAlarmsService.class);
ComponentName service = context.startService(i);
}
}
}
RestartAlarms:
public class RestartAlarmsService extends IntentService{
public RestartAlarmsService() {
super("RestartAlarmsService");
}
#Override
protected void onHandleIntent(Intent intent) {
// Restart your alarms here.
// open database, iterate through every alarm and set them again
}
}

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.

Categories

Resources