我想创建一个定期执行功能的服务,并在满足某些要求时调用另一个功能。所有这些都应该在后台进程中发生。
这是我主要活动的onPause方法,我启动了应该执行所需任务的服务:
@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
if(alarm){
bgIntent = new Intent(this, bgAlarmService.class);
startService(bgIntent);
alarmHostIsService = true;
}
}
onStartCommand我的服务:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Runnable r = new Runnable() {
@Override
public void run() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(bgAlarmService.this)
.addConnectionCallbacks(bgAlarmService.this)
.addOnConnectionFailedListener(bgAlarmService.this)
.addApi(LocationServices.API)
.build();
}
mGoogleApiClient.connect();
}
};
Thread bgThread = new Thread(r);
bgThread.start();
return START_NOT_STICKY;
}
但是当调用onPause方法并且app变为非活动状态时,该服务确实无法继续工作。如何在后台运行此服务?
答案 0 :(得分:3)
使用服务和广播接收器来做到这一点。 在修复时间间隔使用以下代码发送brodcast。
Calendar calendar = Calendar.getInstance();
long currentDateTime=calendar.getTimeInMillis();
calendar.setTime(new Date(currentDateTime+(5*60*1000)));// 5 minutes timeout
Intent myIntent = new Intent(this,YourReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
广播接收器内的现在在onStartCommand内启动服务。
Intent yourService= new Intent(context, YourService.class);
context.startService(Intent yourService= new Intent(context, YourService.class);