List of usage examples for android.os Handler sendEmptyMessage
public final boolean sendEmptyMessage(int what)
From source file:com.scvngr.levelup.core.test.SupportLoaderTestCase.java
/** * 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//from www. ja v a 2 s.c o m */ public <T> T getLoaderResultSynchronously(final Loader<T> loader) { // The test thread blocks on this queue until the loader puts its result in final ArrayBlockingQueue<T> queue = new ArrayBlockingQueue<T>(1); final CountDownLatch latch = new CountDownLatch(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(final Loader<T> completedLoader, final T data) { // Shut the loader down completedLoader.unregisterListener(this); completedLoader.stopLoading(); completedLoader.reset(); // Store the result, unblocking the test thread if (null != data) { queue.add(data); } latch.countDown(); } }; // 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(final 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 { latch.await(); result = queue.peek(); break; } catch (final InterruptedException e) { throw new RuntimeException("waiting thread interrupted", e); } } return result; }
From source file:net.wespot.pim.utils.generic.NetworkHandle.java
public static void isNetworkAvailable(final Handler handler, final int timeout) { // ask fo message '0' (not connected) or '1' (connected) on 'handler' // the answer must be send before before within the 'timeout' (in milliseconds) new Thread() { private boolean responded = false; @Override/*from w w w. j a v a2 s .c o m*/ public void run() { // set 'responded' to TRUE if is able to connect with google mobile (responds fast) new Thread() { @Override public void run() { HttpGet requestForTest = new HttpGet("http://m.google.com"); try { new DefaultHttpClient().execute(requestForTest); // can last... responded = true; } catch (Exception e) { } } }.start(); try { int waited = 0; while (!responded && (waited < timeout)) { sleep(100); if (!responded) { waited += 100; } } } catch (InterruptedException e) { } // do nothing finally { if (!responded) { handler.sendEmptyMessage(0); } else { handler.sendEmptyMessage(1); } } } }.start(); }
From source file:org.videolan.vlc.media.MediaLibrary.java
private void notifyMediaUpdated() { // update the video and audio activities for (int i = 0; i < mUpdateHandler.size(); i++) { Handler h = mUpdateHandler.get(i); h.sendEmptyMessage(0); }// www . jav a2 s .c om }
From source file:io.github.mkjung.ivi.media.MediaLibrary.java
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); }/*from ww w . j a v a 2 s . co m*/ }
From source file:net.carlh.toast.Client.java
public void start(final String hostName, final int port) throws java.net.UnknownHostException, java.io.IOException { /* Thread to read stuff from the server */ readThread = new Thread(new Runnable() { private byte[] getData(Socket socket, int length) { byte[] d = new byte[length]; int offset = 0; while (offset < length) { try { int t = socket.getInputStream().read(d, offset, length - offset); if (t == -1) { break; }//w w w. j a v a2 s . c om offset += t; } catch (SocketException e) { /* This is probably because the socket has been closed in order to make this thread terminate. */ Log.e("Toast", "SocketException in client.getData", e); break; } catch (IOException e) { Log.e("Toast", "IOException in Client.getData()", e); break; } } return java.util.Arrays.copyOf(d, offset); } public void run() { while (!stop.get()) { try { synchronized (mutex) { /* Connect */ socket = new Socket(hostName, port); socket.setSoTimeout(timeout); } /* Keep going until there is a problem on read */ while (true) { byte[] b = getData(socket, 4); if (b.length != 4) { break; } int length = ((b[0] & 0xff) << 24) | ((b[1] & 0xff) << 16) | ((b[2] & 0xff) << 8) | (b[3] & 0xff); if (length < 0 || length > (256 * 1024)) { /* Don't like the sound of that */ Log.e("Toast", "Strange length " + length); break; } byte[] d = getData(socket, length); if (d.length != length) { break; } try { handler(new JSONObject(new String(d))); } catch (JSONException e) { Log.e("Toast", "Exception " + e.toString()); } } synchronized (mutex) { /* Close the socket and go back round to connect again */ socket.close(); socket = null; } } catch (ConnectException e) { Log.e("Toast", "ConnectException"); } catch (UnknownHostException e) { Log.e("Toast", "UnknownHostException"); } catch (IOException e) { Log.e("Client", "IOException"); } finally { try { Thread.sleep(timeout); } catch (java.lang.InterruptedException e) { } } } } }); readThread.start(); /* Thread to send stuff to the server */ writeThread = new Thread(new Runnable() { public void run() { while (!stop.get()) { lock.lock(); try { while (toWrite.size() == 0 && !stop.get()) { writeCondition.await(); } } catch (InterruptedException e) { } finally { lock.unlock(); } String s = null; lock.lock(); if (toWrite.size() > 0) { s = toWrite.get(0); toWrite.remove(0); } lock.unlock(); synchronized (mutex) { try { if (socket != null && s != null) { socket.getOutputStream().write((s.length() >> 24) & 0xff); socket.getOutputStream().write((s.length() >> 16) & 0xff); socket.getOutputStream().write((s.length() >> 8) & 0xff); socket.getOutputStream().write((s.length() >> 0) & 0xff); socket.getOutputStream().write(s.getBytes()); } } catch (IOException e) { Log.e("Toast", "IOException in write"); } } } } }); writeThread.start(); /* Thread to send pings every so often */ pingThread = new Thread(new Runnable() { public void run() { while (!stop.get()) { if (ping.get() == true && pong.get() == false) { for (Handler h : handlers) { h.sendEmptyMessage(0); } setConnected(false); } pong.set(false); try { JSONObject json = new JSONObject(); json.put("type", "ping"); send(json); ping.set(true); Thread.sleep(pingInterval); } catch (JSONException e) { } catch (InterruptedException e) { } } } }); pingThread.start(); }
From source file:org.mozilla.gecko.background.fxa.TestAccountLoader.java
/** * 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/*from w w w . j av a 2 s. co m*/ */ 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<AtomicReference<T>> queue = new ArrayBlockingQueue<AtomicReference<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(new AtomicReference<T>(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().get(); break; } catch (InterruptedException e) { throw new RuntimeException("waiting thread interrupted", e); } } return result; }
From source file:com.jerrellmardis.amphitheatre.task.GetFilesTask.java
@Override protected List<SmbFile> doInBackground(Void... params) { mConfig = ApiClient.getInstance().createTMDbClient().getConfig(); ArrayList<SmbFile> myFiles = new ArrayList<SmbFile>(DownloadTaskHelper.getFiles(mUser, mPassword, mPath)); if (myFiles.isEmpty()) { Handler h = new Handler(Looper.getMainLooper()) { @Override// w ww. j a va 2 s . co m public void handleMessage(Message msg) { super.handleMessage(msg); Toast.makeText(mContext, "Cannot find any files. Make sure your authentication information is correct.", Toast.LENGTH_SHORT).show(); } }; h.sendEmptyMessage(0); return new ArrayList<SmbFile>(); //Return empty set } else { return myFiles; } }
From source file:com.jerrellmardis.amphitheatre.task.DownloadTaskHelper.java
/** * This takes a video object from the database and updates parameters. If this does not * have good data, don't touch it. This runs on its own thread by default * @param video SugarRecord video object, the one that we want to update * @param dtl Listener for when the method finishes, so we can call refresh on the UI thread *//* w ww . j ava 2s . c om*/ public static void updateSingleVideo(final Video video, final DownloadTaskListener dtl) { //TODO Do a check for video's parent and if it is a nameless VOB, use the parent instead final Video original = video.clone(); new Thread(new Runnable() { @Override public void run() { try { Log.d(TAG, "Run video update"); Config config = ApiClient.getInstance().createTMDbClient().getConfig(); if (TextUtils.isEmpty(video.getVideoUrl()) || video.getName().toLowerCase().contains(Constants.SAMPLE)) { return; } Log.d(TAG, "Sending guess for " + video.getName()); Guess guess = GuessItClient.guess(video.getName()); Log.d(TAG, "Guess returns " + guess.toString()); if (guess == null) { Log.d(TAG, "There's nothing here for me"); return; } // if a guess is not found, search again using the parent directory's name if (guess != null && (TextUtils.isEmpty(guess.getTitle()) || guess.getTitle().equals(video.getName()))) { String[] sections = video.getVideoUrl().split("/"); String name = sections[sections.length - 2]; int indexOf = video.getVideoUrl().lastIndexOf("."); String ext = video.getVideoUrl().substring(indexOf, video.getVideoUrl().length()); //NO We're NOT going to be doing that. // Log.d(TAG, "Guess not found, use parent directory name: "+name+ext); // guess = GuessItClient.guess(name + ext); // Log.d(TAG, guess.toString()); } video.setCreated(video.getCreated()); Log.d(TAG, video.getName() + " => " + guess.toString()); //Don't update video and ragequit if (guess == null || (TextUtils.isEmpty(guess.getTitle()) && TextUtils.isEmpty(guess.getSeries()))) { Log.d(TAG, "There's nothing here for me"); return; } if (guess.getTitle().equals("0")) { /* This means the guess came back undefined If I decided to pursue with the movie request, it would apparently return with Tai Chi Zero as the title. This is not correct, so I cannot pursue with this request. */ Log.d(TAG, "There's nothing here for me"); return; } //Not rage quitting; plowing ahead video.setName(WordUtils.capitalizeFully(guess.getTitle())); // video.setVideoUrl(video.getVideoUrl()); video.setIsMovie(guess.getType().contains("movie")); if (!guess.getType().contains("movie")) { //tv logic if (!TextUtils.isEmpty(guess.getSeries())) { try { TvShow tvShow = null; Long tmdbId = null; // look for the TV show in the database first List<TvShow> tvShows = TvShow.find(TvShow.class, "original_name = ?", guess.getSeries()); // if a TV show is found, clone it. // if not, run a TMDb search for the TV show if (tvShows != null && !tvShows.isEmpty()) { tvShow = TvShow.copy(tvShows.get(0)); tmdbId = tvShow.getTmdbId(); } else { SearchResult result; result = ApiClient.getInstance().createTMDbClient() .findTvShow(guess.getSeries()); if (result == null) { result = ApiClient.getInstance().createTVDBClient() .findTvShow(guess.getSeries()); } if (result.getResults() != null && !result.getResults().isEmpty()) { tmdbId = result.getResults().get(0).getId(); tvShow = ApiClient.getInstance().createTMDbClient().getTvShow(tmdbId); if (tvShow == null) { tvShow = ApiClient.getInstance().createTVDBClient().getTvShow(tmdbId); } tvShow.setTmdbId(tmdbId); tvShow.setId(null); tvShow.setFlattenedGenres(StringUtils.join(tvShow.getGenres(), ",")); } } if (tmdbId != null) { // get the Episode information if (guess.getEpisodeNumber() != null && guess.getSeason() != null) { Episode episode; episode = ApiClient.getInstance().createTMDbClient().getEpisode( tvShow.getTmdbId(), guess.getSeason(), guess.getEpisodeNumber()); if (episode == null) { episode = ApiClient.getInstance().createTVDBClient() .getEpisode(tvShow.getId(), tvShow.getEpisode().getAirDate()); } if (episode != null) { if (!TextUtils.isEmpty(episode.getStillPath())) { String stillPathUrl = config.getImages().getBase_url() + "original" + episode.getStillPath(); episode.setStillPath(stillPathUrl); } episode.setTmdbId(tmdbId); episode.setId(null); episode.save(); tvShow.setEpisode(episode); video.setIsMatched(true); } } tvShow.save(); video.setName(tvShow.getOriginalName()); video.setOverview(tvShow.getOverview()); video.setTvShow(tvShow); video.setIsMatched(true); video.setDuration(30 * 60 * 1000); String cardImageUrl = config.getImages().getBase_url() + "original" + tvShow.getPosterPath(); video.setCardImageUrl(cardImageUrl); String bgImageUrl = config.getImages().getBase_url() + "original" + tvShow.getBackdropPath(); video.setBackgroundImageUrl(bgImageUrl); } } catch (Exception e) { //Too many requests, return in 30 seconds if (e.getMessage().contains("429")) { //Too many requests, return in 15+x seconds synchronized (this) { try { long wait = 1000 * 15 + Math.round(15000 * Math.random()); Log.d(TAG, "Delay " + original.getName() + " by " + wait + "s"); this.wait(wait); updateSingleVideo(original, dtl); } catch (Exception E2) { e.printStackTrace(); } } } else { Log.e(TAG, e.getMessage() + ""); e.printStackTrace(); } // return; } } video.save(); } else { //movie logic if (!TextUtils.isEmpty(guess.getTitle())) { try { // search for the movie SearchResult result = ApiClient.getInstance().createTMDbClient() .findMovie(guess.getTitle(), guess.getYear()); // if found, get the detailed info for the movie if (result.getResults() != null && !result.getResults().isEmpty()) { Long id = result.getResults().get(0).getId(); if (id != null) { Movie movie; movie = ApiClient.getInstance().createTMDbClient().getMovie(id); if (movie == null) { movie = ApiClient.getInstance().createTVDBClient().getMovie(id); } movie.setTmdbId(id); movie.setId(null); movie.setFlattenedGenres(StringUtils.join(movie.getGenres(), ",")); movie.setFlattenedProductionCompanies( StringUtils.join(movie.getProductionCompanies(), ",")); movie.save(); video.setOverview(movie.getOverview()); video.setName(movie.getTitle()); video.setIsMatched(true); video.setMovie(movie); if (movie != null) video.setDuration(movie.getRuntime()); } String cardImageUrl = config.getImages().getBase_url() + "original" + result.getResults().get(0).getPoster_path(); video.setCardImageUrl(cardImageUrl); String bgImageUrl = config.getImages().getBase_url() + "original" + result.getResults().get(0).getBackdrop_path(); video.setBackgroundImageUrl(bgImageUrl); } } catch (Exception e) { if (e.getMessage().contains("429")) { //Too many requests, return in 15+x seconds synchronized (this) { try { long wait = 1000 * 15 + Math.round(15000 * Math.random()); Log.d(TAG, "Delay " + original.getName() + " by " + wait + "s"); this.wait(wait); updateSingleVideo(original, dtl); } catch (Exception E2) { e.printStackTrace(); } } } else { Log.e(TAG, e.getMessage() + ""); e.printStackTrace(); } // return; } } video.save(); } Log.d("amp:DownloadTaskHelper", video.toString()); Handler h = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.d(TAG, "Updated video info: " + video.toString()); if (dtl != null) dtl.onDownloadFinished(); } }; h.sendEmptyMessage(0); } catch (Exception e) { /* 8510-9779/com.jerrellmardis.amphitheatre.dev E/AndroidRuntime? FATAL EXCEPTION: Thread-3591 Process: com.jerrellmardis.amphitheatre.dev, PID: 8510 retrofit.RetrofitError: 429 */ // Log.e(TAG, e.getMessage()); if (e.getMessage().contains("429")) { //Too many requests, return in 30 seconds synchronized (this) { try { long wait = 1000 * 15 + Math.round(15000 * Math.random()); Log.d(TAG, "Delay " + original.getName() + " by " + wait + "s"); this.wait(wait); updateSingleVideo(original, dtl); } catch (Exception E2) { e.printStackTrace(); } } } else { Log.e(TAG, "Ran into error " + e.getMessage()); } // return; } } }).start(); }
From source file:com.cr_wd.android.network.HttpClient.java
/** * Cancels a request by Id/*from w w w . j a v a2 s. co m*/ * * @param requestId * the request id * @return True if the cancel message was sent. Does not indicate that * message was actually processed before the request finished, thus * not all requests will actually be canceled. */ public boolean cancel(final int requestId) { try { if (requests.containsKey(requestId)) { final WeakReference<Handler> wr = requests.get(requestId); final Handler h = wr.get(); if (h != null) { h.sendEmptyMessage(HttpHandler.MESSAGE_CANCEL); return true; } } } catch (final Exception e) { Log.w(TAG, e.getMessage()); } return false; }
From source file:com.frostwire.android.gui.adapters.menu.FileListAdapter.java
@Override protected MenuAdapter getMenuAdapter(View view) { Handler h = new Handler(Looper.getMainLooper()); h.sendEmptyMessage(5011105); Context context = getContext(); List<MenuAction> items = new ArrayList<>(); // due to long click generic handle FileDescriptor fd = null;/*w w w . ja v a2s . com*/ if (view.getTag() instanceof FileDescriptorItem) { FileDescriptorItem item = (FileDescriptorItem) view.getTag(); fd = item.fd; } else if (view.getTag() instanceof FileDescriptor) { fd = (FileDescriptor) view.getTag(); } if (checkIfNotExists(fd)) { return null; } List<FileDescriptor> checked = convertItems(getChecked()); ensureCorrectMimeType(fd); boolean canOpenFile = fd.mime != null && (fd.mime.contains("audio") || fd.mime.contains("bittorrent") || fd.filePath != null); int numChecked = checked.size(); boolean showSingleOptions = showSingleOptions(checked, fd); if (TransferManager.canSeedFromMyFilesTempHACK()) { if (showSingleOptions) { items.add(new SeedAction(context, fd)); } else { items.add(new SeedAction(context, checked)); } } if (showSingleOptions) { if (canOpenFile) { items.add(new OpenMenuAction(context, fd.filePath, fd.mime)); } if ((fd.fileType == Constants.FILE_TYPE_RINGTONES || fd.fileType == Constants.FILE_TYPE_AUDIO) && numChecked <= 1) { items.add(new SetAsRingtoneMenuAction(context, fd)); } if (fd.fileType == Constants.FILE_TYPE_PICTURES && numChecked <= 1) { items.add(new SetAsWallpaperMenuAction(context, fd)); } if (fd.fileType != Constants.FILE_TYPE_APPLICATIONS && numChecked <= 1) { items.add(new RenameFileMenuAction(context, this, fd)); } if (fd.mime != null && fd.mime.equals(Constants.MIME_TYPE_BITTORRENT) && numChecked <= 1) { items.add(new CopyToClipboardMenuAction(context, R.drawable.contextmenu_icon_magnet, R.string.transfers_context_menu_copy_magnet, R.string.transfers_context_menu_copy_magnet_copied, new MagnetUriBuilder(fd.filePath).getMagnet())); items.add(new CopyToClipboardMenuAction(context, R.drawable.contextmenu_icon_copy, R.string.transfers_context_menu_copy_infohash, R.string.transfers_context_menu_copy_infohash_copied, new InfoHashBuilder(fd.filePath))); } } List<FileDescriptor> list = checked; if (list.size() == 0) { list = Arrays.asList(fd); } if (fd.fileType == Constants.FILE_TYPE_AUDIO) { items.add(new AddToPlaylistMenuAction(context, list)); } if (fd.fileType != Constants.FILE_TYPE_APPLICATIONS) { items.add(new SendFileMenuAction(context, fd)); items.add(new DeleteFileMenuAction(context, this, list)); } return new MenuAdapter(context, fd.title, items); }