Service与Activity进行通信

来源:互联网 发布:为什么衍生网络主播 编辑:程序博客网 时间:2024/05/16 08:11

Service与Activity进行通信

一、思路

在Android中,Activity的类可以看成是“可见”的逻辑处理类,拥有用户界面与用户进行互动操作,但如果这个Acitvity失去了“焦点”,则它的逻辑处理随即停止,那样如果我们需要进行一些后台类的操作,既与用户当前操作的焦点无关,可以在背后一直运行,为相应的应用程序提供服务,Android中这种逻辑处理类称为Service。一般继承自Service类。

Service类是没有用户界面,但只作为一种后台逻辑处理,为表层Activity提供相应的服务操作,所以Service类处理后的数据要交回给Activity,Activity也要获得Service的服务逻辑,即两者之间要进行交互。而这个交互过程如下:

1、Service类中要创建一个内部类。继承自Binder,因为在Service这个父类中,Onbind方法返回一个IBinder接口的返回值,而Binder是IBinder接口的一个实现。

2、继承自IBinder类的内部类,只需要实现一个返回Service自身对象的功能的方法即可。

3、在Activity中通过bindService方法与对应的Service进行绑定,一旦执行这个方法,则系统自动调用Service类中的onbind方法,这里就会返回一个IBinder类返回值,也就是Service创建的内部类对象。

4、在Activity中创建一个ServiceConnection对象,作为参数传入上面的bindService方法中。这里自动调用Onbind方法就会将Service返回的IBinder类的返回值传入到ServiceConnection中的onServiceConnected方法的参数中。这个方法只需要实现IBinder返回值中的返回Service自身的方法赋值到Activity的一个参数即可。

5、要在AndroidManifest.xml文件中注册Service。

6、注意Service的真正启动其实是在调用Service的线程结束后,例如在Activity中的OnCreate方法中执行startService或者bindService等操作,Service也只在OnCreate方法完成后才真正开始执行。

二、实例

1、Service类

public class ServiceTest extends Service {private MyBinder binder = new MyBinder();@Overridepublic IBinder onBind(Intent intent) {Log.i("demo", "onbind");return binder;}class MyBinder extends Binder{public ServiceTest getService(){return ServiceTest.this;}}}


2、Activity类

public class BlogTestActivity extends Activity {/** Called when the activity is first created. */private ServiceTest Myservice = null;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Intent bindService = new Intent(BlogTestActivity.this,ServiceTest.class);startService(bindService);this.bindService(bindService, connection, Context.BIND_AUTO_CREATE);}ServiceConnection connection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {Myservice = null;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {Log.i("demo", "连接了Server!");Myservice = ((ServiceTest.MyBinder) service).getService();}};}