下面列出了android.os.Messenger#send ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void a(Messenger messenger) {
try {
if (bu.q() && messenger != null) {
bu.a("0");
Message obtain = Message.obtain();
obtain.what = 100;
messenger.send(obtain);
}
if (bu.a()) {
this.z.a();
}
if (bu.d() && !this.x) {
this.x = true;
this.d.sendEmptyMessage(4);
}
if (bu.f() && !this.y) {
this.y = true;
this.d.sendEmptyMessage(5);
}
} catch (Throwable th) {
}
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constant.MSG_FROM_CLIENT:
try {
// 缓存数据
cacheStepData(StepService.this,StepDcretor.CURRENT_STEP + "");
// 更新通知栏
updateNotification(msg.getData());
// 回复消息给Client
Messenger messenger = msg.replyTo;
Message replyMsg = Message.obtain(null, Constant.MSG_FROM_SERVER);
Bundle bundle = new Bundle();
bundle.putInt(STEP_KEY, StepDcretor.CURRENT_STEP);
replyMsg.setData(bundle);
messenger.send(replyMsg);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
@Override
protected void onHandleIntent(Intent intent) {
artist = intent.getStringExtra("artist");
track = intent.getStringExtra("track");
songID = intent.getLongExtra("id", 0);
messenger = (Messenger) intent.getExtras().get("messenger");
File path = new File(Environment.getExternalStorageDirectory() + File.separator + "Lyrically/");
notFound = new File(path, "No Lyrics Found.txt");
lyricsFile = new File(path, songID + ".txt");
if (!lyricsFile.exists())
getLyrics();
else
try { // if the text file with the current song ID already exists, skip fetching the lyrics
messenger.send(new Message());
} catch (RemoteException e) {
e.printStackTrace();
}
}
/**
* Deconstructs the given interaction proto and attempts to run it in the current process.
*
* <p>1. deconstruct InteractionRequestProto into an interaction Espresso can understand 2.
* attempt to run the desired interaction 3. send a response to the caller whether there is
* nothing to execute on (1 is false) or the interaction failed (e.g due to an assertion)
*
* @param caller The caller that initiated this request
* @param data A Bundle including InteractionRequestProto repressing the Espresso interaction
*/
private void handleEspressoRequest(Messenger caller, Bundle data) {
UUID uuid = (UUID) data.getSerializable(BUNDLE_KEY_UUID);
logDebugWithProcess(
TAG, String.format(Locale.ROOT, "handleEspressoRequest for id: %s", uuid));
Message msg = getEspressoMessage(MSG_HANDLE_ESPRESSO_RESPONSE);
Bundle resultData = msg.getData();
// copy over the request UUID
resultData.putSerializable(BUNDLE_KEY_UUID, uuid);
// attempt to execute the request and save the result
isRemoteProcess = true;
InteractionResponse interactionResponse = executeRequest(data);
resultData.putByteArray(BUNDLE_KEY_PROTO, interactionResponse.toProto().toByteArray());
msg.setData(resultData);
try {
caller.send(msg);
} catch (RemoteException e) {
// In this case the remote process was terminated or crashed before we could
// even do anything with it; there is nothing we can do other than unregister the
// Espresso caller instance.
Log.w(TAG, "The remote caller process is terminated unexpectedly", e);
instrumentationConnection.unregisterClient(TYPE, caller);
}
}
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service
mService = new Messenger(service);
boundToTheService = true;
try {
Message msg = Message.obtain(null, InstrumentationService.ConnectToService);
mService.send(msg);
} catch (RemoteException e) {
// service has crashed, nothing to do...
SubstrateMain.log("<!> Thats a very bad news: service has crashed", e);
}
/**
* Send previously stored events
*/
this.sendEventsInCache();
}
/**
* Send request to remote Espresso instances (if any).
*
* @param what User-defined message code so that the recipient can identify what this message is
* about.
* @param data A Bundle of arbitrary data associated with this message
*/
private void sendMsgToRemoteEspressos(int what, Bundle data) {
logDebugWithProcess(TAG, "sendMsgToRemoteEspressos called");
Message msg = getEspressoMessage(what);
msg.setData(data);
Set<Messenger> remoteClients = instrumentationConnection.getClientsForType(TYPE);
for (Messenger remoteEspresso : remoteClients) {
if (messengerHandler.equals(remoteEspresso)) {
// avoid sending message to self
continue;
}
try {
remoteEspresso.send(msg);
} catch (RemoteException e) {
// In this case the remote process was terminated or crashed before we could
// even do anything with it; there is nothing we can do other than unregister the
// Espresso instance.
Log.w(TAG, "The remote process is terminated unexpectedly", e);
instrumentationConnection.unregisterClient(TYPE, remoteEspresso);
}
}
}
@Override
public void handleMessage(@NonNull android.os.Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
// Class not found when unmarshalling: com.chiclaim.ipc.bean.Message
bundle.setClassLoader(Message.class.getClassLoader());
Message data = bundle.getParcelable("message");
Toast.makeText(getApplicationContext(), data.getContent(), Toast.LENGTH_SHORT).show();
Messenger replyTo = msg.replyTo;
Message raw = new Message();
raw.setContent("I receive your message: " + data.getContent());
android.os.Message message = new android.os.Message();
Bundle replyBundle = new Bundle();
replyBundle.putParcelable("message", raw);
message.setData(replyBundle);
try {
replyTo.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d(TAG, "Bound to service " + className.toString());
routerServiceMessenger = new Messenger(service);
isBound = true;
//So we just established our connection
//Register with router service
Message msg = Message.obtain();
msg.what = TransportConstants.ROUTER_STATUS_CONNECTED_STATE_REQUEST;
msg.arg1 = flags;
msg.replyTo = clientMessenger;
try {
routerServiceMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
if(cb!=null){
cb.onConnectionStatusUpdate(false, routerService, context);
}
}
}
private static void sendReply(Context context, Intent intent, String packageName, Intent outIntent) {
try {
if (intent != null && intent.hasExtra(EXTRA_MESSENGER)) {
Messenger messenger = intent.getParcelableExtra(EXTRA_MESSENGER);
Message message = Message.obtain();
message.obj = outIntent;
messenger.send(message);
return;
}
} catch (Exception e) {
Log.w(TAG, e);
}
outIntent.setPackage(packageName);
context.sendOrderedBroadcast(outIntent, null);
}
public boolean notifyAPIStats(Messenger reply, ArrayList<CbStats> statsResult) {
try {
if (reply == null) {
log("cannot notify, reply is null");
} else {
log("cbservice notifying, " + statsResult.size());
reply.send(Message.obtain(null, MSG_STATS, statsResult));
}
} catch (RemoteException re) {
re.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
return false;
}
void notifyMessenger(Messenger messenger, int slot, int err) {
Message message = Message.obtain();
message.what = EVENT_PACKET_KEEPALIVE;
message.arg1 = slot;
message.arg2 = err;
message.obj = null;
try {
messenger.send(message);
} catch (RemoteException e) {
// Process died?
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "onServiceConnected");
mService = new Messenger(service);
Message msg = Message.obtain(null, XPConstant.TEST_JOIN);
try {
msg.replyTo = mReplyMessenger;
mService.send(msg);
mAliGenQR.setEnabled(true);
mWeGenQR.setEnabled(true);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void sendQRComplete(boolean success, String path, Messenger service){
Message msg = Message.obtain(null, XPConstant.MSG_QR_COMPLETE);
Bundle data = new Bundle();
data.putBoolean(XPConstant.QR_SUCCESS, success);
if(success){
data.putString(XPConstant.QR_PATH, path);
}
msg.setData(data);
try {
service.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
private void handlePostEvent(Message msg) {
Bundle bundle = msg.getData();
String eventClz = bundle.getString(Constants.BUNDLE_STR_EVENT_CLZ);
if (TextUtils.isEmpty(eventClz)) {
ILogger.logger.error(ILogger.defaultTag,"cannot handle non class event");
return;
}
List<WeakReference<Messenger>> subscribes = eventSubscriber.get(eventClz);
if (subscribes == null)
return;
for (int i = 0;i<subscribes.size();i++) {
WeakReference<Messenger> subscriberRef = subscribes.get(i);
if (subscriberRef == null || subscriberRef.get() == null) {
subscribes.remove(i);
i--;
continue;
}
Messenger messenger = subscriberRef.get();
Message cm = Message.obtain();
cm.what = Constants.WHAT_RECEIVE_EVENT_FROM_REMOTE;
cm.setData(msg.getData());
try {
messenger.send(cm);
} catch (RemoteException e) {
e.printStackTrace();
//remove the error subscriber
subscriberRef.clear();
subscribes.remove(i);
i--;
// continue;
}
}
}
public void onServiceConnected(ComponentName className, IBinder binderService) {
wakeUpService = new Messenger(binderService);
wakeUpServiceLock.lock();
try {
while (!wakeUpUnsentMessages.isEmpty()) {
wakeUpService.send(wakeUpUnsentMessages.poll());
}
} catch (RemoteException e) {
appendLog(getBaseContext(), TAG, e.getMessage(), e);
} finally {
wakeUpServiceLock.unlock();
}
serviceConnected(currentWeatherServiceConnection);
}
@Override
public void onServiceConnected(ComponentName className, IBinder binderService) {
widgetRefreshIconService = new Messenger(binderService);
widgetRotationServiceLock.lock();
try {
while (!unsentMessages.isEmpty()) {
widgetRefreshIconService.send(unsentMessages.poll());
}
} catch (RemoteException e) {
appendLog(getBaseContext(), TAG, e.getMessage(), e);
} finally {
widgetRotationServiceLock.unlock();
}
}
public void onServiceConnected(ComponentName className, IBinder binderService) {
wakeUpService = new Messenger(binderService);
wakeUpServiceLock.lock();
try {
while (!wakeUpUnsentMessages.isEmpty()) {
wakeUpService.send(wakeUpUnsentMessages.poll());
}
} catch (RemoteException e) {
appendLog(getBaseContext(), TAG, e.getMessage(), e);
} finally {
wakeUpServiceLock.unlock();
}
}
public void onServiceConnected(ComponentName className,
IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. We are communicating with our
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
mService = new Messenger(service);
mCallbackText.setText("Attached.");
// We want to monitor the service for as long as we are
// connected to it.
try {
Message msg = Message.obtain(null,
MessengerService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
// Give it some value as an example.
msg = Message.obtain(null,
MessengerService.MSG_SET_VALUE, this.hashCode(), 0);
mService.send(msg);
} catch (RemoteException e) {
// In this case the service has crashed before we could even
// do anything with it; we can count on soon being
// disconnected (and then reconnected if it can be restarted)
// so there is no need to do anything here.
}
// As part of the sample, tell the user what happened.
Toast.makeText(Binding.this, R.string.remote_service_connected,
Toast.LENGTH_SHORT).show();
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
try {
messenger = new Messenger(service);
Message msg = Message.obtain(null,Constant.Config.MSG_FROM_CLIENT);
msg.replyTo = mGetReplyMessenger;
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case ConnectToService:
SubstrateMain.log("New client is connected to instrumentation service");
//Create reporters, only if this is our first connection
if (!parsingInProgess && eventReporters.size()==0) {
createReportersFromConfigFile();
}
break;
case Event:
msg.getData().setClassLoader(InstrumentationServiceConnection.class.getClassLoader());
InterceptEvent event = (InterceptEvent) msg.getData().getParcelable("eventkey");
if (event != null) {
reportEvent(event);
}
break;
case GetConfiguration:
SubstrateMain.log("Configuration message has been received, sending current configuration to APK Instrumenter");
Messenger m = msg.replyTo;
Message response = Message.obtain(null, ApkInstrumenterActivity.Configuration);
//Construct Bundle from our attributes
Bundle configuration = new Bundle();
configuration.putString("idxp", idXP);
configuration.putBoolean("fileMode", fileMode);
configuration.putBoolean("networkMode", networkMode);
configuration.putString("esIp", esIp);
configuration.putInt("esPort", esPort);
configuration.putInt("esNbThread", esNbThread);
configuration.putString("esIndex", esIndex);
configuration.putString("esDoctype", esDoctype);
configuration.putString("fileName", fileName);
response.setData(configuration);
try {
m.send(response);
} catch (RemoteException e) {
SubstrateMain.log("Service has crashed");
e.printStackTrace();
}
break;
default:
SubstrateMain.log("Unknown Message received: " + msg.toString());
super.handleMessage(msg);
}
}