这是我想要完成的事情并且严重失败。
我需要:
- 启动服务
- 做一些任务
- 设置AlarmManager以在一段时间后再次启动服务
- 停止服务
我遇到的问题是服务正在重新启动,几乎立即被停止。我想要的是服务应该在闹钟响起后启动..
以下是代码: -
Intent intent = new Intent(ThisService.this,
ThisService.class);
PendingIntent pendingIntent = PendingIntent.getService(ThisService.this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.cancel(pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
getUpdateTime(), getUpdateTime(), pendingIntent);
stopSelf();
答案 0 :(得分:1)
您缺少的是广播接收器
流程应为
请参阅http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html
//-----Set the alarm to trigger the broadcast reciver-----------------------------
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds",
Toast.LENGTH_LONG).show();
//---------------Call StopSelf here--------------------
//----------------------------------------------------------------------------------
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//-----------write code to start the service--------------------------
}
}