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