Service相对于Activity可在后台运行,五显示界面,在activity退出的情况下仍能运行。

一.新建一个空的工程,命名为learnService

二.新建一个service,并添加如下所示代码:

鼠标移到java下的com.example.luozhenshan.learnservice,右键->new service

 @Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(){
public void run() {
super.run();
while (true) {
System.out.println("Service is running");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} }.start();
return super.onStartCommand(intent, flags, startId);
}

三.给MainActivity添加两个按钮

四.修改MainAcitivity.java中的代码

 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnStartService).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, MyService.class));
}
});
findViewById(R.id.btnStopService).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(MainActivity.this, MyService.class));
}
});
}

五.运行结果

最新文章

  1. C#结合Jquery LigerUI Tree插件构造树
  2. Reactjs的Controller View模式
  3. Windows Server 2008 显示桌面图标
  4. SCU 2941 I NEED A OFFER!(01背包变形)
  5. Python-S13作业-day4-之登陆,管理后台
  6. html状态码与缓存学习
  7. shiro中unauthorizedUrl不起作用
  8. JS 立即执行的函数表达式(function)写法
  9. 全世界最详细的图形化VMware中linux环境下oracle安装(三)【weber出品必属精品】
  10. Oracle EBS-SQL (MRP-1):检查期间内计划完成的任务.sql
  11. 用VulApps快速搭建各种漏洞环境
  12. Python:名片管理系统(增加登录功能后出现问题,求教)
  13. Pyinstaller (python打包为exe文件)
  14. [dev]typeof, offsetof 和container_of
  15. 转://Oracle 单引号转义
  16. AtCoder Beginner Contest 053
  17. 【转】浅析SkipList跳跃表原理及代码实现
  18. 正确实现用spring扫描自定义的annotation
  19. JS document.execCommand实现复制功能(带你出坑)
  20. Pytest 简明教程

热门文章

  1. SpringMVC 接收复杂对象
  2. quick lua 使用spine骨骼动画
  3. 上传文件时,Request报文头不同浏览器会产生不同的content-type
  4. python安装numpy科学计算模块
  5. c#之线程池
  6. php时间函数整理
  7. StringBuffer中的flush()方法作用
  8. Who's in the Middle 分类: POJ 2015-06-12 19:45 11人阅读 评论(0) 收藏
  9. 关于接收json以及使用json
  10. Mybatis like 模糊查询问题