I have a service called service. How do I get this service sound an alarm or launch a toast at a fixed time, for example at 8:00 am.
in your service set proper time for Calendar instance object:
Calendar calendar = Calendar.getInstance();
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
int mHour = calendar.get(Calendar.HOUR_OF_DAY);
if(mHour >= 8)
mDay++;
//set 8:00 a.m.
calendar.set(mYear, mMonth, mDay, 8, 0, 0);
then use AlarmManager to plan your event:
Intent intent = new Intent(MyService.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MyService.this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
and your AlarmReceiver class:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm Receiver message", Toast.LENGTH_SHORT).show();
}
Remember to add BraodcastReceiver to your Manifest file:
<receiver android:name=".receiver.AlarmReceiver"/>
EDIT: override onStartCommand method
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
lanzarclase();
return super.onStartCommand(intent, flags, startId);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With