动态注册广播接收器必须有实例存在
设置系统时区:
AlarmManager mAlarmManager =
(AlarmManager)getSystemService(Context.ALARM_SERVICE);
mAlarmManager.setTimeZone("GMT+08:00");
设置时区需要在manifest.xml中增加如下权限:
<!--
允许设置时区-->
<uses-permission
android:name="android.permission.SET_TIME_ZONE"
/>
package com.lzh.modeify;
import java.util.Calendar;
import java.util.Timer;
import android.R.integer;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
public class ZoneService extends Service {
private static final String ACTION_DATE_CHANGED = Intent.ACTION_DATE_CHANGED;
private static final String ACTION_TIME_CHANGED = Intent.ACTION_TIME_CHANGED;
private BroadcastReceiver TimerChangered = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Calendar c = Calendar.getInstance();// 可以对每个时间域单独修改
// int year = c.get(Calendar.YEAR);
// int month = c.get(Calendar.MONTH);
// int date = c.get(Calendar.DATE);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
Log.v("time", Integer.toString(hour)+Integer.toString(minute)+Integer.toString(second));
}
};
private BroadcastReceiver stopServiceReceiver = new BroadcastReceiver() {
public void onReceive(android.content.Context context, Intent intent) {
ZoneService.this.stopSelf();
ZoneService.this.unregisterReceiver(stopServiceReceiver);
};
};
@Override
public void onCreate() {
super.onCreate();
Log.i("liujun", "后台进程被创建。。。");
IntentFilter intentFilter = new IntentFilter("closeService");
ZoneService.this.registerReceiver(stopServiceReceiver, intentFilter);
// 服务启动广播接收器,使得广播接收器可以在程序退出后在后天继续执行,接收系统时间变更广播事件
ZoneService.this.registerReceiver(TimerChangered, new IntentFilter(
Intent.ACTION_TIME_TICK));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("liujun", "后台进程。。。");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i("liujun", "后台进程被销毁了。。。");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO 自动生成的方法存根
return null;
}
}
MainActivity.this.sendBroadcast(new Intent("closeService"));
MainActivity.this.startService(new Intent(MainActivity.this,ZoneService.class));