一段代码探究绑定服务流程

来源:互联网 发布:linux grep java 编辑:程序博客网 时间:2024/06/06 09:39

安卓绑定服务的思路是:应用程序如果想访问一个服务的方法,它不能直接获取服务的引用,而要通过一个中间人(下面代码里面就是MyBinder对象)进行通信。

package com.example.mytest;import com.example.mytest.Singer.MyBinder;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.View;public class MainActivity extends Activity {private MyBinder myBinder;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}/** * 绑定服务 *  * @param v */public void bind(View v) {Intent intent = new Intent(this, Singer.class);// 第一步:发出绑定服务请求bindService(intent, new MyConn(), BIND_AUTO_CREATE);}private class MyConn implements ServiceConnection {// 服务成功被绑定时调用@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stub// 第四部 :获得返回的IBinder对象,并且利用这个对象调用服务的功能myBinder = (MyBinder) service;}@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stub}}/** * 取消绑定服务 *  * @param v */public void unbind(View v) {}/** * 调用服务进行唱歌 *  * @param v */public void sing(View v) {// 利用中间者调用服务的方法myBinder.singASong();}}
package com.example.mytest;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;public class Singer extends Service {// 第二步 :调用onBind方法@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn new MyBinder();}/** * 中间人 *  * @author USER *  */public class MyBinder extends Binder {// 第三步 :创建MyBinder对象(中间者),并且暴露服务的方法public void singASong() {sing();}}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();System.out.println("服务被创建");}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();System.out.println("服务被取消");}public void sing() {               // 这个方法通过中间者暴露给用户了               System.out.println("开始唱歌了..");}}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    tools:context=".MainActivity" >    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="bind"        android:text="绑定服务" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="unbind"        android:text="取消绑定服务" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="sing"        android:text="唱歌" /></LinearLayout>


0 0