奇怪的是,我的服务确实在后台运行,但它只在应用程序关闭时创建警报,而不是在它运行时创建。任何人都可以提供一些有关为什么会发生这种情况的见解。我的服务类如下。
public class TimeDifferenceService extends Service {
DatabaseHelper myDbs;
public boolean notificationCheck;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
myDbs = new DatabaseHelper(this);
mHandler.postDelayed(mUpdateTimeChecker,100);
return START_STICKY;
}
Handler mHandler = new Handler();
final Runnable mUpdateTimeChecker = new Runnable() {
public void run() {
// do whatever you want to change here, like:
Cursor res = myDbs.GetFirstTime();
if (res.getCount() == 0) {
return;
}
while (res.moveToNext()) {
String booleancheck =res.getString(5);
notificationCheck = Boolean.parseBoolean(booleancheck);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone tz = TimeZone.getDefault();
Calendar c1 = Calendar.getInstance(tz);
Calendar c2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
try {
c1.setTime(sdf.parse(res.getString(1)));
} catch (ParseException e) {
e.printStackTrace();
}
c2.getTime();
long timeDiff = ((c1.getTimeInMillis()-c2.getTimeInMillis())/(1000*60));
if (timeDiff <= 60 && timeDiff >=0 && !notificationCheck){
setAlarm();
String notifDisplay = "true";
update(res.getInt(0),notifDisplay);
}else {
}
res.close();
}
mHandler.postDelayed(this,1000);
}
};
public void setAlarm(){
long alertTime = new GregorianCalendar().getTimeInMillis()+1*1000;
Intent alertIntent = new Intent(this,AlertReciever.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,alertTime, PendingIntent.getBroadcast(this,1,alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
}
}