@mSolo
2015-04-23T17:51:08.000000Z
字数 3233
阅读 1616
Android
Parcel
图示 AIDL 远程调用
实战例子请参考
mMessenger.send(Message msg)
)。
public void onServiceConnected(ComponentName name, IBinder service) {
mMessenger = new Messenger(service);
// ......
}
public class WorkerThreadService extends Service {
WorkerThread mWorkerThread;
Messenger mWorkerMessenger;
@Override
public void onCreate() {
super.onCreate();
mWorkerThread.start();
}
/**
* Worker thread has prepared a looper and handler.
**/
private void onWorkerPrepared() {
mWorkerMessenger = new Messenger(mWorkerThread.mWorkerHandler);
}
public IBinder onBind(Intent intent) {
return mWorkerMessenger.getBinder();
}
@Override
public void onDestroy() {
super.onDestroy();
mWorkerThread.quit();
}
private class WorkerThread extends Thread {
Handler mWorkerHandler;
@Override
public void run() {
Looper.prepare();
mWorkerHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Implement message processing
}
};
onWorkerPrepared();
Looper.loop();
}
public void quit() {
mWorkerHandler.getLooper().quit();
}
}
}
public void onSendClick(View v) {
if (mBound) {
try {
Message msg = Message.obtain(null, 1, 0, 0);
msg.replyTo = new Messenger(new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "Message sent back - msg.what = " + msg.what);
}
});
mRemoteService.send(msg);
} catch (RemoteException e) {
Log.e(TAG, e.getMessage());
}
}
}
// remote service
public void run() {
Looper.prepare();
mWorkerHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
try {
msg.replyTo.send(Message.obtain(null, msg.what, 0, 0));
} catch (RemoteException e) {
Log.e(TAG, e.getMessage());
}
break;
}
}
};
onWorkerPrepared();
Looper.loop();
}
}