Android实战Service BroadcastReceiver与AlarmManager
2010-08-22 04:48:00 来源:WEB开发网public static Service getService() {
return sms;
}
/*
这里有个小方法有必要说一下,在Service或Activity中我们可以写一个静态的方法来保留自己的实体。这样在其他的地方就可以获取到了。
private static SleepMusicService sms = null; 用来存储自己的实体
在onCreate()中 使用sms = this;来存储实体
编写一个静态的getService()来返回实体就行了。
*/
@Override
public void onCreate() {
super.onCreate();
sms = this;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(TAG, "Service onStart");
//获取AlarmManager
AlarmManager am = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
//获取当前的时间
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
// 只对秒 做修改
// c.set(Calendar.HOUR_OF_DAY, hourOfDay);
// c.set(Calendar.MINUTE, c.get(Calendar.MINUTE));
c.set(Calendar.SECOND, c.get(Calendar.SECOND) + 5); //定时5秒
//c.set(Calendar.MILLISECOND, 0);
//设置消息的响应
Intent ii = new Intent(this, AlarmReceiver.class);
PendingIntent pii = PendingIntent.getBroadcast(this, 0, ii, 0);
am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pii);
//使用Toast提示用户
Toast.makeText(this, "AlarmSet Finish", Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
AlarmManager am = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
Intent i = new Intent(this, StartActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
am.cancel(pi);
super.onDestroy();
}
@Override
更多精彩
赞助商链接