Android进程间的通信:Mesenger、aidl

android进程间的通信方式:

一、Messenger

客户端:

public class MessengerClient extends Activity{
    private Messenger mService;
    //private Messenger m
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent();
        intent.setAction("com.ryg.chapter.lanch");
        intent.setPackage(getPackageName());
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = new Messenger(service);
            Message msg = Message.obtain(null,MyConstance.MSG_CLIENT);
            Bundle data = new Bundle();
            data.putString("msg_for_service","我是来自客户端的消息");
            msg.setData(data);

            try {
                mService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onDestroy() {
        unbindService(mConnection);
        super.onDestroy();
    }
}

服务端:

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import com.ryg.chapter_2.utils.MyConstants;

public class MessengerService extends Service {

    private static final String TAG = "MessengerService";

    private static class MessengerHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MyConstants.MSG_FROM_CLIENT:
                Log.i(TAG, "receive msg from Client:" + msg.getData().getString("msg"));
                Messenger client = msg.replyTo;
                Message relpyMessage = Message.obtain(null, MyConstants.MSG_FROM_SERVICE);
                Bundle bundle = new Bundle();
                bundle.putString("reply", "嗯,你的消息我已经收到,稍后会回复你。-----------");
                relpyMessage.setData(bundle);
                try {
                    client.send(relpyMessage);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            default:
                super.handleMessage(msg);
            }
        }
    }

    private final Messenger mMessenger = new Messenger(new MessengerHandler());

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

}



3、AndroidManifest.xml配置:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ryg.chapter_2">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".IpcMessage.MessengerClient">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>



        <service android:name=".IpcMessage.MessengerService"
            android:process=":jiangshuai">
            <intent-filter>
                <action android:name="com.ryg.chapter.lanch"/>
            </intent-filter>
        </service>


    </application>

</manifest>

用aidl实现线程之间的通信:

项目结构:

1、IBookManager.aidl文件

package com.ryg.ipcaidl;
import com.ryg.ipcaidl.Book;
interface IBookManager {
    List<Book> getBookList();
    void addBook(in Book book);
}

2、Book.aidl文件:

package com.ryg.ipcaidl;

parcelable Book;

3、Book.java文件:

import android.os.Parcel;
import android.os.Parcelable;

public class Book implements Parcelable {

    public int bookId;
    public String bookName;

    public Book() {

    }

    public Book(int bookId, String bookName) {
        this.bookId = bookId;
        this.bookName = bookName;
    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(bookId);
        out.writeString(bookName);
    }

    public static final Creator<Book> CREATOR = new Creator<Book>() {
        public Book createFromParcel(Parcel in) {
            return new Book(in);
        }

        public Book[] newArray(int size) {
            return new Book[size];
        }
    };

    private Book(Parcel in) {
        bookId = in.readInt();
        bookName = in.readString();
    }

    @Override
    public String toString() {
        return String.format("[bookId:%s, bookName:%s]", bookId, bookName);
    }

}

4、客户端实现类:

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.util.List;

public class BookClientActivity extends AppCompatActivity {
    private static final String TAG = "BookClientActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent();
        intent.setAction("com.ryg.ipcaidl.launch");
        intent.setPackage(getPackageName());
        bindService(intent,mConnection, Context.BIND_AUTO_CREATE);

    }
    //获得与服务端链接
    private ServiceConnection mConnection =
            new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    //调用aidl中stub的asinterface
                    //将服务端的binder对象转化为客户端所需要的aidl接口对象
                    IBookManager bookManager = IBookManager.Stub.asInterface(service);
                    try {
                        List<Book> list = bookManager.getBookList();
                        Log.e(TAG, "获取所有书的type:" + list.getClass().getCanonicalName());
                        Log.e(TAG,"获取所有书的list :"+list.toString());
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }
            };

    @Override
    protected void onDestroy() {
        unbindService(mConnection);
        super.onDestroy();
    }
}

5、服务端实现类:

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by apple on 17/5/7.
 */

public class BookManagerService extends Service{
    private CopyOnWriteArrayList<Book> mBookList =
            new CopyOnWriteArrayList<Book>();
    //创建一个binder对象
    private Binder mBinder = new IBookManager.Stub(){//调用服务端aidl的stub中方法

        @Override
        public List<Book> getBookList() throws RemoteException {
            return mBookList;
        }

        @Override
        public void addBook(Book book) throws RemoteException {
            mBookList.add(book);
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        mBookList.add(new Book(1,"messenger study"));
        mBookList.add(new Book(2,"aidl study"));
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;//返回这个binder对象
    }
}

6、service在manifest中注册:

        <service
            android:name=".BookManagerService"
            android:process=":jiangshuai">
            <intent-filter>
                <action android:name="com.ryg.ipcaidl.launch"/>
            </intent-filter>

        </service>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值