上下文:我正在尝试通过 AlarmManager 实现一个服务调用第二个服务(第一个服务的子类)。为此,我需要创建一个广播接收器作为内部类,如此处所推荐的(Service 和 BroadCastReceiver)。但是,似乎第一个服务从未成功调用第二个服务,或者第二个服务没有接收到调用。
我环顾四周,发现其他人也遇到了类似的问题,但从未解决:来自 service 的 AlarmManager。
第一个服务中调用第二个服务的代码很简单:
private final long ONE_MINUTE = 60*1000*1;
Context theContext = getBaseContext();
AlarmManager theService = (AlarmManager) theContext
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(theContext, LocalWordSubClass.class);
PendingIntent thePending = PendingIntent.getBroadcast(theContext, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
//call this after two minutes
theService.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+TWO_MINUTES, thePending);
我的第二项服务是:
public class LocalWordSubClass extends LocalWordService {
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(checkIfGooglePlay() && checkTime()) {
getPostLocation();
}
mLocationClient.disconnect(); //connected in the first service class
stopSelf();
}
};
}
我的第二项服务清单得到认可:
<service
android:name=".LocalWordSubClass"
android:label="LocalWordSubClass" >
</service>
问题:我没有实现方法吗?还是我需要将广播接收器添加到清单中?我有点困惑为什么二等舱没有响应。
**更新:** 感谢 CommonWare 的多项建议,我能够在连接 LocationClient 和获取其最后一个位置之间实现这一分钟的间隔。但是,当 MainActivity 的 AlarmManager 的 setRepeating 方法调用该服务时,该服务不再重复运行。
这是代码(成功地为 locationClient 提供了连接时间)
if(mLocationClient==null) {
pm = (PowerManager) getBaseContext().getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
initalizeLocks();
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
Context theContext = getBaseContext();
AlarmManager theService = (AlarmManager) theContext
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(LocalWordService.this, this.getClass());
PendingIntent thePending = PendingIntent.getService(this, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
//call this after two minutes
theService.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ONE_MINUTE, thePending);
} else {
getPostLocation();
wl.release();
mLocationClient = null;
stopSelf();
}
MainActivity 的 AlarmManager 是:
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, LocalWordService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.
setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), EVERY_TWO_MINUTES, pintent);