下面列出了android.os.Handler#sendMessage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
void
internalNotifyRegistrant (Object result, Throwable exception)
{
Handler h = getHandler();
if (h == null) {
clear();
} else {
Message msg = Message.obtain();
msg.what = what;
msg.obj = new AsyncResult(userObj, result, exception);
h.sendMessage(msg);
}
}
/**
* Shuts down the encoder thread, and releases encoder resources.
* <p>
* Does not return until the encoder thread has stopped.
*/
public void shutdown() {
if (VERBOSE) Log.d(TAG, "releasing encoder objects");
Handler handler = mEncoderThread.getHandler();
handler.sendMessage(handler.obtainMessage(EncoderThread.EncoderHandler.MSG_SHUTDOWN));
try {
mEncoderThread.join();
} catch (InterruptedException ie) {
Log.w(TAG, "Encoder thread join() was interrupted", ie);
}
if (mEncoder != null) {
mEncoder.stop();
mEncoder.release();
mEncoder = null;
}
}
public static void sendMessageHandler(Handler handler, int what, String key, int value) {
Message message = new Message();
message.what = what;
Bundle bundle = new Bundle();
bundle.putInt(key, value);
message.setData(bundle);
handler.sendMessage(message);
}
/**
* Configure the GL renderer for the given set of output surfaces, and block until
* this configuration has been applied.
*
* @param surfaces a collection of pairs of {@link android.view.Surface}s and their
* corresponding sizes to configure.
* @param collector a {@link CaptureCollector} to retrieve requests from.
*/
public void setConfigurationAndWait(Collection<Pair<Surface, Size>> surfaces,
CaptureCollector collector) {
checkNotNull(collector, "collector must not be null");
Handler handler = mGLHandlerThread.getHandler();
final ConditionVariable condition = new ConditionVariable(/*closed*/false);
ConfigureHolder configure = new ConfigureHolder(condition, surfaces, collector);
Message m = handler.obtainMessage(MSG_NEW_CONFIGURATION, /*arg1*/0, /*arg2*/0, configure);
handler.sendMessage(m);
// Block until configuration applied.
condition.block();
}
private void sendOutputStream(int what, int arg, Object obj) {
McsOutputStream os = outputStream;
if (os != null && os.isAlive()) {
Handler outputHandler = os.getHandler();
if (outputHandler != null)
outputHandler.sendMessage(outputHandler.obtainMessage(what, arg, 0, obj));
}
}
/**
* 开启热点
*/
public static void startWifiAp(String ssid, String passwd, final Handler handler) {
if (mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(false);
}
startAp(ssid, passwd);
TimerCheck timerCheck = new TimerCheck() {
@Override
public void doTimerCheckWork() {
if (isWifiApEnabled()) {
// LogUtils.v(TAG, "WifiAp enabled success!");
Message msg = handler.obtainMessage(WifiConst.ApCreateApSuccess);
handler.sendMessage(msg);
this.exit();
} else {
// LogUtils.v(TAG, "WifiAp enabled failed!");
}
}
@Override
public void doTimeOutWork() {
this.exit();
}
};
timerCheck.start(10, 1000);
}
/**
* In case of a Disconnect, the connectivity manager may have already
* established, or may be attempting to establish, connectivity with another
* network. If so, {@code mOtherNetworkInfo} will be non-null.
*/
// private NetworkInfo mOtherNetworkInfo;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
mState = State.NOT_CONNECTED;
mNetworkInfo = manager.getActiveNetworkInfo();
if (mNetworkInfo != null
&& mNetworkInfo.isConnected())
{
mState = State.CONNECTED;
}
if (mHandlers != null)
{
// Notifiy any handlers.
Iterator<Handler> it = mHandlers.keySet().iterator();
while (it.hasNext()) {
Handler target = it.next();
Message message = Message.obtain(target, mHandlers.get(target));
target.sendMessage(message);
}
}
}
public static void sendMessage(Handler handler, int what, int arg1, Bundle bundle) {
Message msg = handler.obtainMessage();
msg.what = what;
msg.arg1 = arg1;
msg.setData(bundle);
// 发送消息
handler.sendMessage(msg);
}
public static void doRead(int port, String outname, Handler handler) throws
IOException {
ServerSocket server = new ServerSocket(port);
Socket client = server.accept();
// Read the file header to know how much to read
DataInputStream ds = new DataInputStream(client.getInputStream());
int size = ds.readInt();
int length = size;
FileOutputStream os = new FileOutputStream(outname);
InputStream is = client.getInputStream();
byte[] buffer = new byte[BUFFER_SIZE];
ByteArrayOutputStream bs = new ByteArrayOutputStream();
while (size >= BUFFER_SIZE) {
size -= readChunk(is, bs, buffer);
// This prevents the stack from growing too large on
// Android devices. Apparently, they can't fit a whole
// 9.9Mb file into the stack.
Message msg = new Message();
msg.what = (int) (100 * (1.0 * (length - size) / length));
Log.e("IP & PORT", msg.what + "");
handler.sendMessage(msg);
os.write(bs.toByteArray());
bs.reset();
}
readLeftover(is, bs);
os.write(bs.toByteArray());
server.close();
client.close();
is.close();
ds.close();
os.close();
}
public static void sendMessage(Handler handler, int what, int arg1, Object obj, Bundle bundle) {
Message msg = handler.obtainMessage();
msg.what = what;
msg.arg1 = arg1;
msg.obj = obj;
msg.setData(bundle);
// 发送消息
handler.sendMessage(msg);
}
public static void sendMessage(Handler handler, int what, int arg1, int arg2, Object obj) {
Message msg = handler.obtainMessage();
msg.what = what;
msg.arg1 = arg1;
msg.arg2 = arg2;
msg.obj = obj;
// 发送消息
handler.sendMessage(msg);
}
protected Object loadCache(Handler mHandler, Object... params){
List list = httpCache.loadCache(params);
Message msg = Message.obtain();
msg.what = MSG_CACHE;
msg.obj = list;
mHandler.sendMessage(msg);
return list;
}
public PackageInstallerSession(PackageInstallerService.InternalCallback callback,
Context context, PackageManagerService pm, Looper looper, int sessionId, int userId,
String installerPackageName, int installerUid, SessionParams params, long createdMillis,
File stageDir, String stageCid, boolean prepared, boolean sealed) {
mCallback = callback;
mContext = context;
mPm = pm;
mHandler = new Handler(looper, mHandlerCallback);
this.sessionId = sessionId;
this.userId = userId;
mOriginalInstallerUid = installerUid;
mInstallerPackageName = installerPackageName;
mInstallerUid = installerUid;
this.params = params;
this.createdMillis = createdMillis;
this.stageDir = stageDir;
this.stageCid = stageCid;
if ((stageDir == null) == (stageCid == null)) {
throw new IllegalArgumentException(
"Exactly one of stageDir or stageCid stage must be set");
}
mPrepared = prepared;
if (sealed) {
synchronized (mLock) {
try {
sealAndValidateLocked();
} catch (PackageManagerException | IOException e) {
destroyInternal();
throw new IllegalArgumentException(e);
}
}
}
final long identity = Binder.clearCallingIdentity();
try {
final int uid = mPm.getPackageUid(PackageManagerService.DEFAULT_CONTAINER_PACKAGE,
PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
defaultContainerGid = UserHandle.getSharedAppGid(uid);
} finally {
Binder.restoreCallingIdentity(identity);
}
// attempt to bind to the DefContainer as early as possible
if ((params.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
mHandler.sendMessage(mHandler.obtainMessage(MSG_EARLY_BIND));
}
}
public static void sendMessageHandler(Handler handler, int what) {
Message message = new Message();
message.what = what;
handler.sendMessage(message);
}
/**
* Installs a library from a ZIP archive
*
* @param libraryZip
* @param context
*/
public static boolean installZipLibrary(Library library, Uri libraryZip, Handler handler, APDE context) {
library.setStatus(Library.Status.EXTRACTING);
handler.sendMessage(Message.obtain(handler, LIBRARY_UPDATE, library.getStatus()));
ParcelFileDescriptor fd = FileSelection.openUri(context, libraryZip, FileSelection.Mode.READ);
if (fd == null) {
System.err.println(context.getResources().getString(R.string.install_zip_library_failure_unexpected_error));
return false;
}
FileInputStream inputStream = new FileInputStream(fd.getFileDescriptor());
try {
//Extract to the libraries folder
if (!extractFile(inputStream, library.getLibraryFolder(context.getLibrariesFolder()))) {
System.err.println(context.getResources().getString(R.string.install_zip_library_failure_unexpected_error));
return false;
}
library.setStatus(Library.Status.DEXING);
handler.sendMessage(Message.obtain(handler, LIBRARY_UPDATE, library.getStatus()));
//We dex during the install to save build time
//Make sure that we have a dexed library directory
library.getLibraryJarDexFolder(context.getLibrariesFolder()).mkdir();
try {
File[] jars = library.getLibraryJars(context.getLibrariesFolder());
File[] dexJars = library.getLibraryDexJars(context.getLibrariesFolder());
//Dex all of the files...
for (int i = 0; i < jars.length; i++) {
dexJar(jars[i], dexJars[i], context);
}
} catch (NullPointerException e) {
//If we can't find the JARs
System.err.println(String.format(Locale.US,
context.getResources().getString(R.string.install_library_failure_poor_structure),
library.getLibraryJarFolder(context.getLibrariesFolder())));
e.printStackTrace();
return false;
}
} finally {
FileSelection.closeFd(fd);
}
library.setStatus(Library.Status.INSTALLED);
handler.sendMessage(Message.obtain(handler, LIBRARY_UPDATE, library.getStatus()));
return true;
}
/**
* 下载方法
* @param handler 消息处理器
*/
private void download(boolean isGoon, Handler handler) {
Message msg = null;
L.l("开始下载。。。");
try {
RandomAccessFile localFile = new RandomAccessFile(new File(mLocalPath), "rwd");
DefaultHttpClient client = new DefaultHttpClient();
client.setParams(getHttpParams());
HttpGet get = new HttpGet(mUrl);
long localFileLength = getLocalFileLength();
final long remoteFileLength = getRemoteFileLength();
long downloadedLength = localFileLength;
// 远程文件不存在
if (remoteFileLength == -1l) {
L.l("下载文件不存在...");
localFile.close();
handler.sendEmptyMessage(ERROR);
return;
}
// 本地文件存在
if (localFileLength > -1l && localFileLength < remoteFileLength) {
L.l("本地文件存在...");
localFile.seek(localFileLength);
get.addHeader("Range", "bytes=" + localFileLength + "-"
+ remoteFileLength);
}
msg = Message.obtain();
// 如果不是继续下载
if(!isGoon) {
// 发送开始下载的消息并获取文件大小的消息
msg.what = START;
msg.obj = remoteFileLength;
}else {
msg.what = GOON;
msg.obj = localFileLength;
}
handler.sendMessage(msg);
HttpResponse response = client.execute(get);
int httpCode = response.getStatusLine().getStatusCode();
if (httpCode >= 200 && httpCode <= 300) {
InputStream in = response.getEntity().getContent();
byte[] bytes = new byte[1024];
int len = -1;
while (-1 != (len = in.read(bytes))) {
localFile.write(bytes, 0, len);
downloadedLength += len;
// Log.log((int)(downloadedLength/(float)remoteFileLength * 100));
if ((int)(downloadedLength/(float)remoteFileLength * 100) % 10 == 0) {
// 发送更新进度的消息
handler.obtainMessage(PUBLISH, downloadedLength).sendToTarget();
// Log.log(mDownloadId + "已下载" + downloadedLength);
}
// 暂停下载, 退出方法
if (isPause) {
// 发送暂停的消息
handler.sendEmptyMessage(PAUSE);
L.l("下载暂停...");
break;
}
// 取消下载, 删除文件并退出方法
if (isCanceled) {
L.l("手动关闭下载。。");
localFile.close();
client.getConnectionManager().shutdown();
new File(mLocalPath).delete();
// 发送取消下载的消息
handler.sendEmptyMessage(CANCEL);
return;
}
}
localFile.close();
client.getConnectionManager().shutdown();
// 发送下载完毕的消息
if(!isPause) handler.sendEmptyMessage(SUCCESS);
}
} catch (Exception e) {
e.printStackTrace();
// 发送下载错误的消息
handler.sendEmptyMessage(ERROR);
}
}
public static void sendMessageHandler(Handler handler, int what, Object obj) {
Message message = new Message();
message.what = what;
message.obj = obj;
handler.sendMessage(message);
}
/**
* Configure with the current list of output Surfaces.
*
* <p>
* This operation blocks until the configuration is complete.
* </p>
*
* <p>Using a {@code null} or empty {@code outputs} list is the equivalent of unconfiguring.</p>
*
* @param outputs a {@link java.util.Collection} of outputs to configure.
*/
public void configure(Collection<Pair<Surface, Size>> outputs) {
Handler handler = mRequestThread.waitAndGetHandler();
final ConditionVariable condition = new ConditionVariable(/*closed*/false);
ConfigureHolder holder = new ConfigureHolder(condition, outputs);
handler.sendMessage(handler.obtainMessage(MSG_CONFIGURE_OUTPUTS, 0, 0, holder));
condition.block();
}
/**
* Pushes a message containing bundle onto the end of the message queue after all pending messages before the current time.
*
* @param handler
* @param what
* @param bundle
*/
public static void sendMessageHandler(Handler handler, int what, Bundle bundle) {
Message message = new Message();
message.what = what;
message.setData(bundle);
handler.sendMessage(message);
}
/**
* Initiates saving the currently-buffered frames to the specified output file. The
* data will be written as a .mp4 file. The call returns immediately. When the file
* save completes, the callback will be notified.
* <p>
* The file generation is performed on the encoder thread, which means we won't be
* draining the output buffers while this runs. It would be wise to stop submitting
* frames during this time.
*/
public void saveVideo(File outputFile) {
Handler handler = mEncoderThread.getHandler();
handler.sendMessage(handler.obtainMessage(
EncoderThread.EncoderHandler.MSG_SAVE_VIDEO, outputFile));
}