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 ...
随机推荐
- Python函数式编程(一):高级函数
首先有一个高级函数的知识. 一个函数可以接收另一个函数作为参数,这种函数就称之为高阶函数. def add(x, y, f): return f(x) + f(y) 当我们调用add(-, , abs ...
- 官网下载的Struts 2解压后缺少xwork-core.jar文件
为Eclipse配置Struts-2.5.10所需最少jar文件: 缺少的文件已被合并在struts2-core-2.5.10.jar文件中.我下的是最新版的,如果你下的找不到就是这个原因啦.
- Java的优先级任务队列的实践
队列的基本理解 在说队列之前说两个名词:Task是任务,TaskExecutor是任务执行器 而我们今天要说的队列就完全符合某机构这个情况,队列在有Task进来的时候TaskExecutor就立刻开始 ...
- git 入门教程之本地和远程仓库的本质
本地仓库和远程仓库在本质上没有太大区别,只不过一个是本地电脑,一个是远程电脑. 远程仓库不一定非得是 github 那种专门的"中央服务器",甚至局域网的另外一台电脑也可以充当&q ...
- 详解JS设计模式
原文链接:www.cnblogs.com 一:理解工厂模式 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式. 简单的工厂模式可以理解为解决 ...
- C#-基本语法(三)
关键词 关键字,是一些被C#规定了用途的重要单词 在Visual Studio的开发环境中,关键字被标识为蓝色 例如: using:导入命名空间 class:声明类 static:静态 void:无返 ...
- web前端(9)—— CSS属性
属性 终于到css属性,前面就零零散散的用了什么color,font-size之类,本篇博文就专项的介绍它了 字体属性 font-family 此属性是设置字体样式的,比如微软雅黑,方正书体,华文宋体 ...
- 洗礼灵魂,修炼python(89)-- 知识拾遗篇 —— 进程
进程 1.含义:计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位.说白了就是一个程序的执行实例. 执行一个程序就是一个进程,比如你打开浏览器看到我的博客,浏览器本身是一 ...
- python连接sqlserver数据库
1.准备工作 python3.6连接sqlserver数据库需要引入pymssql模块 pymssql官方:https://pypi.org/project/pymssql/ 没有安装的话需要: pi ...
- SQL Server 锁实验(UPDATE加锁探究)
update语句: 本例中由于看到的是update执行完的锁情况,因此无法看到IU锁,但其实针对要修改的数据页和索引页会先加IU锁,记录和键先加U锁,然后再转化为IX和X锁. 如果想要看到IU锁和U锁 ...