开机广播权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
开机广播 注册
<receiver android:name="com.stone.receiver.BootedReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver>
开机广播
public class BootedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { context.startService(new Intent(context, TimeService.class)); } }
时间服务
//服务 用于 注册 监听时间变化、设置的广播 时间变化广播只能动态注册 public class TimeService extends Service { //监听时间变化的 这个receiver只能动态创建 private TimeTickReceiver mTickReceiver; private IntentFilter mFilter; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { 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) { System.out.println("启动了服务"); return Service.START_STICKY; } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mTickReceiver); } }
监听时间改变、设置 广播
public class TimeTickReceiver extends BroadcastReceiver { private boolean flag; @Override public void onReceive(Context context, Intent intent) { // System.out.println("时间变了" + intent.getAction()); if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { //每过一分钟 触发 } } else { /* * 系统bug?? * android.intent.action.TIME_SET 当调整系统时间后 这个action会收到两次 */ if (flag) { try { AlarmUtil.startAlarm(context); } catch (DbException e) { e.printStackTrace(); } flag = false; //第二次置false } else { flag = true; //第一次置true } } } }
时间: 2024-10-02 11:08:47