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类

package com.example.communication;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() {@Overridepublic void run() {while(progress < MAX_PROGRESS){progress += 5;try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();}/** * 返回一个Binder对象 */@Overridepublic 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() {@Overridepublic void onServiceDisconnected(ComponentName name) {}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {//返回一个MsgService对象msgService = ((MsgService.MsgBinder)service).getService();}};

在onServiceConnected(ComponentName name, IBinder service) 回调方法中,返回了一个MsgService中的Binder对象,我们可以通过getService()方法来得到一个MsgService对象,然后可以调用MsgService中的一些方法,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 int progress = 0;private ProgressBar mProgressBar;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//绑定ServiceIntent 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() {@Overridepublic void onClick(View v) {//开始下载msgService.startDownLoad();//监听进度listenProgress();}});}/** * 监听进度,每秒钟获取调用MsgService的getProgress()方法来获取进度,更新UI */public void listenProgress(){new Thread(new Runnable() {@Overridepublic 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() {@Overridepublic void onServiceDisconnected(ComponentName name) {}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {//返回一个MsgService对象msgService = ((MsgService.MsgBinder)service).getService();}};@Overrideprotected void onDestroy() {unbindService(conn);super.onDestroy();}}其实上面的代码我还是有点疑问,就是监听进度变化的那个方法我是直接在线程中更新UI的,不是说不能在其他线程更新UI操作吗,可能是ProgressBar比较特殊吧,我也没去研究它的源码,知道的朋友可以告诉我一声,,谢谢!不能接受失败,也意味太想去成功了,从心理学上解释,

Android Service与Activity之间通信的几种方式

相关文章:

你感兴趣的文章:

标签云: