이 클라이언트
SparseArray<CountDownLatch> lockArray = new SparseArray<>();
SparseArray<Bundle> msgDataArray = new SparseArray<>();
public Bundle sendAndWaitResponse(Message msg) throws
RemoteException, InterruptedException {
int msgId = msg.arg2;
Log.d("PlatformConnector", "Sending message to service, Type: "
+ msg.what + ", msgId: " + msg.arg2);
CountDownLatch latch = new CountDownLatch(1);
lockArray.put(msgId, latch);
platformMessenger.send(msg);
latch.await();
Bundle response = msgDataArray.get(msgId);
lockArray.delete(msgId);
msgDataArray.delete(msgId);
return response;
}
void storeResponseAndNotify(Message msg) {
int msgId = msg.arg2;
// Because the message itself is recycled after Handler returns,
// we should store only the data of message
msgDataArray.put(msgId, msg.getData());
lockArray.get(msgId).countDown();
}
private class ClientMessageHandler extends Handler {
@Override
public void handleMessage(Message msg) {
storeResponseAndNotify(msg);
}
}
이 코드 위의 활용의 예이다의 메시지 부분에 대한 코드입니다. RandomInt.getNextInt()
은 Random.nextInt()
으로 임의의 정수를 생성하는 내 사용자 정의 정적 메서드입니다. 다음과 같이
public JSONObject doSomething(JSONObject object) {
Message msg = Message.obtain(null, Constants.MESSAGE_SOMETHING, 0, RandomInt.getNextInt());
Bundle bundle = new Bundle();
bundle.putString(Constants.MESSAGE_DATA_SOMETHING, object.toString());
msg.setData(bundle);
try {
Bundle responseData = sendAndWaitResponse(msg);
return new JSONObject(responseData.getString(Constants.MESSAGE_DATA_RETURN));
} catch (RemoteException e) {
Log.e(TAG, "Failed to send message to platform");
e.printStackTrace();
} catch (InterruptedException e) {
Log.e(TAG, "Interrupted while waiting message from platform");
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
순서가
는
- 클라이언트는
Message
을 준비하고 설정, 자사의 arg2
어떤 임의의 정수 (이 정수 동기화를위한 메시지 ID 예정) 등.
- 클라이언트가 새로
CountDownLatch
을 준비하고 LockArray
에 넣습니다.
- 클라이언트가
sendAndWaitResponse()
과 함께 메시지를 보냅니다. Messenger
을 통해 서비스에 메시지를 보내고 latch.await()
을 호출합니다.
- 서비스 프로세스는 메시지를 수신하고 응답 메시지를 준비합니다. 이 회신 메시지의
arg2
은 수신 메시지와 같아야합니다.
- 서비스가 replyTo에
Messenger
을 통해 클라이언트에 응답 메시지를 보냅니다.
- 클라이언트 메시지 처리기는
storeResponseAndNotify
으로 메시지를 처리합니다.
- 클라이언트 스레드 차단이 완료되면 응답 데이터는 이미
msgDataArray
에 준비되어 있습니다.
CountDownLatch
은 스레드를 차단하고 차단 해제하는 간단한 스위치입니다. (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html)
SparseArray
은 HashMap
과 유사하지만 작은 세트의 경우 메모리 효율이 우수합니다. (http://developer.android.com/reference/android/util/SparseArray.html)
Messenger
의 스레드를 차단하지 않도록주의하십시오.Messenger
은 단일 스레드에서 실행되며 handleMessage()
에서 차단하면 다른 모든 메시지가 차단되어 디 잠금 문제가 발생합니다.
AIDL을 시도해보고 메소드를 정의하고 호출하면 모든 것이 동기화되고 프로토콜을 정의하는 데 더 이상 문제가 없습니다 http://developer.android.com/guide/components/aidl.html – eduyayo
aidl에 대한 "반대"느낌 그러나 지금 나는 그것을 들여다 볼 것입니다 –
감사합니다, 그것의 명확하게 훨씬 더 approch –