Android Broadcast调用Service做的一个定时器
2010-08-20 02:13:00 来源:WEB开发网Java代码
1. public class AlarmActivity extends Activity implements OnClickListener {
2. private Button b_call_service, b_exit_service;
3. private Intent intent;
4. private PendingIntent p_intent;
5.
6. public void onCreate(Bundle icicle) {
7. super.onCreate(icicle);
8. setContentView(R.layout.main);
9. b_call_service = (Button) findViewById(R.id.call_alarm_service);
10. b_call_service.setOnClickListener(this);
11. b_exit_service = (Button) findViewById(R.id.exit);
12. b_exit_service.setOnClickListener(this);
13.
14. intent = new Intent(this, AlarmReceiver.class);
15. p_intent = PendingIntent.getBroadcast(this, 0, intent, 0);
16. }
17.
18. public void onClick(View arg0) {
19. if (arg0 == b_call_service) {
20. setTitle("Waiting... 5s后Alarm启动");
21.
22. Calendar calendar = Calendar.getInstance();
23. calendar.setTimeInMillis(System.currentTimeMillis());
24. calendar.add(Calendar.SECOND, 5);
25.
26. AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
27. am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), p_intent);
28. }
29.
30. if (arg0 == b_exit_service) {
31. setTitle("Alarm关闭");
32. AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
33. am.cancel(p_intent);
34. }
35. }
36. }
public class AlarmActivity extends Activity implements OnClickListener {
private Button b_call_service, b_exit_service;
private Intent intent;
private PendingIntent p_intent;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
更多精彩
赞助商链接