Шаг 1: Вы должны создать сервис, для которого здесь мой сервис MyAlarmService.class, как показано ниже
public class MyAlarmService extends Service {
@Override
public void onCreate() {
// Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent intent) {
//Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
//Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
try
{
Context context = getApplicationContext();
// Displaying Notification
NotificationManager manger = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "Notification", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), Target.class), 0);
notification.setLatestEventInfo(getApplicationContext(), "Notification", "Notification subject", contentIntent);
notification.flags = Notification.FLAG_INSISTENT;
int NOTIFICATION_ID=(int)System.currentTimeMillis();
manger.notify(NOTIFICATION_ID, notification);
}
catch(Exception e)
{
e.printStackTrace();
}
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
}
Шаг 2: Вы должны создать ожидающее намерение, как показано ниже
Intent myIntent = new Intent(SynchronizeData.this, MyAlarmService.class);
PendingIntent pendingIntent = PendingIntent.getService(this.getApplicationContext(), 0, myIntent, 0);
Step 3 : Create set Alarm
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,triggerTime, pendingIntent);
// trigger time is your time interval in milliseconds
Примечание: Не забыл объявить службу в AndroidManifest.xml