服务的应用-后台执行的定时任务

时间:2022-01-09 08:15:01

介绍

1定时操作的实现方式:Alarm
获取实例:
AlarmManger manger = (AlarmManger )getSystemService(Context.ALARM_SERVICE);
设置任务的时间:
long triggerAtTime =long triggerAtTime = SystemClock.elapsedRealtime()+10*1000; 定时10s
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP , triggerAtTime , pendingIntent);


ELAPSED_REALTIME 从系统开机时间开始算起,不唤醒cpu
ELAPSED_REALTIME_WAKEUP 从系统开机时间开始算起,不唤醒cpu
RTC 从1970年1月1号开机时间开始算起,不唤醒cpu
RTC_WAKEUP 从1970年1月1号开机时间开始算起,不唤醒cpu

<service android:name=".LongRunningService"></service>
<receiver android:name=".AlarmReceiver"></receiver>
package com.example.servicebestpractice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import java.util.Date;

public class LongRunningService extends Service {
public IBinder onBind(Intent intent){
return null ;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
Log.d("LongRunningService" , "executed at" + new Date().toString());
}
}).start();

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);
}
}
package com.example.servicebestpractice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;


public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent( context, LongRunningService.class);
context.startService(i);
}
}

由于广播接收器在1小时后收到广播,而在收到广播后又会重新启动服务,因此会一直循环。