下面列出了怎么用android.os.Message的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case CODE_SHOWLOADING:
showLoading();
handler.sendEmptyMessageDelayed(CODE_SHOWLOADING, 1000);
break;
case CODE_STOP_SHOWLOADING:
hideLoading();
handler.removeMessages(CODE_SHOWLOADING);
break;
case CODE_GONE_PROGRAMINFO:
rlDisplay.setVisibility(View.INVISIBLE);
break;
case CODE_NET_STATE:
tvNetState.setVisibility(View.INVISIBLE);
break;
case CODE_HIDE_BLACK:
tvBlack.setVisibility(View.INVISIBLE);
break;
}
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case -1:
//网络请求失败
Toast.makeText(getContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
break;
case 0:
//网络请求成功,但是返回状态为失败
Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
break;
case 1:
//网络请求成功
Bitmap bitmap = (Bitmap) msg.obj;
setImageBitmap(bitmap);
break;
}
}
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (X8MediaFileDownloadManager.this.mUiDownloadListener != null) {
switch (msg.what) {
case 0:
X8MediaFileDownloadManager.this.mUiDownloadListener.onProgress((MediaModel) msg.obj, msg.arg1);
return;
case 1:
X8MediaFileDownloadManager.this.mUiDownloadListener.onSuccess((MediaModel) msg.obj);
return;
case 2:
X8MediaFileDownloadManager.this.mUiDownloadListener.onFailure((MediaModel) msg.obj);
return;
case 3:
MediaModel mediaModel = msg.obj;
X8MediaFileDownloadManager.this.mUiDownloadListener.onStop(mediaModel);
X8MediaFileDownloadManager.this.sendStopDownload(mediaModel);
X8MediaFileDownloadManager.this.next();
return;
default:
return;
}
}
}
private MessageHandler getSensorDataRequestHandler() {
return new SinglePathMessageHandler(MessageHandler.PATH_SENSOR_DATA_REQUEST) {
@Override
public void handleMessage(Message message) {
// parse message
String sourceNodeId = getSourceNodeIdFromMessage(message);
String dataRequestJson = getDataFromMessageAsString(message);
Log.v(TAG, "Received a data request from " + sourceNodeId + ": " + dataRequestJson);
// update status from sensor data request
SensorDataRequest sensorDataRequest = SensorDataRequest.fromJson(dataRequestJson);
if (sensorDataRequest != null) {
if (sensorDataRequest.getEndTimestamp() == DataRequest.TIMESTAMP_NOT_SET) {
lastRequestedSensorCount = sensorDataRequest.getSensorTypes().size();
} else {
lastRequestedSensorCount = 0;
}
lastConnectedDeviceName = app.getGoogleApiMessenger().getNodeName(sensorDataRequest.getSourceNodeId());
}
updateStatusTexts();
logTextView.setText(String.valueOf(System.currentTimeMillis()));
}
};
}
/**
* 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 dispatchWallpaperCommand(String action, int x, int y,
int z, Bundle extras, boolean sync) {
synchronized (mLock) {
if (DEBUG) Log.v(TAG, "Dispatch wallpaper command: " + x + ", " + y);
WallpaperCommand cmd = new WallpaperCommand();
cmd.action = action;
cmd.x = x;
cmd.y = y;
cmd.z = z;
cmd.extras = extras;
cmd.sync = sync;
Message msg = mCaller.obtainMessage(MSG_WALLPAPER_COMMAND);
msg.obj = cmd;
mCaller.sendMessage(msg);
}
}
private void notifyClients(final Message message){
if(message==null){
Log.w(TAG, "Can't notify clients, message was null");
return;
}
Log.d(TAG, "Notifying "+ registeredApps.size()+ " clients");
int result;
synchronized(REGISTERED_APPS_LOCK){
Collection<RegisteredApp> apps = registeredApps.values();
Iterator<RegisteredApp> it = apps.iterator();
Message formattedMessage = new Message();
while(it.hasNext()){
RegisteredApp app = it.next();
formattedMessage.copyFrom(message);
//Format the message for the receiving app and appropriate messaging version
if(formatMessage(app, formattedMessage)) {
result = app.sendMessage(formattedMessage);
if (result == RegisteredApp.SEND_MESSAGE_ERROR_MESSENGER_DEAD_OBJECT) {
app.close();
it.remove();
}
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_rel);
new Thread(new Runnable() {
@Override
public void run() {
Map<String, String> versionInfo = HttpUtils.getVersionInfo();
Message message = Message.obtain();
message.obj = versionInfo;
message.what = 1;
handler.sendMessage(message);
}
}).start();
initUI();
initDialog();
initVideo();
//new TimeThread().start(); //启动新的线程刷新时间
}
@Override
public void handleMessage(Message msg) {
final OpenSLVisualizer holder = mHolder.get();
if (holder == null)
return;
final OnDataCaptureListener listener = holder.mOnDataCaptureListener;
if (listener == null)
return;
switch (msg.what) {
case MSG_ON_WAVEFORM_DATA_CAPTURE:
listener.onWaveFormDataCapture(holder, (byte[]) msg.obj, msg.arg1);
break;
case MSG_ON_FFT_DATA_CAPTURE:
listener.onFftDataCapture(holder, (byte[]) msg.obj, msg.arg1);
break;
}
}
@Override
public void handleMessage(Message msg) {
long pos;
switch (msg.what) {
case FADE_OUT:
hide();
break;
case SHOW_PROGRESS:
pos = setProgress();
if (!mDragging && mShowing) {
msg = obtainMessage(SHOW_PROGRESS);
sendMessageDelayed(msg, 1000 - (pos % 1000));
updatePausePlay();
}
break;
}
}
@Override
public void handleMessage(Message msg) {
// ALog.i(TAG, "ServiceHandler msg what:" + msg.what);
switch (msg.what) {
case MSG_DISCOVER_PEER:
if(!mStopDiscover){
ALog.i(TAG, "ServiceHandler 尝试探索");
mIsWifiP2pSearching=true;
discover();
}else{
mServiceHandler.removeMessages(MSG_DISCOVER_PEER);
ALog.i(TAG, "ServiceHandler 被终止探索");
}
break;
case MSG_DISCOVER_STOP:
ALog.i(TAG, "ServiceHandler 尝试终止探索");
stopPeer();
break;
}
}
public void onProgress(long token, AbstractAction action, float progress) {
Editor editor = mCallMap.get(token);
if (editor == null) {
return;
}
// notify stage
Message stageMsg = Message.obtain();
Bundle stageParams = new Bundle();
stageParams.putLong(KEY_TOKEN, token);
stageParams.putString(KEY_ACTION, action.mActionName);
stageParams.putFloat(KEY_STAGE_PROGRESS, progress);
stageMsg.what = MSG_ON_STAGE_PROGRESS;
stageMsg.setData(stageParams);
mMainHandler.sendMessage(stageMsg);
// notify overall
Message overallMsg = Message.obtain();
Bundle overallParams = new Bundle();
overallParams.putLong(KEY_TOKEN, token);
int lastPos = editor.mActionList.indexOf(action);
overallParams.putFloat(KEY_PROGRESS, (lastPos * 1.0f + progress) / editor.mActionList.size());
overallMsg.what = MSG_ON_PROGRESS;
overallMsg.setData(overallParams);
mMainHandler.sendMessage(overallMsg);
}
public void onClick(View v) {
Message m = null;
if (v == mButtonPositive && mButtonPositiveMessage != null) {
m = Message.obtain(mButtonPositiveMessage);
} else if (v == mButtonNegative && mButtonNegativeMessage != null) {
m = Message.obtain(mButtonNegativeMessage);
} else if (v == mButtonNeutral && mButtonNeutralMessage != null) {
m = Message.obtain(mButtonNeutralMessage);
}
if (m != null) {
m.sendToTarget();
}
// Post a message so we dismiss after the above handlers are executed
mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface)
.sendToTarget();
}
private void findLbeMessageAndRemoveIt(Message message) {
if (message == null) {
return;
}
Runnable callback = message.getCallback();
if (message.what == 0 && callback != null) {
if (callback.getClass().getName().indexOf("com.lbe.security.client") >= 0) {
message.getTarget().removeCallbacks(callback);
}
}
try {
Object nextObj = FieldUtils.readField(message, "next", true);
if (nextObj != null) {
Message next = (Message) nextObj;
findLbeMessageAndRemoveIt(next);
}
} catch (Exception e) {
Log.e(TAG, "findLbeMessageAndRemoveIt:error on remove lbe message", e);
}
}
public static synchronized void subscribe(android.content.Context context,
java.lang.String channel, java.lang.Class<? extends android.app.Activity> cls) {
startServiceIfRequired(context, cls);
final String finalChannel = channel;
AVInstallation.getCurrentInstallation().addUnique("channels", finalChannel);
_installationSaveHandler.sendMessage(Message.obtain());
if (cls != null) {
AVNotificationManager manager = AVNotificationManager.getInstance();
manager.addDefaultPushCallback(channel, cls.getName());
// set default push callback if it's not exist yet
if (manager.getDefaultPushCallback(AVOSCloud.getApplicationId()) == null) {
manager.addDefaultPushCallback(AVOSCloud.getApplicationId(), cls.getName());
}
}
}
private void updateImageFile(File imageFile) {
final BmobFile file = new BmobFile(imageFile);
file.uploadblock(new UploadFileListener() {
@Override
public void done(BmobException e) {
if (e == null) {
Log.i(TAG, "file.uploadblock:success ");
createFaceSet(file.getFileUrl());
} else {
Log.e(TAG, "file.uploadblock:failed ", e);
Message message = new Message();
message.arg1 = FinalUtil.UPDATE_PICTURE_EXCEPTION;
myhandler.sendMessage(message);
}
}
@Override
public void onProgress(Integer value) {
super.onProgress(value);
Log.i(TAG, "onProgress: " + value);
}
});
}
private void handleAddFeedback(Message msg){
String result = msg.obj.toString();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Root root = gson.fromJson(result, Root.class);
if(root==null){
//new Dialog(this,"错误","链接服务器失败").show();
Toast.makeText(this,"服务器繁忙,请重试",Toast.LENGTH_LONG).show();
return ;
}
if (!root.success){
new Dialog(this,"Tips",root.message).show();
return;
}
Toast.makeText(this,"提交成功",Toast.LENGTH_LONG).show();
finish();
}
private void handleCheckVideoCall(Message msg){
String result = msg.obj.toString();
Log.d("NearbyUserFragment", result);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
CheckVideoCallRoot root = gson.fromJson(result, CheckVideoCallRoot.class);
if (root == null){
//new Dialog(this,"错误","链接服务器失败").show();
Toast.makeText(getActivity(), "服务器繁忙,请重试", Toast.LENGTH_LONG).show();
return;
}
if (root.success == false){
new Dialog(getActivity(),"错误",root.message).show();
}
video_fee = root.video_fee + "";
}
@Override
public boolean handleMessage(Message message) {
switch (message.what) {
case CREATE_CHOREOGRAPHER: {
createChoreographerInstanceInternal();
return true;
}
case MSG_ADD_OBSERVER: {
addObserverInternal();
return true;
}
case MSG_REMOVE_OBSERVER: {
removeObserverInternal();
return true;
}
default: {
return false;
}
}
}
@Override
public void handleMessage(Message msg) {
String msgRxd;
Log.d(LOGTAG,"handleMessage: " + msg.what);
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_SET_CMD_VALUE:
msgRxd = msg.getData().getString("cmd");
Log.i(LOGTAG, msgRxd);
break;
case MSG_GS_TO_ROBOT:
msgRxd = msg.getData().getString("cmd");
Log.i(LOGTAG, msgRxd);
translateGSToRobot(msg.getData());
break;
default:
super.handleMessage(msg);
}
}
public void handleMessage(Message message)
{
switch (message.what)
{
default:
return;
case 0: // '\0'
a.onStart();
return;
case 1: // '\001'
a.onFinish(message.obj);
return;
case 2: // '\002'
a.onProgress(message.arg1);
return;
case 3: // '\003'
a.onFailed(message.obj);
break;
}
}
/**
* call alipay sdk pay. 调用SDK支付
*/
public void payV1(final String payInfo) {
Runnable payRunnable = new Runnable() {
@Override
public void run() {
// 构造PayTask 对象
PayTask alipay = new PayTask(context);
// 调用支付接口,获取支付结果
String result = alipay.pay(payInfo, true);// true 在调起支付页面之前显示进度条
Message msg = new Message();
msg.what = Config.SDK_PAY_FLAG;
msg.arg1 = VERSION_1;
msg.obj = result;
mHandler.sendMessage(msg);
}
};
// 必须异步调用
Thread payThread = new Thread(payRunnable);
payThread.start();
}
@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);
}
}
@Override
public boolean handleMessage(Message msg) {
if (!IdleCondition.handleMessage(msg, conditionSet, generation)) {
Log.i(TAG, "Unknown message type: " + msg);
return false;
} else {
return true;
}
}
@SuppressWarnings("unchecked")
public void handleMessage(android.os.Message msg) {
switch(msg.what){
case A6Util.MSG_GET_PASSENGERS_SUCCESS:
initPNames((List<PassengerInfo>)msg.obj);
break;
}
}
@Override
public void handleMessage(Message message) {
try {
Log.v(TAG, "Received a ping from " + getSourceNodeIdFromMessage(message) + ": " + getDataFromMessageAsString(message));
googleApiMessenger.sendMessageToNearbyNodes(PATH_ECHO, Build.MODEL);
} catch (Exception ex) {
Log.w(TAG, "Unable to answer ping");
}
}
public final void onCancel(Platform platform, int action) {
Message msg = new Message();
msg.arg1 = 3;
msg.arg2 = action;
msg.obj = platform;
UIHandler.sendMessage(msg, this);
// 分享失败的统计
ShareSDK.logDemoEvent(5, platform);
}
private void handleGetFriendGroupNameList(Message msg){
String result = msg.obj.toString();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Root root = gson.fromJson(result, Root.class);
if(root==null){
//new Dialog(this,"错误","链接服务器失败").show();
Toast.makeText(this,"服务器繁忙,请重试",Toast.LENGTH_LONG).show();
return ;
}
if (!root.success){
new Dialog(this,"Tips",root.message).show();
return;
}
list_friendgroupnameItem.clear();
FriendGroupNameItem friendGroupNameItem;
for(FriendGroup friendGroup : root.list_friendgroup){
friendGroupNameItem = new FriendGroupNameItem();
friendGroupNameItem.setId(friendGroup.id);
friendGroupNameItem.setFriendgroup_name(friendGroup.friendgroup_name);
list_friendgroupnameItem.add(friendGroupNameItem);
}
friendGroupNameBaseAdapter = new FriendGroupNameBaseAdapter(this,list_friendgroupnameItem);
listView.setAdapter(friendGroupNameBaseAdapter);
listView.setMenuCreator(creator);
System.out.print("");
}
/**
* Sets a click listener or a message to be sent when the button is clicked.
* You only need to pass one of {@code listener} or {@code msg}.
* @param whichButton Which button, can be one of
* {@link DialogInterface#BUTTON_POSITIVE},
* {@link DialogInterface#BUTTON_NEGATIVE}, or
* {@link DialogInterface#BUTTON_NEUTRAL}
* @param text The text to display in button.
* @param icon The icon to display in button.
* @param listener The {@link DialogInterface.OnClickListener} to use.
* @param msg The {@link Message} to be sent when clicked.
*/
public void setButton(int whichButton, CharSequence text, Drawable icon,
DialogInterface.OnClickListener listener, Message msg) {
if (msg == null && listener != null) {
msg = mHandler.obtainMessage(whichButton, listener);
}
switch (whichButton) {
case DialogInterface.BUTTON_POSITIVE:
mButtonBundlePositive.buttonText = text;
mButtonBundlePositive.buttonIcon = icon;
mButtonBundlePositive.buttonMessage = msg;
break;
case DialogInterface.BUTTON_NEGATIVE:
mButtonBundleNegative.buttonText = text;
mButtonBundleNegative.buttonIcon = icon;
mButtonBundleNegative.buttonMessage = msg;
break;
case DialogInterface.BUTTON_NEUTRAL:
mButtonBundleNeutral.buttonText = text;
mButtonBundleNeutral.buttonIcon = icon;
mButtonBundleNeutral.buttonMessage = msg;
break;
default:
throw new IllegalArgumentException("Button does not exist");
}
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.obj.toString().equals("clear")) {
clearDate();
dialogDismiss();
}
}