Android Service与Activity之间通信的几种方式
在Android中,Activity主要负责前台页面的展示,Service主要负责需要长期运行的任务,所以在我们实际开发中,就会常常遇到Activity与Service之间的通信,我们一般在Activity中启动后台Service,通过Intent来启动,Intent中我们可以传递数据给Service,而当我们Service执行某些操作之后想要更新UI线程,我们应该怎么做呢?接下来我就介绍两种方式来实现Service与Activity之间的通信问题
- 通过Binder对象
当Activity通过调用bindService(Intent service, ServiceConnection conn,int flags),我们可以得到一个Service的一个对象实例,然后我们就可以访问Service中的方法,我们还是通过一个例子来理解一下吧,一个模拟下载的小例子,带大家理解一下通过Binder通信的方式
首先我们新建一个工程Communication,然后新建一个Service类
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; public class MsgService extends Service {
/**
* 进度条的最大值
*/
public static final int MAX_PROGRESS = 100;
/**
* 进度条的进度值
*/
private int progress = 0; /**
* 增加get()方法,供Activity调用
* @return 下载进度
*/
public int getProgress() {
return progress;
} /**
* 模拟下载任务,每秒钟更新一次
*/
public void startDownLoad(){
new Thread(new Runnable() { @Override
public void run() {
while(progress < MAX_PROGRESS){
progress += 5;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
}).start();
} /**
* 返回一个Binder对象
*/
@Override
public IBinder onBind(Intent intent) {
return new MsgBinder();
} public class MsgBinder extends Binder{
/**
* 获取当前Service的实例
* @return
*/
public MsgService getService(){
return MsgService.this;
}
} }
上面的代码比较简单,注释也比较详细,最基本的Service的应用了,相信你看得懂的,我们调用startDownLoad()方法来模拟下载任务,然后每秒更新一次进度,但这是在后台进行中,我们是看不到的,所以有时候我们需要他能在前台显示下载的进度问题,所以我们接下来就用到Activity了
Intent intent = new Intent("com.example.communication.MSG_ACTION");
bindService(intent, conn, Context.BIND_AUTO_CREATE);
通过上面的代码我们就在Activity绑定了一个Service,上面需要一个ServiceConnection对象,它是一个接口,我们这里使用了匿名内部类
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//返回一个MsgService对象
msgService = ((MsgService.MsgBinder)service).getService();
}
};
在onServiceConnected(ComponentName name, IBinder service) 回调方法中,返回了一个MsgService中的Binder对象,我们可以通过getService()方法来得到一个MsgService对象,然后可以调用MsgService中的一些方法,Activity的代码如下
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar; public class MainActivity extends Activity {
private MsgService msgService;
private int progress = 0;
private ProgressBar mProgressBar; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //绑定Service
Intent intent = new Intent("com.example.communication.MSG_ACTION");
bindService(intent, conn, Context.BIND_AUTO_CREATE); mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
//开始下载
msgService.startDownLoad();
//监听进度
listenProgress();
}
}); } /**
* 监听进度,每秒钟获取调用MsgService的getProgress()方法来获取进度,更新UI
*/
public void listenProgress(){
new Thread(new Runnable() { @Override
public void run() {
while(progress < MsgService.MAX_PROGRESS){
progress = msgService.getProgress();
mProgressBar.setProgress(progress);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
}).start();
} ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) { } @Override
public void onServiceConnected(ComponentName name, IBinder service) {
//返回一个MsgService对象
msgService = ((MsgService.MsgBinder)service).getService(); }
}; @Override
protected void onDestroy() {
unbindService(conn);
super.onDestroy();
} }
其实上面的代码我还是有点疑问,就是监听进度变化的那个方法我是直接在线程中更新UI的,不是说不能在其他线程更新UI操作吗,可能是ProgressBar比较特殊吧,我也没去研究它的源码,知道的朋友可以告诉我一声,谢谢!
上面的代码就完成了在Service更新UI的操作,可是你发现了没有,我们每次都要主动调用getProgress()来获取进度值,然后隔一秒在调用一次getProgress()方法,你会不会觉得很被动呢?可不可以有一种方法当Service中进度发生变化主动通知Activity,答案是肯定的,我们可以利用回调接口实现Service的主动通知,不理解回调方法的可以看看http://blog.csdn.net/xiaanming/article/details/8703708
新建一个回调接口
public interface OnProgressListener {
void onProgress(int progress);
}
MsgService的代码有一些小小的改变,为了方便大家看懂,我还是将所有代码贴出来
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; public class MsgService extends Service {
/**
* 进度条的最大值
*/
public static final int MAX_PROGRESS = 100;
/**
* 进度条的进度值
*/
private int progress = 0; /**
* 更新进度的回调接口
*/
private OnProgressListener onProgressListener; /**
* 注册回调接口的方法,供外部调用
* @param onProgressListener
*/
public void setOnProgressListener(OnProgressListener onProgressListener) {
this.onProgressListener = onProgressListener;
} /**
* 增加get()方法,供Activity调用
* @return 下载进度
*/
public int getProgress() {
return progress;
} /**
* 模拟下载任务,每秒钟更新一次
*/
public void startDownLoad(){
new Thread(new Runnable() { @Override
public void run() {
while(progress < MAX_PROGRESS){
progress += 5; //进度发生变化通知调用方
if(onProgressListener != null){
onProgressListener.onProgress(progress);
} try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
}).start();
} /**
* 返回一个Binder对象
*/
@Override
public IBinder onBind(Intent intent) {
return new MsgBinder();
} public class MsgBinder extends Binder{
/**
* 获取当前Service的实例
* @return
*/
public MsgService getService(){
return MsgService.this;
}
} }
Activity中的代码如下
package com.example.communication; 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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar; public class MainActivity extends Activity {
private MsgService msgService;
private ProgressBar mProgressBar; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //绑定Service
Intent intent = new Intent("com.example.communication.MSG_ACTION");
bindService(intent, conn, Context.BIND_AUTO_CREATE); mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
//开始下载
msgService.startDownLoad();
}
}); } ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) { } @Override
public void onServiceConnected(ComponentName name, IBinder service) {
//返回一个MsgService对象
msgService = ((MsgService.MsgBinder)service).getService(); //注册回调接口来接收下载进度的变化
msgService.setOnProgressListener(new OnProgressListener() { @Override
public void onProgress(int progress) {
mProgressBar.setProgress(progress); }
}); }
}; @Override
protected void onDestroy() {
unbindService(conn);
super.onDestroy();
} }
用回调接口是不是更加的方便呢,当进度发生变化的时候Service主动通知Activity,Activity就可以更新UI操作了
- 通过broadcast(广播)的形式
当我们的进度发生变化的时候我们发送一条广播,然后在Activity的注册广播接收器,接收到广播之后更新ProgressBar,代码如下
package com.example.communication; import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar; public class MainActivity extends Activity {
private ProgressBar mProgressBar;
private Intent mIntent;
private MsgReceiver msgReceiver; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //动态注册广播接收器
msgReceiver = new MsgReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.communication.RECEIVER");
registerReceiver(msgReceiver, intentFilter); mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
//启动服务
mIntent = new Intent("com.example.communication.MSG_ACTION");
startService(mIntent);
}
}); } @Override
protected void onDestroy() {
//停止服务
stopService(mIntent);
//注销广播
unregisterReceiver(msgReceiver);
super.onDestroy();
} /**
* 广播接收器
* @author len
*
*/
public class MsgReceiver extends BroadcastReceiver{ @Override
public void onReceive(Context context, Intent intent) {
//拿到进度,更新UI
int progress = intent.getIntExtra("progress", 0);
mProgressBar.setProgress(progress);
} } }
package com.example.communication; import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MsgService extends Service {
/**
* 进度条的最大值
*/
public static final int MAX_PROGRESS = 100;
/**
* 进度条的进度值
*/
private int progress = 0; private Intent intent = new Intent("com.example.communication.RECEIVER"); /**
* 模拟下载任务,每秒钟更新一次
*/
public void startDownLoad(){
new Thread(new Runnable() { @Override
public void run() {
while(progress < MAX_PROGRESS){
progress += 5; //发送Action为com.example.communication.RECEIVER的广播
intent.putExtra("progress", progress);
sendBroadcast(intent); try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
}).start();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
startDownLoad();
return super.onStartCommand(intent, flags, startId);
} @Override
public IBinder onBind(Intent intent) {
return null;
} }
总结:
- Activity调用bindService (Intent service, ServiceConnection conn, int flags)方法,得到Service对象的一个引用,这样Activity可以直接调用到Service中的方法,如果要主动通知Activity,我们可以利用回调方法
- Service向Activity发送消息,可以使用广播,当然Activity要注册相应的接收器。比如Service要向多个Activity发送同样的消息的话,用这种方法就更好
转载自:http://blog.csdn.net/xiaanming/article/details/9750689
Android Service与Activity之间通信的几种方式的更多相关文章
- Android Service与Activity之间通信
主要分为: 通过Binder对象 通过broadcast(广播)的形式 Activity调用bindService (Intent service, ServiceConnection conn, i ...
- IPC进程之间通信的几种方式
概念 进程间通信就是在不同进程之间传播或交换信息,那么不同进程之间存在着什么双方都可以访问的介质呢?进程的用户空间是互相独立的,一般而言是不能互相访问的,唯一的例外是 共享内存区 .但是,系统空间却是 ...
- Intent在Activity之间传值的几种方式
发这篇博客主要讲一下Android中Intent中如何传值的几种方法: 1:基本数据类型,包含了Java八种基本数据类型和CharSequece文本2:八种数据类新对应数组和CharSequece文本 ...
- Vue组件之间通信的三种方式
最近在看梁颠编著的<Vue.js实战>一书,感觉颇有收获,特此记录一些比价实用的技巧. 组件是MVVM框架的核心设计思想,将各功能点组件化更利于我们在项目中复用,这类似于我们服务端面向对象 ...
- Prism学习笔记-模块之间通信的几种方式
在开发大型复杂系统时,我们通常会按功能将系统分成很多模块,这样模块就可以独立的并行开发.测试.部署.修改.使用Prism框架设计表现层时,我们也会遵循这个原则,按功能相关性将界面划分为多个模块,每个模 ...
- vue组件之间通信的8种方式
对于vue来说,组件之间的消息传递是非常重要的,下面是我对组件之间消息传递的常用方式的总结. props和$emit(常用) $attrs和$listeners 中央事件总线(非父子组件间通信) v- ...
- Liferay7 BPM门户开发之33: Portlet之间通信的3种方式(session、IPC Render Parameter、IPC Event、Cookies)
文章介绍了5种方式,4种是比较常用的: Portlet session IPC Public Render Parameters IPC Event Cookies 参考地址: https://web ...
- 总结vue中父向子,子向父以及兄弟之间通信的几种方式
子向父方式1:通过props,如例子中子组件test1.vue向父组件App.vue传值 App.vue代码 <template> <div id="app"&g ...
- (Android数据传递)Service和Activity之间-- 借助BroadcastReceiver--的数据传递
实现逻辑如下: 左侧为Activity中的执行逻辑,右侧为Service中的执行逻辑: /** * <功能描述> Service和Activity之间的数据交互:具体表现为: 1. 从Se ...
随机推荐
- AtCoder Grand Contest 001
B - Mysterious Light 题意:从一个正三角形边上一点出发,遇到边和已走过的边则反弹,问最终路径长度 思路:GCD 数据爆long long #pragma comment(linke ...
- mybatis系列-10-一对一查询
10.1 需求 查询订单信息,关联查询创建订单的用户信息 10.2 resultType 10.2.1 sql语句 确定查询的主表:订单表 确定查询的关联表:用户表 关联查询 ...
- The Datastore
[中央数据库模式难扩展]绝大多数的Web应用在处理一个为了以后的请求作检索用的请求时,需要存储信息.<1.Most useful web applications need to store i ...
- hadoop2.7【单节点】单机、伪分布、分布式安装指导
问题导读 1.从本文部署实际部署,总结本地模式.伪分布.分布式的区别是什么?2.单机是否是伪分布?3.本地模式是否可以运行mapreduce? 来源:about云 http://www.aboutyu ...
- LeetCode 232 Implement Queue using Stacks
Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of ...
- 修改MongoDb的 DB 和 Log 存储路径 (Windows)-摘自网络
Create a file called mongod.cfg in MongoDB folder if you dont have it. In my case: C:\Users\ivanbtru ...
- 第二百六十九天 how can I 坚持
什么是明事理,搞不懂啊,好烦. 有点像我妈. 为什么突然就想买房了呢,为什么?年龄到了,考虑的东西就不一样了. 哎,不要想太多,睡觉.
- 关于CoreData和SQLite多线程访问时的线程安全问题
数据库读取操作一般都是多线程访问的.在对数据进行读取时,我们要保证其当前状态不能被修改,即读取时加锁,否则就会出现数据错误混乱.IOS中常用的两种数据持久化存储方式:CoreData和SQLite,两 ...
- [转]directsound抓取麦克风PCM数据封装类
网上有很多方法从麦克风读取PCM数据,不想一一举例.只是在这里发布一个我自己写的directsound的麦克风PCM数据采集类,通过它,可以很方便的利用directsound技术把麦克风的数据采集到, ...
- Codeforces Round #353 (Div. 2) C. Money Transfers (思维题)
题目链接:http://codeforces.com/contest/675/problem/C 给你n个bank,1~n形成一个环,每个bank有一个值,但是保证所有值的和为0.有一个操作是每个相邻 ...