Ramprasad
Ramprasad

Reputation: 8071

How to run the service from 8 AM to 8 PM everyday in Android

I have a Service in Android. I want to run this service from 8 AM to 8 PM everyday. How to do this in Android Application.Already My service start on BootUp using Broadcastreceiver BootUp event.How to do this?

Upvotes: 0

Views: 439

Answers (2)

Ramprasad
Ramprasad

Reputation: 8071

I have tried Alarm Manager like below. I want to start 8 AM...But it was not start Application on 8 AM..But All Toast message displays...

AlarmReceiver.class

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Alarm Receiver", Toast.LENGTH_LONG).show();
    AlarmManager alarm=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, MyService.class);  

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, i, 0);
    Calendar time = Calendar.getInstance();
    //time.setTimeInMillis(System.currentTimeMillis());
    time.add(Calendar.MINUTE, 8);
    time.add(Calendar.HOUR, 0);
    time.add(Calendar.SECOND, 0);
    Toast.makeText(context, "App will start shortly", Toast.LENGTH_LONG).show();
    Toast.makeText(context, time.toString(), Toast.LENGTH_LONG).show();
    alarm.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);
}
}

Manifestfile:

</application>
<receiver android:name="AlarmReceiver">  
            <intent-filter>  
                <action android:name="android.intent.action.BOOT_COMPLETED" />  
            </intent-filter>  
        </receiver>
</application>
       <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
        <uses-permission android:name="android.permission.SET_TIME"/>

Upvotes: 1

Lucifer
Lucifer

Reputation: 29642

You need to use the AlarmManager Class for this purpose. Just register your activity/service in the alarm you want to repeat at time. and start the alarm.

Upvotes: 1

Related Questions