下面列出了android.os.Handler#sendEmptyMessage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_splash);
iv_splash = (ImageView) findViewById(R.id.iv_splash);
mUiHandler = new Handler(this.getMainLooper(), mUiHandlerCallback);
if (GApplication.isEntry()) {
getUiHandler().sendEmptyMessage(MSG_UI_INIT_FINISH);
return;
}
mSubThread = new HandlerThread("application_setup_thread");
mSubThread.start();
mSubHandler = new Handler(mSubThread.getLooper(), mSubHandlerCallback);
mSubHandler.sendEmptyMessage(MSG_SUB_INIT_TASK);
}
/**
* Queue a work-runnable for processing asynchronously.
*
* @param work The new runnable to process
* @param shouldDelay If the message should be delayed
*/
public static void queue(Runnable work, boolean shouldDelay) {
Handler handler = getHandler();
synchronized (sLock) {
sWork.add(work);
if (shouldDelay && sCanDelay) {
handler.sendEmptyMessageDelayed(QueuedWorkHandler.MSG_RUN, DELAY);
} else {
handler.sendEmptyMessage(QueuedWorkHandler.MSG_RUN);
}
}
}
public void waitUntilIdle() {
Handler handler = waitAndGetHandler();
MessageQueue queue = handler.getLooper().getQueue();
if (queue.isIdle()) {
return;
}
mIdle.close();
queue.addIdleHandler(mIdleHandler);
// Ensure that the idle handler gets run even if the looper already went idle
handler.sendEmptyMessage(MSG_POKE_IDLE_HANDLER);
if (queue.isIdle()) {
return;
}
mIdle.block();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause");
super.onPause();
// if we get here too quickly, the handler might still be null; not dealing with that
Handler handler = mRenderThread.getHandler();
handler.sendEmptyMessage(0);
mRenderThread = null;
}
/**
* Release {@link WakeLock} and notify {@link Handler}.
*
* @param h {@link Handler}
* @param a action
*/
private void release(final Handler h, final String a) {
// schedule next update
if (a == null || !a.equals(ACTION_SHORT_RUN)) {
LogRunnerReceiver.schedNext(this, null);
} else {
LogRunnerReceiver.schedNext(this, a);
}
if (h != null) {
h.sendEmptyMessage(Plans.MSG_BACKGROUND_STOP_MATCHER);
}
Log.i(TAG, "wakelock released");
}
public synchronized void sync(final boolean syncUp, final boolean syncDown,
Handler hanler) {
if (hanler != null) {
hanler.sendEmptyMessage(SYNC_START);
}
toSync(syncUp, syncDown, hanler);
}
public static void updateClients() {
//myLog.l(Log.DEBUG, "UI update");
//Log.d("UiUpdate", "Update now");
for (Handler client : clients) {
client.sendEmptyMessage(0);
}
}
private void notifyMediaUpdated() {
// update the video and audio activities
for (int i = 0; i < mUpdateHandler.size(); i++) {
Handler h = mUpdateHandler.get(i);
h.sendEmptyMessage(MEDIA_ITEMS_UPDATED);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_time = (TextView) findViewById(R.id.tv_time);
tv_date = (TextView) findViewById(R.id.tv_date);
tv_day = (TextView) findViewById(R.id.tv_day);
Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/ds_digi.ttf");
tv_time.setTypeface(typeFace);
tv_date.setTypeface(typeFace);
tv_weather = (TextView) findViewById(R.id.tv_weather);
tv_descript = (TextView) findViewById(R.id.tv_descript);
handler = new Handler(this);
tv_setting = (TextView) findViewById(R.id.tv_setting);
tv_setting.setOnClickListener(this);
tv_time.setOnClickListener(this);
RelativeLayout rel_main = (RelativeLayout) findViewById(R.id.rel_main);
rel_main.setOnClickListener(this);
init();
PowerManager powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Clock");
localWakeLock = powerManager.newWakeLock(32, "MyPower");
ClockApplication.getInstance().setMainActivity(this);
ClockApplication.getInstance().getBusinessService().getWeather(model.getCity());
timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(UPDATE_TIME);
}
};
timer.schedule(timerTask, 1000, 1000);
ClockApplication.getInstance().getBusinessService().checkUpdate();
}
/** Ensures that the main looper is not blocked and can process messages during test execution. */
@Test
public void testMainLooperIsAlive() throws InterruptedException {
final boolean[] called = new boolean[1];
Handler handler =
new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
called[0] = true;
}
};
handler.sendEmptyMessage(0);
Thread.sleep(SLEEP_TIME);
Assert.assertTrue(called[0]);
}
@Override
public void run() {
super.run();
mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.e("Edwin", "LooperThread2 ok");
}
};
mHandler.sendEmptyMessage(1);
}
private void notifyNewOutput() {
Handler writerHandler = mWriterHandler;
if (writerHandler == null) {
/* Writer thread isn't started -- will pick up data once it does */
return;
}
writerHandler.sendEmptyMessage(NEW_OUTPUT);
}
public void performSync(TvInputProvider provider, String inputId) {
Log.d(TAG, "Actually begin the sync");
List<Channel> allChannels = provider.getAllChannels(getContext());
if(allChannels == null) {
//You have no channels!!
return;
}
Log.d(TAG, allChannels.toString());
for (int i = 0; i < allChannels.size(); i++) {
if (allChannels.get(i).getOriginalNetworkId() == 0)
allChannels.get(i).setOriginalNetworkId(i + 1);
if (allChannels.get(i).getTransportStreamId() == 0)
allChannels.get(i).setTransportStreamId(i + 1);
}
TvContractUtils.updateChannels(getContext(), inputId, allChannels);
LongSparseArray<Channel> channelMap = TvContractUtils.buildChannelMap(
mContext.getContentResolver(), inputId, allChannels);
if (channelMap == null) {
Log.d(TAG, "?");
Handler h = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Toast.makeText(getContext(), "Couldn't find any channels. Uh-oh.", Toast.LENGTH_SHORT).show();
}
};
h.sendEmptyMessage(0);
//Let's not continue running
return;
}
long startMs = new Date().getTime();
long endMs = startMs + FULL_SYNC_WINDOW_SEC * 1000;
Log.d(TAG, "Now start to get programs");
for (int i = 0; i < channelMap.size(); ++i) {
Uri channelUri = TvContract.buildChannelUri(channelMap.keyAt(i));
List<Program> programList = provider.getProgramsForChannel(getContext(), channelUri, channelMap.valueAt(i), startMs, endMs);
Log.d(TAG, "Okay, we NEED to set the channel id first");
for(Program p: programList) {
p.setChannelId(channelMap.keyAt(i));
}
Log.d(TAG, "For " + channelMap.valueAt(i).toString());
Log.d(TAG, programList.toString());
updatePrograms(channelUri, programList);
//Let's double check programs
Uri programEditor = TvContract.buildProgramsUriForChannel(channelUri);
}
Log.d(TAG, "Sync performed");
}
protected void sendEmptyMessage(Handler handler, int what) {
if (handler != null)
handler.sendEmptyMessage(what);
}
private void freezeSerialHandler(Handler handler) {
handler.sendEmptyMessage(WHAT_FREEZE);
}
/**
* Runs a Loader synchronously and returns the result of the load. The loader will
* be started, stopped, and destroyed by this method so it cannot be reused.
*
* @param loader The loader to run synchronously
* @return The result from the loader
*/
@SuppressLint("HandlerLeak")
public <T> T getLoaderResultSynchronously(final Loader<T> loader) {
// The test thread blocks on this queue until the loader puts it's result in
final ArrayBlockingQueue<T> queue = new ArrayBlockingQueue<T>(1);
// This callback runs on the "main" thread and unblocks the test thread
// when it puts the result into the blocking queue
final OnLoadCompleteListener<T> listener = new OnLoadCompleteListener<T>() {
@Override
public void onLoadComplete(Loader<T> completedLoader, T data) {
// Shut the loader down
completedLoader.unregisterListener(this);
completedLoader.stopLoading();
completedLoader.reset();
// Store the result, unblocking the test thread
queue.add(data);
}
};
// This handler runs on the "main" thread of the process since AsyncTask
// is documented as needing to run on the main thread and many Loaders use
// AsyncTask
final Handler mainThreadHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
loader.registerListener(0, listener);
loader.startLoading();
}
};
// Ask the main thread to start the loading process
mainThreadHandler.sendEmptyMessage(0);
// Block on the queue waiting for the result of the load to be inserted
T result;
while (true) {
try {
result = queue.take();
break;
} catch (InterruptedException e) {
throw new RuntimeException("waiting thread interrupted", e);
}
}
return result;
}
/**
* 下载方法
* @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);
}
}
/**
* Submit the given burst of requests to be captured.
*
* <p>If the burst is repeating, replace the current repeating burst.</p>
*
* @param requests the burst of requests to add to the queue.
* @param repeating true if the burst is repeating.
* @return the submission info, including the new request id, and the last frame number, which
* contains either the frame number of the last frame that will be returned for this request,
* or the frame number of the last frame that will be returned for the current repeating
* request if this burst is set to be repeating.
*/
public SubmitInfo submitCaptureRequests(CaptureRequest[] requests, boolean repeating) {
Handler handler = mRequestThread.waitAndGetHandler();
SubmitInfo info;
synchronized (mIdleLock) {
info = mRequestQueue.submit(requests, repeating);
handler.sendEmptyMessage(MSG_SUBMIT_CAPTURE_REQUEST);
}
return info;
}
/**
* Send an empty message containing only the what value.
* @param handler
* @param what
*/
public static void sendMessageHandler(Handler handler, int what) {
handler.sendEmptyMessage(what);
}
/**
* Send an empty message containing only the what value.
* @param handler
* @param what
*/
public static void sendMessageHandler(Handler handler, int what) {
handler.sendEmptyMessage(what);
}