新建服务类
public class TimeService extends Service{
//监听时间变化的 这个receiver只能动态创建
private TimeTickReceiver mTickReceiver;
private IntentFilter mFilter;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.d("flag--","onCreate(TimeService.java:27)-->>");
super.onCreate();
mFilter = new IntentFilter();
mFilter.addAction(Intent.ACTION_TIME_TICK); //每分钟变化的action
mFilter.addAction(Intent.ACTION_TIME_CHANGED); //设置了系统时间的action
mTickReceiver = new TimeTickReceiver();
registerReceiver(mTickReceiver, mFilter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("flag--","onStartCommand(TimeService.java:37)-->>"+"启动了服务");
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mTickReceiver);
}
}
新建Reveicer
开启时启动服务
public class BootedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("flag--","onReceive(BootedReceiver.java:18)-->>"+"startService");
context.startService(new Intent(context, TimeService.class));
}
}
public class TimeTickReceiver extends BroadcastReceiver{
private boolean flag;
@Override
public void onReceive(Context context, Intent intent) {
Log.d("flag--","onReceive(TimeTickReceiver.java:17)-->>"+"时间变了" + intent.getAction());
if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
//每过一分钟 触发
Log.d("flag--", "onReceive(TimeTickReceiver.java:21)-->>" + "time change");
} else {
/*
* 系统bug??
* android.intent.action.TIME_SET 当调整系统时间后 这个action会收到两次
*/
if (flag) {
try {
/* do some thing */
} catch (Exception e) {
e.printStackTrace();
}
flag = false; //第二次置false
} else {
flag = true; //第一次置true
}
}
}
}
在manifest文件中添加
<!--开机时自动启动-->
<receiver android:name="com.halfopen.h.cislsign.receiver.BootedReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<!--声明服务-->
<service android:name=".service.TimeService"/>
添加广播权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
最终效果
可从看到服务已经启动
出现在开机启动项里面