Service启动,绑定与交互
1. Service的启动方式有startServcie和bindService两种。
startService时,会经历onCreate—onStartCommand—onDestroy生命周期,
bindService时,会经历onCreate—onBind—onUnbind—onDestroy生命周期。
2. Service与Activity之间交互时,可以通过bindService获取Service的连接的Binder,进而可以获取Service的引用,这样就可以与Service进行交互了。示例中,通过Service每秒更新TextView一次。
ICounterCallback接口
package com.fxb.servicetest;
public interface ICounterCallback {
public void count(int val);
}
CountService类
package com.fxb.servicetest; import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log; public class CountService extends Service{ private volatile boolean isRunning = true;
private CounterBinder counterBinder = new CounterBinder(); @Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i(MainActivity.TAG, "on bind!");
return counterBinder;
} public void startCounter(final int value, final ICounterCallback callback){
isRunning = true;
new AsyncTask<Integer, Integer, Void>() {
@Override
protected Void doInBackground(Integer... params) {
int count = params[0];
while(isRunning){
try {
Thread.sleep(1000);
count++;
Log.i(MainActivity.TAG, Integer.toString(count));
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
} @Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
callback.count(values[0]);
}
}.execute(0);
} public void stopCounter(){
isRunning = false;
} @Override
public void onCreate() {
super.onCreate();
Log.i(MainActivity.TAG, "on create!");
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(MainActivity.TAG, "on start command!");
return super.onStartCommand(intent, flags, startId);
} @Override
public boolean onUnbind(Intent intent) {
Log.i(MainActivity.TAG, "on unbind servcie!");
return super.onUnbind(intent);
} @Override
public void onDestroy() {
isRunning = false;
Log.i(MainActivity.TAG, "on destroy service");
super.onDestroy();
} @Override
public boolean stopService(Intent name) {
Log.i(MainActivity.TAG, "on stop service!");
return super.stopService(name);
} public class CounterBinder extends Binder{
public CountService getService(){
return CountService.this;
}
}
}
MainActivity类
package com.fxb.servicetest; import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; public class MainActivity extends Activity implements View.OnClickListener, ICounterCallback{ public static final String TAG = "ServiceTest"; private TextView tvShow;
private Button btnStartServie, btnStopService;
private Button btnBindService, btnUnbindService;
private Button btnStartCounter, btnStopCounter;
private CountService countService; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
} private void initView(){
tvShow = (TextView)findViewById(R.id.tvShow);
btnStartServie = (Button)findViewById(R.id.btnStartService);
btnStopService = (Button)findViewById(R.id.btnStopService);
btnBindService = (Button)findViewById(R.id.btnBindService);
btnUnbindService = (Button)findViewById(R.id.btnUnbindService);
btnStartCounter = (Button)findViewById(R.id.btnStartCount);
btnStopCounter = (Button)findViewById(R.id.btnStopCount); btnStartServie.setOnClickListener(this);
btnStopService.setOnClickListener(this);
btnBindService.setOnClickListener(this);
btnUnbindService.setOnClickListener(this);
btnStartCounter.setOnClickListener(this);
btnStopCounter.setOnClickListener(this);
} private void startCountService(){
Intent intent = new Intent(MainActivity.this, CountService.class);
startService(intent);
} private void stopCountService(){
Intent intent = new Intent(MainActivity.this, CountService.class);
stopService(intent);
} private void myBindService(){
Intent intent = new Intent(MainActivity.this, CountService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
} private void myUnbindService(){
unbindService(serviceConnection);
} @Override
public void onClick(View v) {
if(v == btnStartServie){
Log.i(TAG, "start click");
startCountService();
}
else if(v == btnStopService){
stopCountService();
}
else if(v == btnBindService){
myBindService();
}
else if(v == btnUnbindService){
myUnbindService();
}
else if(v == btnStartCounter){
if(countService != null){
countService.startCounter(0, this);
}
}
else if(v == btnStopCounter){
if(v == btnStopCounter){
countService.stopCounter();
}
}
} @Override
public void count(int val) {
tvShow.setText("count:"+val);
} private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(MainActivity.TAG, "service connected!");
CountService.CounterBinder binder = (CountService.CounterBinder)service;
countService = binder.getService();
} @Override
public void onServiceDisconnected(ComponentName name) {
Log.i(MainActivity.TAG, "service disconnected!");
}
}; }
在bindService之后,点击startCount后,tvShow每隔1s更新一次,点击stopCount后停止更新。
Service启动,绑定与交互的更多相关文章
- 深入分析Service启动、绑定过程
Service是Android中一个重要的组件,它没有用户界面,可以运行在后太做一些耗时操作.Service可以被其他组件启动,甚至当用户切换到其他应用时,它仍然可以在后台保存运行.Service 是 ...
- Android学习笔记(八)深入分析Service启动、绑定过程
Service是Android中一个重要的组件,它没有用户界面,可以运行在后太做一些耗时操作.Service可以被其他组件启动,甚至当用户切换到其他应用时,它仍然可以在后台保存运行.Service 是 ...
- Service启动过程分析
Service是一种计算型组件,用于在后台执行一系列的计算任务.由于工作在后台,因此用户是无法直接感知到它的存在.Service组件和Activity组件略有不同,Activity组件只有一种运行模式 ...
- 探索 OpenStack 之(11):cinder-api Service 启动过程分析 以及 WSGI / Paste deploy / Router 等介绍
OpenStack 中的每一个提供 REST API Service 的组件,比如 cinder-api,nova-api 等,其实是一个 WSGI App,其主要功能是接受客户端发来的 HTTP R ...
- Service的绑定过程
--摘自<Android进阶解密> 第一步:ContextImpl到AMS的调用过程 第二步:Service的绑定过程 1)几个与Service相关的对象类型 * ServiceRecor ...
- Android深入四大组件(七)Service的绑定过程
前言 我们可以通过调用Context的startService来启动Service,也可以通过Context的bindService来绑定Service,建议阅读此篇文章前请阅读Android深入四大 ...
- Service 启动Activity
1, 在BroadcastReceiver中启动Activity的问题 * * 如果在BroadcastReceiver的onReceive()方法中如下启动一个Activity * Inten ...
- Service(一):认识service、绑定Service
Activity是与用户打交道的,而Service是在后台运行的. 这个程序介绍了下如何启动和停止一个Service,以及在后台打印消息,我添加了一些注释. 在activity_main中将布局改为线 ...
- 【起航计划 034】2015 起航计划 Android APIDemo的魔鬼步伐 33 App->Service->Local Service Binding 绑定服务 ServiceConnection Binder
本例和下列Local Service Controller 的Activity代码都定义在LocalServiceActivities.Java 中,作为LocalServiceActivities ...
随机推荐
- 在插件中得到,调用 插件的id
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...
- 关于最新笔记本机型预装win8如何更换为win7的解决办法
关于最新笔记本机型预装win8如何更换为win7的解决办法 目前新出的很多机型出厂自带的都是win8系统,可能有些人用不习惯,想更换为win7系统,但是由于这些机型主板都采用UEFI这种接口(硬盘分区 ...
- codeforces 2B The least round way(DP+数学)
The least round way 题目链接:http://codeforces.com/contest/2/problem/B ——每天在线,欢迎留言谈论.PS.本题有什么想法.建议.疑问 欢迎 ...
- Spring从认识到细化了解
目录 Spring的介绍 基本运行环境搭建 IoC 介绍: 示例使用: 使用说明: 使用注意: Bean的实例化方式 Bean的作用范围的配置: 补充: DI: 属性注入: 补充: IoC的注解方式: ...
- Orchard详解--第九篇 拓展模块及引用的处理
在分析Orchard的模块加载之前,先简要说一下因为Orchard中的模块并不是都被根(启动)项目所引用的,所以当Orchard需要加载一个模块时首先需要保证该模块所依赖的其它程序集能够被找到,那么才 ...
- python os模块常用方法总结
该模块提供一种便捷的方式来操作系统 os.environ:返回系统环境变量 os.getenv(env):返回环境变量env的值 os.getpid():当前程序的进程 os.uname():返回一个 ...
- PHP的匿名函数和闭包
匿名函数 // Example1 $func = function( $param ) { echo $param; }; $func( 'some string' );//输出:some strin ...
- SQL中触发器的使用
创建触发器 是特殊的存储过程,自动执行,一般不要有返回值 类型: 1.后触发器 (AFTER,FOR)先执行对应语句,后执行触发器中的语句 2.前触发器 并没有真正的执行触发语句(insert,up ...
- 自动化测试基础篇--Selenium文件上传send_keys
摘自https://www.cnblogs.com/sanzangTst/p/8358165.html 文件上传是web页面上很常见的一个功能,自动化成功中操作起来却不是那么简单. 一般分两个场景:一 ...
- 老K漫谈区块链的共识(1)——免信任的共识机制
老k,柏链道捷CTO.清华阿尔山区块链研究中心高级工程师,超过17年的系统软件开发经验,在操作系统.编译器.虚拟机和符号执行方面都有实战经验.主持开发多个开眼项目,目前主要从事区块链底层系统开发工作. ...