Android Service 入门
说明
Service 工作在主进程上。生命周期图

两种状态
Started
比如Activity通过调用startService 方法。一旦被启动(Started),服务就永久在后台运行,即使创建他的Activity被销毁。
Bound
当一个Component通过调用bindService方法来绑定该服务。服务提供接口让组件和服务交互。
回调方法说明
onStartCommand 其他组件通过调用startService时,被调用,如果实现该方法,需要调用stopSelf或者stopService来结束服务。
onBind 其他组件通过调用bindService时,被调用。需要实现接口,返回IBinder对象,让Client和服务交互。如果不绑定服务,返回null
onUnbind 所有已经绑定的组件断开
onCreate创建服务只有一次。
onDestroy服务被销毁时调用,这里应该清理相应资源。
例子1:
主界面两个按钮

Activity对应的两个方法
public void startService(View view)
{ startService(new Intent(getBaseContext(), MyService.class));
}
public void stopService(View view)
{
stopService(new Intent(getBaseContext(), MyService.class));
}
服务类的内容
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Servcie Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
}
}
然后在AndroidManifest.xml中添加

运行效果
点击启动服务

点击停止服务

例子2:使用绑定服务,并且在Activity中调用Service的内部类的方法
在例子1的基础上
public class MyService extends Service {
public static final String SERVICE_LOG = "service_LOG";
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d(SERVICE_LOG, "MyServic Bound");
return new Mybind();
}
@Override
public boolean onUnbind(Intent intent) {
Log.d(SERVICE_LOG, "MyService Unbound");
return super.onUnbind(intent);
}
@Override
public void onCreate() {
super.onCreate();
Log.d(SERVICE_LOG, "Myservice created");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(SERVICE_LOG, "Myservice Started");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(SERVICE_LOG, "MyService destroyed");
}
public class Mybind extends Binder
{
public void getString() {
Log.d(SERVICE_LOG, "============> get a string");
}
}
}
主要变化,新增内部类Mybind,并且在onBind返回Mybind对象。
Activity中新增

