您好我想创建一个后台服务,该服务将在每天的特定时间重复以从服务器更新数据,直到现在我有这个代码:
public class Service_class extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
@Override
public void onCreate() {
super.onCreate();
}
}
我在main
中使用此代码启动服务startService(new Intent(getBaseContext(), Service_class.class));
如何让我的服务在每天的确切时间重复,即使应用程序关闭也不会停止?谢谢
答案 0 :(得分:1)
您可以使用AlaramManager
,如下所示
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * 10), pi);
// Millisec * Second
答案 1 :(得分:0)
您可以将 AlarmManager 类用于此
Intent alarmIntent = new Intent(context, Service_class.class);
pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
int interval = 60*60*24;//number of seconds
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), interval, pendingIntent);
答案 2 :(得分:0)
我也有同样的要求。我遵循以下程序。
在您的服务onCreate()
Intent alarmIntent=new Intent(this,AlarmHandle.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 86400*1000; // for getting called every 24 hours
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

此处AlarmHandle
类扩展了BroadcastReceiver
。在提到的时间间隔值期间,将调用此接收器的onReceive
。
确保AndroidManifest文件中的receiver标记提及AlarmHandle
。
<receiver android:name=".AlarmHandle">
</receiver>
&#13;