我正在尝试在android中启动2个服务。一项服务应在每天上午10点触发通知,另一项服务将有3项任务,首先更改时钟到达上午12点的那天的值,然后分别在下午12点和下午6点显示基于条件的通知。
要做到这一点,我正在使用timertask和一个计时器。该服务确实在后台运行,但任务不执行。起初我尝试通过正常设置我的日历到所需的时间来做到这一点,但这导致任务一旦我启动应用程序并执行调用服务可能因为它赶上当天的时间可能已经过去。所以我试着通过在第一次执行的时间增加24小时(即86400000毫秒)来延迟它。
这是我的代码:
第一次服务
$(".result>span.message").html(response);
第二次服务
public class reminder extends Service{
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
/* NotificationCompat.Builder b = new NotificationCompat.Builder(this);
b.setSmallIcon(R.drawable.tmcnotification);
b.setContentTitle("TechMotherCare is Running");
startForeground(1,b.build());*/
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "started 2", Toast.LENGTH_SHORT).show();
Intent resultIntent = new Intent(this, reminderresponse.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
final NotificationCompat.Builder n= new NotificationCompat.Builder(this);
n.setContentTitle("How are you feeling?");
n.setSmallIcon(R.drawable.tmcnotification);
n.setContentText("Tap to open window.");
n.setContentIntent(resultPendingIntent);
n.setAutoCancel(true);
final NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
JodaTimeAndroid.init(this);
DateTime now = DateTime.now();
final int time = now.getHourOfDay();
final MediaPlayer pl = new MediaPlayer().create(this,R.raw.tune);
final Calendar c= Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY,10);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
//c.set(Calendar.AM_PM,Calendar.PM);
Timer t = new Timer();
Date w=c.getTime();
TimerTask notify = new TimerTask() {
@Override
public void run() {
pl.start();
mNotifyMgr.notify(1,n.build());
}
};
//t.schedule(notify,c.getTime(),(1*60*60*1000));
t.schedule(notify, new Date(w.getTime()+86400000),TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS));
}
}