我一直在努力解决这个问题 . 我想要做的是定期运行服务,间隔约2-3分钟 . 我有一个Activity负责界面和设置第一个警报 .
警报由BroadcastReceiver配置,如下所示:
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = "Alarm worked";
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
setAlarm(context);
}
public void setAlarm(Context context){
AlarmManager am = (AlarmManager) context.
getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, Receiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent dailyUpdater = new Intent(context, DiscoveryService.class);
context.startService(dailyUpdater);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (1000 * 30) , pi);
}
}
我已经尝试使用setRepeating for AlarmManager,但它仍然具有相同的效果 . 会发生什么事情是AlarmManager工作的方式,它会触发接收器获取的Intent并定期执行onReceive,就像它应该的那样 . 但是,它仅在第一次执行服务 . 在第一次之后,警报仍然关闭,但服务未执行 .
我从有类似问题的人那里读了一些帖子,其中一个提到PendingIntent只持续一次发送 . 因此,我每次都选择设置闹钟,因此我可以设置pendingIntent标志以便每次更新 .
我尝试使我的服务成为一个intentService,这很好,但是然后我在服务中的蓝牙扫描程序不起作用,因为intentService线程终止而没有等待我的蓝牙发现完成 .
任何人都知道什么可以帮助我?
这是我服务的一部分:
public class DiscoveryService extends Service {
public void onCreate() {
super.onCreate();
Toast.makeText(this, "MyAlarmService.onCreate()",
Toast.LENGTH_LONG).show();
findEverything();
}
}
编辑:这是我目前的代码 .
public void onReceive(Context context, Intent intent) {
String message = "Alarm worked";
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
Intent dailyUpdater = new Intent(context, DiscoveryService.class);
context.startService(dailyUpdater);
}
public void setAlarm(Context context){
// get a Calendar object with current time
AlarmManager am=(AlarmManager)context.
getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, Receiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
(1000 * 30) , pi);
}
1 回答
在安排警报时,您正在调用
startService()
. 你根本没有从BroadcastReceiver
调用startService()
. 然而,您正在通过BroadcastReceiver
安排警报 . 因此,当警报响起时,服务将不会发送命令,因为您没有发送命令 .那只有你使用
FLAG_ONE_SHOT
.从
onReceive()
方法调用startService()
,而不是从setAlarm()
方法调用 . 此外,添加所有WakeLock
管理逻辑,因为您正在使用_WAKEUP
警报,而您无法使用我的WakefulIntentService
.