Android跨进程通信之非AIDL(二)

目录

Android跨进程通信之小例子(一)
Android跨进程通信之非AIDL(二)
Android跨进程通信之Proxy与Stub(三)
Android跨进程通信之AIDL(四)

从最常用的例子谈起

这篇文章围绕的核心主题就是IBinder,或许你早就在ServiceonBind方法中见过。该方法就是返回一个IBinder对象。一般我们的做法是这样的:

service代码

public class MusicService extends Service{

    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }
    
        public class MyBinder extends Binder {
        public MyService getMyService() {
            return MusicService.this;
        }
    }
    
        public void play(){
            Log.i("TAG", "play");
        }
        public void pause(){
            Log.i("TAG", "pause");
        }
}

获取service控制权代码

public class MainActivity extends Activity {
    Intent              service;
    ServiceConnection   conn;
    MyService           myService;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        service = new Intent(MainActivity.this, MusicService.class);
        conn = new ServiceConnection() {
            
            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
            
            @Override
            public void onServiceConnected(ComponentName name, IBinder binder) {
                myService = ((MyBinder) binder).getMyService();
            }
        };
        bindService(service, conn, BIND_AUTO_CREATE);
    }
}

我们通过ServiceConnection去绑定一个Service然后绑定成功后返回一个IBinder对象,其中IBinder就充当与一个中介。是的,中介这个词没有用错。再通过MyBinder提供的getMyService来获取服务进而控制Service

一个真相引发的血案

其实上面的例子跟文章要说的内容没什么卵关系,只是让你更好的回忆一下IBinder接口。这篇文章主要讲一下onTransact方法。

IBinder跨进程通信图

ibinder

下面就大概简单说明一下。

  • 首先myActivity通过调用bindService去绑定一个远程的服务(myService),绑定成功后返回一个IBinder对象。这时候双方就算是建立了连接了。
  • 建立连接之后,双方就可以通过持有的IBinder进行通信。myActivity使用IBindertransact方法去给底层的Binder Driver(Linux层)发送消息间接调用底层的IBinderexecTransact方法。
  • execTransact导致的结果就是调用onTransact方法。那么这时候事件的处理就可以在该环节进行了。

其实就是一个transact->onTransact的一个过程

事实上我们看到transactonTransact的参数是一模一样的。

protected boolean onTransact(int code, Parcel data, Parcel reply,int flags);
public final boolean transact(int code, Parcel data, Parcel reply,int flags);

transact的参数

  • code : 这是一个识别码,类似于Handler体系里面的Message的what属性。根据不同的code产生不同的响应。
  • data : 调用transact的对象传送过去的参数。
  • reply : 调用onTransact的对象返回的参数。
  • flags : Java里面默认的native方法都是阻塞的,当不需要阻塞的时候设置为IBinder.FLAG_ONEWAY,否则设置为0

一个小例子

环境:

  • 一个叫做RemoteService的APP
  • 一个叫做RemoteServiceDemo的APP
  • RemoteServiceDemo中的Activity去控制RemoteService中的Service。

RemoteService

Service声明

<service android:name="com.example.remoteservice.MusicService" >
            <intent-filter>
                <action android:name="top.august1996.musicservice" />
            </intent-filter>
        </service>

别忘了加入<action android:name="top.august1996.musicservice" />,否则会抛出安全异常。

Service代码

public class MusicService extends Service {
    
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }
    
    public class MyBinder extends Binder {
        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
            switch (code) {
                case 0:
                    Log.i("TAG", data.readString());
                    play();
                    reply.writeString("Service play Music at " + sdf.format(new Date()));
                    break;
                case 1:
                    Log.i("TAG", data.readString());
                    pause();
                    reply.writeString("Service pause Music at " + sdf.format(new Date()));
                    
                    break;
                default:
                    break;
            }
            
            return true;
        }
    }
    
    public void play() {
        Log.d("TAG", "play");
    }
    
    public void pause() {
        Log.d("TAG", "pause");
    }
}

服务的代码很简单,也没什么需要说的。

RemoteServiceDemo

布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="bind"
        android:text="bind service" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="unbind"
        android:text="unbind service" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="play"
        android:text="play" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="pause"
        android:text="pause" />

</LinearLayout>

代码

public class MainActivity extends Activity {
    
    private ServiceConnection   mServiceConnection  = new ServiceConnection() {
                                                        @Override
                                                        public void onServiceDisconnected(ComponentName name) {
                                                            
                                                        }
                                                        @Override
                                                        public void onServiceConnected(ComponentName name,
                                                                IBinder service) {
                                                            mBinder = service;
                                                        }
                                                    };
    
    private IBinder             mBinder             = null;
    private Parcel              data                = Parcel.obtain();
    private Parcel              reply               = Parcel.obtain();
    private SimpleDateFormat    sdf                 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    public void bind(View v) {
        if (isBinded()) {
            return;
        }
        /**
         * 通过ComponentName去定位意图
         * 第一个参数是应用包名
         * 第二个参数是Service或者Activity所在的包名+类名
         */
        bindService(
                new Intent().setComponent(
                        new ComponentName("com.example.remoteservice", "com.example.remoteservice.MusicService")),
                mServiceConnection, Context.BIND_AUTO_CREATE);
    }
    
    public void unbind(View v) {
        if (!isBinded()) {
            return;
        }
        unbindService(mServiceConnection);
        mBinder = null;
    }
    
    public void play(View v) {
        if (!isBinded()) {
            return;
        }
        try {
            data.writeString("Activity request to play music at " + sdf.format(new Date()));
            mBinder.transact(0, data, reply, 0);
            Log.i("TAG", reply.readString());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    
    public void pause(View v) {
        try {
            data.writeString("Activity request to pause music at " + sdf.format(new Date()));
            mBinder.transact(1, data, reply, 0);
            Log.i("TAG", reply.readString());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    
    private boolean isBinded() {
        return mBinder != null;
    }
    
}

因为我们需要使用reply,所以我们使用阻塞的transact,否则我们调用了transact,但是那边还未给reply写入字符串,最终导致NullPointException。

项目地址

Github地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容