Rumah > Soal Jawab > teks badan
书上创建一个后台服务,该服务使用了AlarmManager设置了一个一小时后启动的PendingIntent,这个PendingIntent启动一个广播接收器,然后广播接收器的onReceive方法则再次启动上述的那个服务,以此循环,达到该服务长期运行的效果。我的疑问是为什么要由广播接收器来启动服务,PendingIntent不是也有启动服务的getService方法吗,直接启动服务自身不也可以吗。
书上的代码如下:
public class LongRunningService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE); int anHour = 60*60*1000; long triggerAtTime = SystemClock.elapsedRealtime() + anHour; Intent i = new Intent(this, AlarmReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi); return super.onStartCommand(intent, flags, startId); } } public class AlarmReceiver extends BroadcastRecevier { @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(context, LongRunningService.class); context.startService(i); } }