您的位置:首页 > 移动开发 > Android开发

android下Service BroadcastReceiver与AlarmManager

2011-04-23 01:20 435 查看
先申明的就是本文借鉴了这片文章里的东西 http://hi.baidu.com/lith/blog/item/e0b54ffbf8df1969034f569d.html
然后写了自己需要的代码,我只把自己用到的写上了

先来代码,主Activity里的两个button的点击事件:

//MainActivity 主Activity
//AlarmService 自己的service

//启动service的button事件
Intent iAlarmService = new Intent(MainActivity.this,AlarmService.class);
startService(iAlarmService);

//结束service的button事件
Intent iAlarmService = new Intent(MainActivity.this,AlarmService.class);
stopService(iAlarmService);
//记得在manifest里添加service
<service android:name=".AlarmService"></service>


接着就是 AlarmService这个自己写的服务里的代码,因为是继承了service这个类,所以必须实现他的几个方法,我这里的两端代码主要就是onStart() 和 onDestory():

//这段是onStart()的代码,里面的hourOfDay和minute都是被我写死的一个时间

hourOfDay = 00;
minute = 51;
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(System.currentTimeMillis());

cl.set(Calendar.HOUR_OF_DAY, hourOfDay);
cl.set(Calendar.MINUTE, minute);
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MILLISECOND, 0);

Intent arIntent = new Intent(this,AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, arIntent, 0);

AlarmManager am = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cl.getTimeInMillis(), pendingIntent);

//这段是onDestory()里的代码,我个人不是很明白为啥会把intent传给主Activity去了。。
AlarmManager am = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
Intent intent = new Intent(this,MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
am.cancel(pi);
super.onDestroy();


最后就是那个BroadcastReceiver的onReceiver()了 :

Intent i = new Intent();
i.setClass(context, ShowActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);


这样就可以大致的实现用自己的service调用系统的AlarmManager和BroadcastReceiver来做点事情,比如闹钟之类的。

说下题外的话,有个广州的朋友一直感慨android会自动清除内存,这样闹钟的优先级是最低的,就会被清理掉,认为我用service只会更加增加负担,但我觉得,现在的手机基本都往大配置发展了,这些问题会漫漫的好转,前途还是光明的嘛。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