List of usage examples for android.os Looper getMainLooper
public static Looper getMainLooper()
From source file:com.example.android.threadsample.PhotoManager.java
/** * Constructs the work queues and thread pools used to download and decode images. *//*from w ww . j a va 2 s . c o m*/ private PhotoManager() { /* * Creates a work queue for the pool of Thread objects used for downloading, using a linked * list queue that blocks when the queue is empty. */ mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the pool of Thread objects used for decoding, using a linked * list queue that blocks when the queue is empty. */ mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the set of of task objects that control downloading and * decoding, using a linked list queue that blocks when the queue is empty. */ mPhotoTaskWorkQueue = new LinkedBlockingQueue<PhotoTask>(); /* * Creates a new pool of Thread objects for the download work queue */ mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue); /* * Creates a new pool of Thread objects for the decoding work queue */ mDecodeThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); // Instantiates a new cache based on the cache size estimate mPhotoCache = new LruCache<URL, byte[]>(IMAGE_CACHE_SIZE) { /* * This overrides the default sizeOf() implementation to return the * correct size of each cache entry. */ @Override protected int sizeOf(URL paramURL, byte[] paramArrayOfByte) { return paramArrayOfByte.length; } }; /* * Instantiates a new anonymous Handler object and defines its * handleMessage() method. The Handler *must* run on the UI thread, because it moves photo * Bitmaps from the PhotoTask object to the View object. * To force the Handler to run on the UI thread, it's defined as part of the PhotoManager * constructor. The constructor is invoked when the class is first referenced, and that * happens when the View invokes startDownload. Since the View runs on the UI Thread, so * does the constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when the * Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Sets an PhotoView that's a weak reference to the // input ImageView PhotoView localView = photoTask.getPhotoView(); // If this input view isn't null if (localView != null) { /* * Gets the URL of the *weak reference* to the input * ImageView. The weak reference won't have changed, even if * the input ImageView has. */ URL localURL = localView.getLocation(); /* * Compares the URL of the input ImageView to the URL of the * weak reference. Only updates the bitmap in the ImageView * if this particular Thread is supposed to be serving the * ImageView. */ if (photoTask.getImageURL() == localURL) /* * Chooses the action to take, based on the incoming message */ switch (inputMessage.what) { // If the download has started, sets background color to dark green case DOWNLOAD_STARTED: localView.setStatusResource(R.drawable.imagedownloading); break; /* * If the download is complete, but the decode is waiting, sets the * background color to golden yellow */ case DOWNLOAD_COMPLETE: // Sets background color to golden yellow localView.setStatusResource(R.drawable.decodequeued); break; // If the decode has started, sets background color to orange case DECODE_STARTED: localView.setStatusResource(R.drawable.decodedecoding); break; /* * The decoding is done, so this sets the * ImageView's bitmap to the bitmap in the * incoming message */ case TASK_COMPLETE: localView.setImageBitmap(photoTask.getImage()); recycleTask(photoTask); break; // The download failed, sets the background color to dark red case DOWNLOAD_FAILED: localView.setStatusResource(R.drawable.imagedownloadfailed); // Attempts to re-use the Task object recycleTask(photoTask); break; default: // Otherwise, calls the super method super.handleMessage(inputMessage); } } } }; }
From source file:org.tomahawk.libtomahawk.resolver.ScriptResolver.java
/** * Construct a new {@link ScriptResolver} * * @param metaData this resolver's metadata (parsed from metadata.json) * @param path {@link String} containing the path to this js resolver's "content"-folder *//*from ww w . ja v a 2 s . c o m*/ public ScriptResolver(ScriptResolverMetaData metaData, String path, OnResolverReadyListener onResolverReadyListener) { super(metaData.name, onResolverReadyListener); mObjectMapper = InfoSystemUtils.getObjectMapper(); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(TomahawkApp.getContext()); mMetaData = metaData; if (mMetaData.staticCapabilities != null) { for (String capability : mMetaData.staticCapabilities) { if (capability.equals("configTestable")) { mConfigTestable = true; } } } mPath = path; mReady = false; mStopped = true; mId = mMetaData.pluginName; mIconPath = "file:///android_asset/" + path + "/" + mMetaData.manifest.icon; if (getConfig().get(ENABLED_KEY) != null) { mEnabled = (Boolean) getConfig().get(ENABLED_KEY); } else { if (TomahawkApp.PLUGINNAME_JAMENDO.equals(mId) || TomahawkApp.PLUGINNAME_OFFICIALFM.equals(mId) || TomahawkApp.PLUGINNAME_SOUNDCLOUD.equals(mId)) { setEnabled(true); } else { setEnabled(false); } } mFuzzyIndexPath = TomahawkApp.getContext().getFilesDir().getAbsolutePath() + File.separator + getId() + ".lucene"; FuzzyIndex fuzzyIndex = new FuzzyIndex(); if (fuzzyIndex.create(mFuzzyIndexPath, false)) { Log.d(TAG, "Found a fuzzy index at: " + mFuzzyIndexPath); mFuzzyIndex = fuzzyIndex; } else { Log.d(TAG, "Didn't find a fuzzy index"); } new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { //pre-initalize WebView getWebView(); } }); }
From source file:com.nextgis.maplibui.service.LayerFillService.java
@Override public void onCreate() { mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Bitmap largeIcon = NotificationHelper.getLargeIcon(R.drawable.ic_notification_download, getResources()); mProgressIntent = new Intent(ACTION_UPDATE); Intent intent = new Intent(this, LayerFillService.class); intent.setAction(ACTION_STOP);/*from w w w. j a v a2s.c om*/ PendingIntent stopService = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); intent.setAction(ACTION_SHOW); PendingIntent showProgressDialog = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder = new NotificationCompat.Builder(this); mBuilder.setSmallIcon(R.drawable.ic_notification_download).setLargeIcon(largeIcon).setAutoCancel(false) .setOngoing(true).setContentIntent(showProgressDialog) .addAction(R.drawable.ic_action_cancel_dark, getString(R.string.tracks_stop), stopService); mIsCanceled = false; mQueue = new LinkedList<>(); mIsRunning = false; mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle resultData = msg.getData(); Toast.makeText(LayerFillService.this, resultData.getString(BUNDLE_MSG_KEY), Toast.LENGTH_LONG) .show(); } }; }
From source file:com.digium.respokesdk.RespokeDirectConnection.java
public void onStateChange() { switch (dataChannel.state()) { case CONNECTING: break;/*from ww w.j a v a 2s . c om*/ case OPEN: { if (null != callReference) { RespokeCall call = callReference.get(); if (null != call) { call.directConnectionDidOpen(this); } } new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { if (null != listenerReference) { Listener listener = listenerReference.get(); if (null != listener) { listener.onOpen(RespokeDirectConnection.this); } } } }); } break; case CLOSING: break; case CLOSED: { if (null != callReference) { RespokeCall call = callReference.get(); if (null != call) { call.directConnectionDidClose(this); } } new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { if (null != listenerReference) { Listener listener = listenerReference.get(); if (null != listener) { listener.onClose(RespokeDirectConnection.this); } } } }); } break; } }
From source file:com.example.hotnewsapp.imageutil.PhotoManager.java
/** * Constructs the work queues and thread pools used to download and decode * images.// w ww . ja va 2 s .c om */ private PhotoManager() { /* * Creates a work queue for the pool of Thread objects used for * downloading, using a linked list queue that blocks when the queue is * empty. */ mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the pool of Thread objects used for * decoding, using a linked list queue that blocks when the queue is * empty. */ mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the set of of task objects that control * downloading and decoding, using a linked list queue that blocks when * the queue is empty. */ mPhotoTaskWorkQueue = new LinkedBlockingQueue<PhotoTask>(); /* * Creates a new pool of Thread objects for the download work queue */ mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue); /* * Creates a new pool of Thread objects for the decoding work queue */ mDecodeThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); // Instantiates a new cache based on the cache size estimate mPhotoCache = new LruCache<URL, byte[]>(IMAGE_CACHE_SIZE) { /* * This overrides the default sizeOf() implementation to return the * correct size of each cache entry. */ @Override protected int sizeOf(URL paramURL, byte[] paramArrayOfByte) { return paramArrayOfByte.length; } }; /* * Instantiates a new anonymous Handler object and defines its * handleMessage() method. The Handler *must* run on the UI thread, * because it moves photo Bitmaps from the PhotoTask object to the View * object. To force the Handler to run on the UI thread, it's defined as * part of the PhotoManager constructor. The constructor is invoked when * the class is first referenced, and that happens when the View invokes * startDownload. Since the View runs on the UI Thread, so does the * constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when the * Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Sets an PhotoView that's a weak reference to the // input ImageView PhotoView localView = photoTask.getPhotoView(); // If this input view isn't null if (localView != null) { /* * Gets the URL of the *weak reference* to the input * ImageView. The weak reference won't have changed, even if * the input ImageView has. */ URL localURL = localView.getLocation(); /* * Compares the URL of the input ImageView to the URL of the * weak reference. Only updates the bitmap in the ImageView * if this particular Thread is supposed to be serving the * ImageView. */ if (photoTask.getImageURL() == localURL) { /* * Chooses the action to take, based on the incoming * message */ switch (inputMessage.what) { // If the download has started, sets background color to // dark green case DOWNLOAD_STARTED: localView.setStatusResource(R.drawable.imagedownloading); break; /* * If the download is complete, but the decode is * waiting, sets the background color to golden yellow */ case DOWNLOAD_COMPLETE: // Sets background color to golden yellow localView.setStatusResource(R.drawable.decodequeued); break; // If the decode has started, sets background color to // orange case DECODE_STARTED: localView.setStatusResource(R.drawable.decodedecoding); break; /* * The decoding is done, so this sets the ImageView's * bitmap to the bitmap in the incoming message */ case TASK_COMPLETE: localView.setImageBitmap(photoTask.getImage()); recycleTask(photoTask); break; // The download failed, sets the background color to // dark red case DOWNLOAD_FAILED: localView.setStatusResource(R.drawable.imagedownloadfailed); // Attempts to re-use the Task object recycleTask(photoTask); break; default: // Otherwise, calls the super method super.handleMessage(inputMessage); } } } } }; }
From source file:com.phonegap.plugins.speech.XSpeechRecognizer.java
/** * Fire an intent to start the speech recognition activity. * * @param args Argument array with the following string args: [req code][number of matches] */// w ww. j a v a2 s. c om private void startSpeechRecognitionActivity(JSONArray args) { int maxMatches = 0; String language = Locale.getDefault().toString(); try { if (args.length() > 0) { // Maximum number of matches, 0 means the recognizer decides String temp = args.getString(0); maxMatches = Integer.parseInt(temp); } if (args.length() > 1) { // Language language = args.getString(1); } } catch (Exception e) { Log.e(TAG, String.format("startSpeechRecognitionActivity exception: %s", e.toString())); } // Create the intent and set parameters final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); // intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test"); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language); if (maxMatches > 0) intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxMatches); Handler loopHandler = new Handler(Looper.getMainLooper()); loopHandler.post(new Runnable() { @Override public void run() { recognizer.startListening(intent); } }); }
From source file:com.comic.lazyupload.image.PhotoManager.java
/** * Constructs the work queues and thread pools used to download and decode * images.// w ww .j a v a 2s.com */ private PhotoManager() { /* * Creates a work queue for the pool of Thread objects used for * downloading, using a linked list queue that blocks when the queue is * empty. */ mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the pool of Thread objects used for * decoding, using a linked list queue that blocks when the queue is * empty. */ mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the set of of task objects that control * downloading and decoding, using a linked list queue that blocks when * the queue is empty. */ mPhotoTaskWorkQueue = new LinkedBlockingQueue<PhotoTask>(); /* * Creates a new pool of Thread objects for the download work queue */ mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue); /* * Creates a new pool of Thread objects for the decoding work queue */ mDecodeThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); // Instantiates a new cache based on the cache size estimate mPhotoCache = new LruCache<URL, byte[]>(IMAGE_CACHE_SIZE) { /* * This overrides the default sizeOf() implementation to return the * correct size of each cache entry. */ @Override protected int sizeOf(URL paramURL, byte[] paramArrayOfByte) { return paramArrayOfByte.length; } }; /* * Instantiates a new anonymous Handler object and defines its * handleMessage() method. The Handler *must* run on the UI thread, * because it moves photo Bitmaps from the PhotoTask object to the View * object. To force the Handler to run on the UI thread, it's defined as * part of the PhotoManager constructor. The constructor is invoked when * the class is first referenced, and that happens when the View invokes * startDownload. Since the View runs on the UI Thread, so does the * constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when the * Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Sets an PhotoView that's a weak reference to the // input ImageView PhotoView localView = photoTask.getPhotoView(); // If this input view isn't null if (localView != null) { /* * Gets the URL of the *weak reference* to the input * ImageView. The weak reference won't have changed, even if * the input ImageView has. */ URL localURL = localView.getLocation(); /* * Compares the URL of the input ImageView to the URL of the * weak reference. Only updates the bitmap in the ImageView * if this particular Thread is supposed to be serving the * ImageView. */ int downloadingImageId = localView.getCustomDownloadingImage(); int failImageId = localView.getCustomFailImage(); if (photoTask.getImageURL() == localURL) /* * Chooses the action to take, based on the incoming * message */ switch (inputMessage.what) { // If the download has started, sets background color to // dark green case DOWNLOAD_STARTED: Loge.i("DOWNLOAD_STARTED"); localView.setStatusResource(downloadingImageId); break; /* * If the download is complete, but the decode is * waiting, sets the background color to golden yellow */ case DOWNLOAD_COMPLETE: // Sets background color to golden yellow Loge.i("DOWNLOAD_COMPLETE"); localView.setStatusResource(downloadingImageId); break; // If the decode has started, sets background color to // orange case DECODE_STARTED: Loge.i("DECODE_STARTED"); localView.setStatusResource(downloadingImageId); break; /* * The decoding is done, so this sets the ImageView's * bitmap to the bitmap in the incoming message */ case TASK_COMPLETE: Loge.i("TASK_COMPLETE"); localView.setImageBitmap(photoTask.getImage()); recycleTask(photoTask); break; // The download failed, sets the background color to // dark red case DOWNLOAD_FAILED: Loge.i("DOWNLOAD_FAILED"); localView.setStatusResource(downloadingImageId); // Attempts to re-use the Task object recycleTask(photoTask); break; default: // Otherwise, calls the super method super.handleMessage(inputMessage); } } } }; }
From source file:me.willowcheng.makerthings.core.OpenHABVoiceService.java
/** * Displays the given message as a toast * * @param message The message to be displayed. *//*w w w . jav a2 s . co m*/ private void showToast(final String message) { // Display toast on main looper because OpenHABVoiceService might be destroyed // before to toast has finished displaying new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); } }); }
From source file:com.microsoft.rightsmanagement.sampleapp.TextEditorFragment.java
/** * Sets the text view text.//from ww w.ja va2 s . co m * * @param decryptedContent the new text view text */ public void setTextViewText(final String decryptedContent) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { mTextEditor.setText(decryptedContent); } }); }
From source file:com.example.david.wheretogo_test1.PickerActivity.java
@Override protected void onStart() { super.onStart(); if (FRIEND_PICKER.equals(getIntent().getData())) { try {/*from ww w. j a v a2 s . co m*/ friendPickerFragment.loadData(false); } catch (Exception ex) { onError(ex); } } else if (PLACE_PICKER.equals(getIntent().getData())) { try { Location location = null; Criteria criteria = new Criteria(); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String bestProvider = locationManager.getBestProvider(criteria, false); if (bestProvider != null) { location = locationManager.getLastKnownLocation(bestProvider); if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) { locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { boolean updateLocation = true; Location prevLocation = placePickerFragment.getLocation(); if (prevLocation != null) { updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD; } if (updateLocation) { placePickerFragment.setLocation(location); placePickerFragment.loadData(true); } } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD, locationListener, Looper.getMainLooper()); } } if (location == null) { String model = Build.MODEL; if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) { // this may be the emulator, pretend we're in an exotic place location = SAN_FRANCISCO_LOCATION; } } if (location != null) { placePickerFragment.setLocation(location); placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS); placePickerFragment.setSearchText(SEARCH_TEXT); placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT); placePickerFragment.loadData(false); } else { onError(getResources().getString(R.string.no_location_error), true); } } catch (Exception ex) { onError(ex); } } }