在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操作了

当我们的进度发生变化的时候我们发送一条广播,然后在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;
} }

总结:

  1. Activity调用bindService (Intent service, ServiceConnection conn, int flags)方法,得到Service对象的一个引用,这样Activity可以直接调用到Service中的方法,如果要主动通知Activity,我们可以利用回调方法

  2. Service向Activity发送消息,可以使用广播,当然Activity要注册相应的接收器。比如Service要向多个Activity发送同样的消息的话,用这种方法就更好

转载自:http://blog.csdn.net/xiaanming/article/details/9750689

Android Service与Activity之间通信的几种方式的更多相关文章

  1. Android Service与Activity之间通信

    主要分为: 通过Binder对象 通过broadcast(广播)的形式 Activity调用bindService (Intent service, ServiceConnection conn, i ...

  2. IPC进程之间通信的几种方式

    概念 进程间通信就是在不同进程之间传播或交换信息,那么不同进程之间存在着什么双方都可以访问的介质呢?进程的用户空间是互相独立的,一般而言是不能互相访问的,唯一的例外是 共享内存区 .但是,系统空间却是 ...

  3. Intent在Activity之间传值的几种方式

    发这篇博客主要讲一下Android中Intent中如何传值的几种方法: 1:基本数据类型,包含了Java八种基本数据类型和CharSequece文本2:八种数据类新对应数组和CharSequece文本 ...

  4. Vue组件之间通信的三种方式

    最近在看梁颠编著的<Vue.js实战>一书,感觉颇有收获,特此记录一些比价实用的技巧. 组件是MVVM框架的核心设计思想,将各功能点组件化更利于我们在项目中复用,这类似于我们服务端面向对象 ...

  5. Prism学习笔记-模块之间通信的几种方式

    在开发大型复杂系统时,我们通常会按功能将系统分成很多模块,这样模块就可以独立的并行开发.测试.部署.修改.使用Prism框架设计表现层时,我们也会遵循这个原则,按功能相关性将界面划分为多个模块,每个模 ...

  6. vue组件之间通信的8种方式

    对于vue来说,组件之间的消息传递是非常重要的,下面是我对组件之间消息传递的常用方式的总结. props和$emit(常用) $attrs和$listeners 中央事件总线(非父子组件间通信) v- ...

  7. 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 ...

  8. 总结vue中父向子,子向父以及兄弟之间通信的几种方式

    子向父方式1:通过props,如例子中子组件test1.vue向父组件App.vue传值 App.vue代码 <template> <div id="app"&g ...

  9. (Android数据传递)Service和Activity之间-- 借助BroadcastReceiver--的数据传递

    实现逻辑如下: 左侧为Activity中的执行逻辑,右侧为Service中的执行逻辑: /** * <功能描述> Service和Activity之间的数据交互:具体表现为: 1. 从Se ...

随机推荐

  1. stl+模拟 CCF2016 4 路径解析

    // stl+模拟 CCF2016 4 路径解析 // 一开始题意理解错了.... #include <iostream> #include <string> #include ...

  2. [Hive - LanguageManual] Hive Concurrency Model (待)

    Hive Concurrency Model Hive Concurrency Model Use Cases Turn Off Concurrency Debugging Configuration ...

  3. uva202:循环小数(循环节+抽屉原理)

    题意: 给出两个数n,m,0<=n,m<=3000,输出n/m的循环小数表示以及循环节长度. 思路: 设立一个r[]数组记录循环小数,u[]记录每次的count,用于标记,小数计算可用 r ...

  4. java 拷贝功能

    java 中的 拷贝分为浅拷贝 和 深拷贝 浅拷贝需要实现Cloneable接口,深拷贝需要实现Serializable接口. public class Square implements Clone ...

  5. 第二百七十天 how can I 坚持

    终于有点事干了,今天挺忙的. 今晚没玩游戏,看了个电影<解救吾先生>,还好. 傻. 12月28了,还三天就2016了,好快. 今天地铁人好多,早上又没起来,又迟到了,去霍营倒车,竟然还差点 ...

  6. ES6学习(1)——如何通过babel将ES6转化成ES5

    使用babel编译ES6 babel是一个工具,可以通过多个平台,让js文件从ES6转化成ES5,从而支持一些浏览器并未支持的语法. Insall babel $ sudo npm install b ...

  7. HTML5每日一练之details展开收缩标签的应用

    details标签的出现,为我们带来了更好的用户体验,不必为这种收缩展开的效果再编写JS来实现.注:目前仅Chrome支持此标签. details有一个新增加的子标签——summary,当鼠标点击su ...

  8. ubuntu 备份安装程序列表

    一般情况下,我们重装ubuntu的系统会做如下几个事情 1)修改默认的程序更新源 2)开始根据需求安装软件. 3)配置文件(如vim/tmux等) 对于步骤,只需要cp /etc//etc/apt/s ...

  9. Xcode 的正确打开方式——Debugging

    程序员日常开发中有大量时间都会花费在 debug 上,从事 iOS 开发不可避免地需要使用 Xcode.这篇博客就主要介绍了 Xcode 中几种能够大幅提升代码调试效率的方式. “If debuggi ...

  10. URAL 2045 Richness of words (回文子串,贪心)

    Richness of words 题目链接: http://acm.hust.edu.cn/vjudge/contest/126823#problem/J Description For each ...