Android用AlarmManager实现后台任务-android学习之旅(63)

因为Timer不能唤醒cpu,所以会在省电的原因下失效,所以需要唤醒cpu在后台稳定化的执行任务,AlarmManager能够唤醒cpu

这个例子讲解了如何通过Service来在后他每一个小时执行.特定的任务,原理是在Service里面设置一个一小时定时,然后到了一个小时以后启动BroadCast,然后在onReceive方法中再次启动Service,这样每一个小时就启动一次Service,行程循环

代码如下

activity

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this,LongRunningService.class);
        startService(intent);
    }

service

public class LongRunningService extends Service {
    public LongRunningService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("LongRunningService", "excuted" + new Date().toString());
            }
        }).start();
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int anHour = 60*60*1000;
        long trigerAtTime = SystemClock.elapsedRealtime()+anHour;
        Intent alarmIntent = new Intent(this,AlarmReceive.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,alarmIntent,0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,trigerAtTime,pendingIntent);
        return super.onStartCommand(intent, flags, startId);
    }
}

receiver

public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Intent i = new Intent(context,LongRunningService.class);
        context.startService(i);
    }
}

你可能感兴趣的:(android,alarm,android后台,android定时)