标签:
课程背景:
Service 是 Android 四大基本组件之一,是无界面的应用程序,可以长期在后台运行,在实际工作中非常重要,比如接收推送消息、在锁屏状态下侦听传感器信息。
核心内容:
1.启动Service
2.绑定Service
新建Service文件:MyService.java
重写Serivce的启动函数:
@Override public int onStartCommand(Intent intent, int flags, int startId) { new Thread(){ @Override public void run() { super.run(); while (true) { System.out.println("服务正在运行..."); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); return super.onStartCommand(intent, flags, startId); }
启动Service:
startService(new Intent(MainActivity.this, MyService.class));
停止Service:
//一个程序中Service只能存在一个,新创建一个Intent并不影响最终效果 stopService(new Intent(MainActivity.this, MyService.class));
《Android笔记3.7》 认识 Android Service
标签:
原文地址:http://www.cnblogs.com/woodk/p/4704984.html