Android中Intent,service,broadcast应用浅析(一)
- public class Activity01 extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button startService = (Button) findViewById(R.id.startBtn);
- startService.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- startService(new Intent(Activity01.this,
- BackgroundService.class));
- }
- });
- Button stopService = (Button) findViewById(R.id.stopBtn);
- stopService.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- stopService(new Intent(Activity01.this, BackgroundService.class));
- }
- });
- }
- }
- @Override
- public void onCreate() {
- super.onCreate();
- notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- handler = new Handler() {
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case 1:
- seconds++;
- updateNotification(seconds);
- break;
- }
- super.handleMessage(msg);
- }
- };
- timer = new Timer(false);
- }
- @Override
- public void onStart(Intent intent, int startId) {
- super.onStart(intent, startId);
- displayNotificationMessage("starting Background Service");
- timer.schedule(new TimerTask() {
- @Override
- public void run() {
- Message message = new Message();
- message.what = 1;
- handler.sendMessage(message);
- }
- }, 1000, 1000);
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- displayNotificationMessage("stopping Background Service");
- seconds = 0;
- timer.cancel();
- }
- private void displayNotificationMessage(String message) {
- Notification notification = new Notification(R.drawable.icon, message,
- System.currentTimeMillis());
- PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
- new Intent(this, Activity01.class), 0);
- notification.setLatestEventInfo(this, "Background Service", message,
- contentIntent);
- notificationMgr.notify(R.id.app_notification_id, notification);
- }