Java Code Examples for android.os.Handler#sendEmptyMessage()

The following examples show how to use android.os.Handler#sendEmptyMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SplashActivity.java    From opencdk-appwidget with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: MediaLibrary.java    From VCL-Android with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 3
Source File: TermSession.java    From Ansole with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 4
Source File: ComplexActivity.java    From AndroidProjects with MIT License 5 votes vote down vote up
@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);
}
 
Example 5
Source File: AndroidJUnitRunnerTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
/** 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]);
}
 
Example 6
Source File: MainActivity.java    From CoolClock with GNU General Public License v3.0 5 votes vote down vote up
@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();
}
 
Example 7
Source File: QueuedWork.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 8
Source File: UiUpdater.java    From stynico with MIT License 5 votes vote down vote up
public static void updateClients() {
	//myLog.l(Log.DEBUG, "UI update");
	//Log.d("UiUpdate", "Update now");
	for (Handler client : clients) {
		client.sendEmptyMessage(0);
	}
}
 
Example 9
Source File: Evernote.java    From EverMemo with MIT License 5 votes vote down vote up
public synchronized void sync(final boolean syncUp, final boolean syncDown,
		Handler hanler) {
	if (hanler != null) {
		hanler.sendEmptyMessage(SYNC_START);
	}
	toSync(syncUp, syncDown, hanler);
}
 
Example 10
Source File: LogRunnerService.java    From callmeter with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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");
}
 
Example 11
Source File: ChorTestActivity.java    From grafika with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 12
Source File: RequestHandlerThread.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 13
Source File: BaseManager.java    From FoodOrdering with Apache License 2.0 4 votes vote down vote up
protected void sendEmptyMessage(Handler handler, int what) {
    if (handler != null)
        handler.sendEmptyMessage(what);
}
 
Example 14
Source File: QueuesHandler.java    From FileDownloader with Apache License 2.0 4 votes vote down vote up
private void freezeSerialHandler(Handler handler) {
    handler.sendEmptyMessage(WHAT_FREEZE);
}
 
Example 15
Source File: SupportLoaderTestCase.java    From arca-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
    * 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;
   }
 
Example 16
Source File: SyncAdapter.java    From ChannelSurfer with MIT License 4 votes vote down vote up
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");
}
 
Example 17
Source File: Download.java    From LitePlayer with Apache License 2.0 4 votes vote down vote up
/**
	 * 下载方法
	 * @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);
		}
	}
 
Example 18
Source File: RequestThreadManager.java    From android_9.0.0_r45 with Apache License 2.0 3 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source File: HandlerUtils.java    From UltimateAndroid with Apache License 2.0 2 votes vote down vote up
/**
 * Send an empty message containing only the what value.
 * @param handler
 * @param what
 */
public static void sendMessageHandler(Handler handler, int what) {
    handler.sendEmptyMessage(what);
}
 
Example 20
Source File: HandlerUtils.java    From UltimateAndroid with Apache License 2.0 2 votes vote down vote up
/**
 * Send an empty message containing only the what value.
 * @param handler
 * @param what
 */
public static void sendMessageHandler(Handler handler, int what) {
    handler.sendEmptyMessage(what);
}