下面列出了android.hardware.usb.UsbAccessory#android.os.Messenger 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
try {
//Register client with service
Message msg = Message.obtain(null, NTRIPService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
//Request a status update.
msg = Message.obtain(null, NTRIPService.MSG_UPDATE_STATUS, 0, 0);
mService.send(msg);
//Request full log from service.
msg = Message.obtain(null, NTRIPService.MSG_UPDATE_LOG_FULL, 0, 0);
mService.send(msg);
SetSettings();
NTrip.this.onServiceConnected();
} catch (RemoteException e) {
// In this case the service has crashed before we could even do anything with it
}
}
private boolean onSelectRoute(Messenger messenger, int requestId,
int controllerId) {
ClientRecord client = getClient(messenger);
if (client != null) {
MediaRouteProvider.RouteController controller =
client.getRouteController(controllerId);
if (controller != null) {
controller.onSelect();
if (DEBUG) {
Log.d(TAG, client + ": Route selected"
+ ", controllerId=" + controllerId);
}
sendGenericSuccess(messenger, requestId);
return true;
}
}
return false;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (DEBUG) {
Log.d(TAG, this + ": Connected");
}
if (mBound) {
disconnect();
Messenger messenger = (service != null ? new Messenger(service) : null);
if (isValidRemoteMessenger(messenger)) {
Connection connection = new Connection(messenger);
if (connection.register()) {
mActiveConnection = connection;
} else {
if (DEBUG) {
Log.d(TAG, this + ": Registration failed");
}
}
} else {
Log.e(TAG, this + ": Service returned invalid messenger binder");
}
}
}
public boolean sendGuestScienceStop(String apkName) {
if (mApkMessengers.containsKey(apkName)) {
Messenger messenger = mApkMessengers.get(apkName);
Message msg = Message.obtain(null, MessageType.STOP.toInt());
try {
messenger.send(msg);
} catch (RemoteException e) {
ManagerNode.INSTANCE().getLogger().error(LOG_TAG, e.getMessage(), e);
return false;
}
} else {
ManagerNode.INSTANCE().getLogger().error(LOG_TAG, "Couldn't find messenger for " +
apkName + ". Thus cannot send a message to stop the apk.");
return false;
}
return true;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
BleLog.i(TAG, "mConnection onServiceConnected");
mSendMessage = new Messenger(service);
sendMsgAndSubscribe(BleConstants.MSG_CONTROL_ID_REGISTER);
mConnectTimeout = new TimeoutCallback() {
@Override
public void onTimeout() {
if(mConnCallback != null) {
mConnCallback.onConnectFailed(ConnectError.ConnectTimeout);
}
stopScanDevice();
}
};
if(mBindListener != null){
mBindListener.onServiceConnected();
}
}
public NetworkAgentInfo(Messenger messenger, AsyncChannel ac, Network net, NetworkInfo info,
LinkProperties lp, NetworkCapabilities nc, int score, Context context, Handler handler,
NetworkMisc misc, NetworkRequest defaultRequest, ConnectivityService connService) {
this.messenger = messenger;
asyncChannel = ac;
network = net;
networkInfo = info;
linkProperties = lp;
networkCapabilities = nc;
currentScore = score;
mConnService = connService;
mContext = context;
mHandler = handler;
networkMonitor = mConnService.createNetworkMonitor(context, handler, this, defaultRequest);
networkMisc = misc;
}
@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
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ONDOWNLOADPROGRESS:
Bundle bun = msg.getData();
if ( null != mContext ) {
bun.setClassLoader(mContext.getClassLoader());
DownloadProgressInfo dpi = (DownloadProgressInfo) msg.getData()
.getParcelable(PARAM_PROGRESS);
mItf.onDownloadProgress(dpi);
}
break;
case MSG_ONDOWNLOADSTATE_CHANGED:
mItf.onDownloadStateChanged(msg.getData().getInt(PARAM_NEW_STATE));
break;
case MSG_ONSERVICECONNECTED:
mItf.onServiceConnected(
(Messenger) msg.getData().getParcelable(PARAM_MESSENGER));
break;
}
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ONDOWNLOADPROGRESS:
Bundle bun = msg.getData();
if ( null != mContext ) {
bun.setClassLoader(mContext.getClassLoader());
DownloadProgressInfo dpi = (DownloadProgressInfo) msg.getData()
.getParcelable(PARAM_PROGRESS);
mItf.onDownloadProgress(dpi);
}
break;
case MSG_ONDOWNLOADSTATE_CHANGED:
mItf.onDownloadStateChanged(msg.getData().getInt(PARAM_NEW_STATE));
break;
case MSG_ONSERVICECONNECTED:
mItf.onServiceConnected(
(Messenger) msg.getData().getParcelable(PARAM_MESSENGER));
break;
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// Ignore this call if we disconnected in the meantime.
if (mContext == null) return;
mService = new Messenger(service);
mComponentName = name;
try {
Message registerClientMessage = Message.obtain(
null, REQUEST_REGISTER_CLIENT);
registerClientMessage.replyTo = mMessenger;
Bundle b = mGsaHelper.getBundleForRegisteringGSAClient(mContext);
registerClientMessage.setData(b);
registerClientMessage.getData().putString(
KEY_GSA_PACKAGE_NAME, mContext.getPackageName());
mService.send(registerClientMessage);
// Send prepare overlay message if there is a pending GSA context.
} catch (RemoteException e) {
Log.w(SERVICE_CONNECTION_TAG, "GSAServiceConnection - remote call failed", e);
}
}
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. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
Messenger mServiceMessenger = new Messenger(service);
mServiceMessengers.put(className.getClassName(), mServiceMessenger);
if(++countBoundServices == COUNT_SERVICES_FOR_BINDING) {
ConnectedDevice connectedDevice = BluetoothUtils.getPairedMicrobit(mCtx);
if(connectedDevice.mStatus) {
Intent intent = new Intent(mCtx, IPCService.class);
intent.putExtra(IPCConstants.INTENT_TYPE, EventCategories.IPC_BLE_CONNECT);
mCtx.startService(intent);
}
}
mBound = true;
}
public void onServiceConnected(final ComponentName name, final IBinder binder) {
postOrRun(new Runnable() {
public void run() {
if (MediaServiceConnection.this.isCurrent("onServiceConnected")) {
MediaBrowserServiceImplBase.this.mServiceBinderWrapper = new ServiceBinderWrapper(binder);
MediaBrowserServiceImplBase.this.mCallbacksMessenger = new Messenger(MediaBrowserServiceImplBase.this.mHandler);
MediaBrowserServiceImplBase.this.mHandler.setCallbacksMessenger(MediaBrowserServiceImplBase.this.mCallbacksMessenger);
MediaBrowserServiceImplBase.this.mState = 1;
try {
MediaBrowserServiceImplBase.this.mServiceBinderWrapper.connect(MediaBrowserServiceImplBase.this.mContext, MediaBrowserServiceImplBase.this.mRootHints, MediaBrowserServiceImplBase.this.mCallbacksMessenger);
} catch (RemoteException e) {
Log.w(MediaBrowserCompat.TAG, "RemoteException during connect for " + MediaBrowserServiceImplBase.this.mServiceComponent);
}
}
}
});
}
public void onLoadChildren(Messenger callback, String parentId, List list, Bundle options) {
if (isCurrent(callback, "onLoadChildren")) {
List<MediaItem> data = list;
Subscription subscription = (Subscription) this.mSubscriptions.get(parentId);
if (subscription != null) {
SubscriptionCallback subscriptionCallback = subscription.getCallback(options);
if (subscriptionCallback == null) {
return;
}
if (options == null) {
subscriptionCallback.onChildrenLoaded(parentId, data);
} else {
subscriptionCallback.onChildrenLoaded(parentId, data, options);
}
}
}
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ONDOWNLOADPROGRESS:
Bundle bun = msg.getData();
if ( null != mContext ) {
bun.setClassLoader(mContext.getClassLoader());
DownloadProgressInfo dpi = (DownloadProgressInfo) msg.getData()
.getParcelable(PARAM_PROGRESS);
mItf.onDownloadProgress(dpi);
}
break;
case MSG_ONDOWNLOADSTATE_CHANGED:
mItf.onDownloadStateChanged(msg.getData().getInt(PARAM_NEW_STATE));
break;
case MSG_ONSERVICECONNECTED:
mItf.onServiceConnected(
(Messenger) msg.getData().getParcelable(PARAM_MESSENGER));
break;
}
}
@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 int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
LogInfo.log("onStartCommand", "intent == null>>");
return super.onStartCommand(intent, flags, startId);
}
switch (intent.getIntExtra("cmd", 0)) {
case 1:
this.messenger = (Messenger) intent.getParcelableExtra("handler");
this.mScannerLocalVideoAsync = new LocalVideoScannerThread(this);
this.mScannerLocalVideoAsync.start();
break;
case 2:
if (this.mScannerLocalVideoAsync != null) {
this.mScannerLocalVideoAsync.cancelTask(true);
this.mScannerLocalVideoAsync = null;
}
stopSelf();
break;
case 3:
String tip = intent.getStringExtra("tip");
LogInfo.log(" ", "showToast tip >>" + tip);
LetvToast.showToast(tip);
break;
}
return super.onStartCommand(intent, flags, startId);
}
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);
}
private static Messenger createMessenger(final SingeProcessMessengerHandler.Callback callback) {
return new Messenger(new Handler(Looper.getMainLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
callback.onResult(msg.obj);
return true;
}
}));
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
bleHandler = new BLEHandler(this);
return new Messenger(bleHandler).getBinder();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_main);
Resources res = getResources();
defaultColor = res.getColor(R.color.none_received);
startJobColor = res.getColor(R.color.start_received);
stopJobColor = res.getColor(R.color.stop_received);
// Set up UI.
mShowStartView = (TextView) findViewById(R.id.onstart_textview);
mShowStopView = (TextView) findViewById(R.id.onstop_textview);
mParamsTextView = (TextView) findViewById(R.id.task_params);
mDelayEditText = (EditText) findViewById(R.id.delay_time);
mDeadlineEditText = (EditText) findViewById(R.id.deadline_time);
mPeriodEditText = (EditText) findViewById(R.id.period_time);
mNoConnectivityRadioButton = (RadioButton) findViewById(R.id.checkbox_none);
mWiFiConnectivityRadioButton = (RadioButton) findViewById(R.id.checkbox_unmetered);
mAnyConnectivityRadioButton = (RadioButton) findViewById(R.id.checkbox_any);
mRequiresChargingCheckBox = (CheckBox) findViewById(R.id.checkbox_charging);
mRequiresIdleCheckbox = (CheckBox) findViewById(R.id.checkbox_idle);
mPersistedCheckbox = (CheckBox) findViewById(R.id.checkbox_persisted);
mBackoffDelayEditText = (EditText) findViewById(R.id.backoff_delay_time);
mBackoffLinearRadioButton = (RadioButton) findViewById(R.id.checkbox_linear);
mBackoffExponentialRadioButton = (RadioButton) findViewById(R.id.checkbox_exponential);
mServiceComponent = new ComponentName(this, TestJobService.class);
// Start service and provide it a way to communicate with us.
Intent startServiceIntent = new Intent(this, TestJobService.class);
startServiceIntent.putExtra("messenger", new Messenger(mHandler));
startService(startServiceIntent);
}
@Test
public void verifyMultipleInitsAreIgnored() {
final EspressoRemote espressoRemote = new EspressoRemote(mockedInstrumentation);
espressoRemote.init();
espressoRemote.init();
espressoRemote.init();
Messenger messenger = espressoRemote.incomingHandler.messengerHandler;
verify(mockedInstrumentation).registerClient(EspressoRemote.TYPE, messenger);
}
private static void doFetchUsers(final Context context, final int type,
final Handler handler, final int page, final String userId) {
final Intent intent = new Intent(context, FanFouService.class);
intent.putExtra(Constants.EXTRA_TYPE, type);
intent.putExtra(Constants.EXTRA_MESSENGER, new Messenger(handler));
intent.putExtra(Constants.EXTRA_COUNT, Constants.MAX_USERS_COUNT);
intent.putExtra(Constants.EXTRA_PAGE, page);
intent.putExtra(Constants.EXTRA_ID, userId);
context.startService(intent);
}
public static void startServiceAction(Context context, String action, Handler handler) {
Intent intent = new Intent(context, MainIntentService.class);
// Create a new Messenger for the communication back
if (handler != null) {
Messenger messenger = new Messenger(handler);
intent.putExtra(MainIntentService.EXTRA_MESSENGER, messenger);
}
intent.setAction(action);
// start service with intent
context.startService(intent);
}
private int findClient(Messenger messenger) {
final int count = mClients.size();
for (int i = 0; i < count; i++) {
ClientRecord client = mClients.get(i);
if (client.hasMessenger(messenger)) {
return i;
}
}
return -1;
}
public void onServiceConnected(ComponentName className, IBinder service) {
log("widget client says : service connected");
mService = new Messenger(service);
mBound = true;
Message msg = Message.obtain(null, CbService.MSG_OKAY);
log("widget client received " + msg.arg1 + " " + msg.arg2);
askForLocalRecents(3);
askForSettings();
}
/** {@hide} */
public void unregisterNetworkFactory(Messenger messenger) {
try {
mService.unregisterNetworkFactory(messenger);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* @hide
* Register a NetworkAgent with ConnectivityService.
* @return NetID corresponding to NetworkAgent.
*/
public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
NetworkCapabilities nc, int score, NetworkMisc misc) {
try {
return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public IBinder onBind(Intent intent) {
Bundle extras = intent.getExtras();
// Get messager from the Activity
if (extras != null) {
outMessenger = (Messenger) extras.get("MESSENGER");
}
// Return our messenger to the Activity to get commands
return inMessenger.getBinder();
}
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. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mServiceMessenger = new Messenger(service);
mItf.onServiceConnected(
mServiceMessenger);
}
private void onBinderDied(Messenger messenger) {
int index = findClient(messenger);
if (index >= 0) {
ClientRecord client = mClients.remove(index);
if (DEBUG) {
Log.d(TAG, client + ": Binder died");
}
client.dispose();
}
}