.
新增代码
private MyService.Mybind mybind;
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mybind = (MyService.Mybind) iBinder;
mybind.getString();
} @Override
public void onServiceDisconnected(ComponentName componentName) { }
};
public void BindService(View view) {
Intent bindIntent = new Intent(LoginActivity.this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
} public void UnbindService(View view) {
unbindService(connection);
}
全部代码
public class LoginActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_login);
}
public void startService(View view)
{startService(new Intent(getBaseContext(), MyService.class));
}
public void stopService(View view)
{
stopService(new Intent(getBaseContext(), MyService.class));
}
private MyService.Mybind mybind;
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mybind = (MyService.Mybind) iBinder;
mybind.getString();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
public void BindService(View view) {
Intent bindIntent = new Intent(LoginActivity.this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
}
public void UnbindService(View view) {
unbindService(connection);
}
}
运行效果
A测试
点击绑定服务,此时创建服务,然后绑定服务,
Myservice created
MyService Bound
============> get a string
点击解除绑定(解绑之后,再点击解绑,程序会崩溃)
MyService Unbound
MyService destroyed
如果Activity销毁,服务同样自动解绑,销毁。
B测试
点击启动服务
Myservice created
Myservice Started
点击绑定服务
MyServic Bound
============> get a string
点击解除绑定
MyService Unbound
因为是通过startService创建的后台Service,不会销毁。
如果有client绑定,点击“停止服务”,service 不会停止,一旦所有client解除绑定,因为已经点击过“停止服务”,此时服务停止。
Android Service 入门的更多相关文章
- [译]:Xamarin.Android开发入门——Hello,Android Multiscreen深入理解
原文链接:Hello, Android Multiscreen_DeepDive. 译文链接:Xamarin.Android开发入门--Hello,Android Multiscreen深入理解. 本 ...
- android service 本地 远程 总结
android编写Service入门 android SDK提供了Service,用于类似*nix守护进程或者windows的服务. Service有两种类型: 本地服务(Local Service) ...
- Android开发入门要点记录:四大组件
cocos2dx跨平台开发中需要了解android开发,昨天快速的浏览了一本Android开发入门教程,因为之前也似懂非懂的写过Activity,Intent,XML文件,还有里面许多控件甚至编程思想 ...
- [译]:Xamarin.Android开发入门——Hello,Android深入理解
返回索引目录 原文链接:Hello, Android_DeepDive. 译文链接:Xamarin.Android开发入门--Hello,Android深入理解 本部分介绍利用Xamarin开发And ...
- [译]:Xamarin.Android开发入门——Hello,Android快速上手
返回索引目录 原文链接:Hello, Android_Quickstart. 译文链接:Xamarin.Android开发入门--Hello,Android快速上手 本部分介绍利用Xamarin开发A ...
- android service两种启动方式
android service的启动方式有以下两种: 1.Context.startService()方式启动,生命周期如下所示,启动时,startService->onCreate()-> ...
- 1、Android Studio集成极光推送(Jpush) 报错 java.lang.UnsatisfiedLinkError: cn.jpush.android.service.PushProtoco
Android studio 集成极光推送(Jpush) (华为手机)报错, E/JPush: [JPushGlobal] Get sdk version fail![获取sdk版本失败!] W/Sy ...
- Android Service完全解析,关于服务你所需知道的一切(下)
转载请注册出处:http://blog.csdn.net/guolin_blog/article/details/9797169 在上一篇文章中,我们学习了Android Service相关的许多重要 ...
- Android Service完全解析,关于服务你所需知道的一切(上)
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/11952435 相信大多数朋友对Service这个名词都不会陌生,没错,一个老练的A ...
随机推荐
- [Spring] Spring Data JPA
Previouly we need to define a DAO interface and a DAO impl for 'Employee', it is not so reuseable, s ...
- PHP mysqli_num_rows() 函数
<?php // 假定数据库用户名:root,密码:123456,数据库:RUNOOB $con=mysqli_connect("localhost","root& ...
- pat 甲级 1045 ( Favorite Color Stripe ) (动态规划 )
1045 Favorite Color Stripe (30 分) Eva is trying to make her own color stripe out of a given one. She ...
- vue-cli 3.x 修改dist路径和在本地查看方法
打包文件路径问题 需要在项目的根目录添加一个vue.config.js.在这个文件中,我们可以进行一些个性化定制. module.exports = { // 基本路径 baseUrl: './', ...
- vue 编译大量空格警告问题总结 warning: Replace `↹↹` with `··`
1.vue开发中发现最后越来越多的编译警告,如 warning: Replace `↹↹` with `··` (prettier/prettier) at src/views/shebei/shou ...
- hadoop HA+Federation(高可用联邦)搭建配置(一)
hadoop HA+Federation(高可用联邦)搭建配置(一) 标签(空格分隔): 未分类 介绍 hadoop 集群一共有4种部署模式,详见<hadoop 生态圈介绍>. HA联邦模 ...
- shell练习1
题目 把ls -l 的输出按照属主分类,打印每个属住的文件名 ls -l |sed -n '2,$p'| awk ' {hash[$]=hash[$]} END{ for (user in hash) ...
- Visual Studio Code(VS code)介绍
一.日常安利 VS code VS vode特点: 开源,免费: 自定义配置 集成git 智能提示强大 支持各种文件格式(html/jade/css/less/sass/xml) 调试功能强大 各种方 ...
- vue 复制内容到粘贴板
首先是npm安装依赖包:npm install clipboard --save 导入组件:import Clipboard from "clipboard"; html如图: c ...
- Nginx之 Location 的生成
1. Location 的生成 location 的生成大致有三种: 由 location 指令直接生成 命令 location:仅用于 server 内部跳转,如 rewrite 就是命名 loca ...