Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action at a fixed time in Android [closed]

Tags:

android

action

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.

like image 351
user2171300 Avatar asked Dec 04 '25 10:12

user2171300


1 Answers

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);
}
like image 77
Mieszko Avatar answered Dec 06 '25 23:12

Mieszko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!