-
本案例知识是:后台执行定时任务。
Alarm机制:
一、创建LongRunningService类
123456789101112131415161718192021222324252627282930313233343536373839404142package
com.example.servicebestpractice;
import
java.util.Date;
import
android.app.AlarmManager;
import
android.app.PendingIntent;
import
android.app.Service;
import
android.content.Intent;
import
android.os.IBinder;
import
android.os.SystemClock;
public
class
LongRunningService
extends
Service {
@Override
public
IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return
null
;
}
@Override
public
int
onStartCommand(Intent intent,
int
flags,
int
startId) {
new
Thread(
new
Runnable() {
@Override
public
void
run() {
// 打印日志模拟耗时操作。
System.out.println(
"服务启动时间:"
+
new
Date().toString());
}
}).start();
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
int
times =
1000
*
60
;
// 设置相隔多久启动一次广播,我设置为1分钟启动一次服务,去执行定时任务(虽然我写的是打印一条日志,看起来很无趣)
long
triggerAtime = SystemClock.elapsedRealtime() + times;
// 设置触发时间点
Intent i =
new
Intent(
this
, AlarmReceiver.
class
);
// 服务启动广播的intent意图
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this
,
0
, i,
0
);
// 封装pendingIntent,启动广播接收者意图
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtime,
pendingIntent);
// 设置精确定时时间,定时到了触发,广播启动。
return
super
.onStartCommand(intent, flags, startId);
}
}
二、创建要接收上述要启动的广播。1234567891011121314151617package
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 intent2 =
new
Intent(context, LongRunningService.
class
);
context.startService(intent2);
//启动广播做启动服务操作,服务又一次启动。
//由于服务不再前台,因此不需要设置addFlags();方法。因为服务不再借助任务栈去创建了。
}
}
三、我们要有一个启动服务的入口,那就选择在主活动作为入口:12345678910111213141516171819package
com.example.servicebestpractice;
import
android.os.Bundle;
import
android.app.Activity;
import
android.content.Intent;
import
android.view.Menu;
public
class
MainActivity
extends
Activity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//主活动要首先有一次启动服务的操作
Intent intent3 =
new
Intent(
this
, LongRunningService.
class
);
startService(intent3);
//启动服务
}
}
四、广播、活动、服务三大 组件记得去清单文件配置一下:12345678910111213<intent-filter>
<category android:name=
"android.intent.category.LAUNCHER"
>
</category></action></intent-filter>
</activity>
<service android:name=
"com.example.servicebestpractice.LongRunningService"
>
</service>
<receiver android:name=
"com.example.servicebestpractice.AlarmReceiver"
>
</receiver>
写完这篇博客后,看了一下我的log后台输出如下截图:每隔一分钟,定时任务完成,启动一次服务。
Android初级教程启动定时器详解
最新推荐文章于 2023-02-13 16:30:55 发布