List of usage examples for android.os Looper myLooper
public static @Nullable Looper myLooper()
From source file:com.rxsampleapp.RxApiTestActivity.java
public void checkForHeaderPost(View view) { RxANRequest.PostRequestBuilder postRequestBuilder = RxAndroidNetworking .post(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER); postRequestBuilder.addHeaders("token", "1234"); RxANRequest rxAnRequest = postRequestBuilder.setTag(this).build(); rxAnRequest.setAnalyticsListener(new AnalyticsListener() { @Override//from w ww. ja v a2 s. co m public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }); rxAnRequest.getJSONObjectObservable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<JSONObject>() { @Override public void onCompleted() { Log.d(TAG, "onComplete Detail : checkForHeaderPost completed"); } @Override public void onError(Throwable e) { if (e instanceof ANError) { ANError anError = (ANError) e; if (anError.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + anError.getErrorCode()); Log.d(TAG, "onError errorBody : " + anError.getErrorBody()); Log.d(TAG, "onError errorDetail : " + anError.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + anError.getErrorDetail()); } } else { Log.d(TAG, "onError errorMessage : " + e.getMessage()); } } @Override public void onNext(JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } }); }
From source file:com.networking.OkHttpResponseTestActivity.java
public void checkForHeaderPost(View view) { ANRequest.PostRequestBuilder postRequestBuilder = AndroidNetworking .post(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER); postRequestBuilder.addHeaders("token", "1234"); ANRequest anRequest = postRequestBuilder.setTag(this).setPriority(Priority.LOW) .setExecutor(Executors.newSingleThreadExecutor()).build(); anRequest.setAnalyticsListener(new AnalyticsListener() { @Override/*from ww w.ja v a2 s . com*/ public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }); anRequest.getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); }
From source file:com.example.levelup.core.app.PaymentCodeFragment.java
/** * Updates the views to show a given state. * /*from ww w .j a v a2 s . c o m*/ * @param uiState one of {@link #UI_STATE_LOADING}, {@link #UI_STATE_ERROR_MESSAGE}, or * {@link #UI_STATE_SHOWING_CODE}. */ private void setUiState(int uiState) { if (Looper.getMainLooper() != Looper.myLooper()) { throw new IllegalStateException("Must be called from main thread"); } int qrCodeVisibility; int progressVisibility; int errorMessageVisibility; switch (uiState) { case UI_STATE_LOADING: qrCodeVisibility = View.INVISIBLE; progressVisibility = View.VISIBLE; errorMessageVisibility = View.GONE; break; case UI_STATE_SHOWING_CODE: qrCodeVisibility = View.VISIBLE; progressVisibility = View.GONE; errorMessageVisibility = View.GONE; break; case UI_STATE_ERROR_MESSAGE: qrCodeVisibility = View.INVISIBLE; progressVisibility = View.GONE; errorMessageVisibility = View.VISIBLE; break; default: throw new IllegalArgumentException(); } View fragmentView = getView(); mCodeView.setVisibility(qrCodeVisibility); fragmentView.findViewById(R.id.progress).setVisibility(progressVisibility); fragmentView.findViewById(R.id.error_message).setVisibility(errorMessageVisibility); }
From source file:com.scvngr.levelup.core.ui.view.LevelUpCodeView.java
/** * <p>/*from w w w . j a v a2s. c om*/ * Sets the code that will be displayed. * </p> * <p> * This must be called on the UI thread. * </p> * * @param codeData the raw content to be displayed in the QR code. * @param codeLoader the loader by which to load the QR code. */ public void setLevelUpCode(@NonNull final String codeData, @NonNull final LevelUpCodeLoader codeLoader) { if (Looper.getMainLooper() != Looper.myLooper()) { throw new AssertionError("Must be called from the main thread."); } if (null == mCurrentData && mIsFadeColorsSet) { animateFadeColorsDelayed(); } if (codeData.equals(mCurrentData)) { final OnCodeLoadListener codeLoadListener = mOnCodeLoadListener; if (null != codeLoadListener) { if (null != mPendingImage && mPendingImage.isLoaded()) { codeLoadListener.onCodeLoad(false); } } return; } if (mPendingImage != null) { mPendingImage.cancelLoad(); } mCurrentData = codeData; /* * The current code needs to be cleared so that it isn't displayed while the new code is * loading. */ mCurrentCode = null; // Fake the loading flag so that cached results get a single isLoading(false) call. mPreviousIsCodeLoading = true; final PendingImage<LevelUpQrCodeImage> pendingImage = codeLoader.getLevelUpCode(codeData, mOnImageLoaded); mPendingImage = pendingImage; mPreviousIsCodeLoading = false; if (!pendingImage.isLoaded()) { callOnCodeLoadListener(true); // If the image is cached, invalidate() will be called from there. invalidate(); } }
From source file:com.smallzhi.autobahn.WebSocketConnection.java
/** * Create master message handler.//w w w . j a v a 2s . c o m */ protected void createHandler() { try { if (Looper.myLooper() != null) { return; } Looper.prepare(); mMasterHandler = new Handler(Looper.myLooper()) { public void handleMessage(Message msg) { if (msg.obj instanceof WebSocketMessage.TextMessage) { WebSocketMessage.TextMessage textMessage = (WebSocketMessage.TextMessage) msg.obj; if (mWsHandler != null) { mWsHandler.onTextMessage(textMessage.mPayload); } else { if (DEBUG) Log.d(TAG, "could not call onTextMessage() .. handler already NULL"); } } else if (msg.obj instanceof WebSocketMessage.RawTextMessage) { WebSocketMessage.RawTextMessage rawTextMessage = (WebSocketMessage.RawTextMessage) msg.obj; if (mWsHandler != null) { mWsHandler.onRawTextMessage(rawTextMessage.mPayload); } else { if (DEBUG) Log.d(TAG, "could not call onRawTextMessage() .. handler already NULL"); } } else if (msg.obj instanceof WebSocketMessage.BinaryMessage) { WebSocketMessage.BinaryMessage binaryMessage = (WebSocketMessage.BinaryMessage) msg.obj; if (mWsHandler != null) { mWsHandler.onBinaryMessage(binaryMessage.mPayload); } else { if (DEBUG) Log.d(TAG, "could not call onBinaryMessage() .. handler already NULL"); } } else if (msg.obj instanceof WebSocketMessage.Ping) { WebSocketMessage.Ping ping = (WebSocketMessage.Ping) msg.obj; if (DEBUG) Log.d(TAG, "WebSockets Ping received"); // reply with Pong WebSocketMessage.Pong pong = new WebSocketMessage.Pong(); pong.mPayload = ping.mPayload; mWriter.forward(pong); } else if (msg.obj instanceof WebSocketMessage.Pong) { @SuppressWarnings("unused") WebSocketMessage.Pong pong = (WebSocketMessage.Pong) msg.obj; if (DEBUG) Log.d(TAG, "WebSockets Pong received"); } else if (msg.obj instanceof WebSocketMessage.Close) { WebSocketMessage.Close close = (WebSocketMessage.Close) msg.obj; if (DEBUG) Log.d(TAG, "WebSockets Close received (" + close.mCode + " - " + close.mReason + ")"); mWriter.forward(new WebSocketMessage.Close(1000)); } else if (msg.obj instanceof WebSocketMessage.ServerHandshake) { WebSocketMessage.ServerHandshake serverHandshake = (WebSocketMessage.ServerHandshake) msg.obj; if (DEBUG) Log.d(TAG, "opening handshake received"); if (serverHandshake.mSuccess) { if (mWsHandler != null) { mWsHandler.onOpen(); } else { if (DEBUG) Log.d(TAG, "could not call onOpen() .. handler already NULL"); } } } else if (msg.obj instanceof WebSocketMessage.ConnectionLost) { @SuppressWarnings("unused") WebSocketMessage.ConnectionLost connnectionLost = (WebSocketMessage.ConnectionLost) msg.obj; failConnection(WebSocketConnectionHandler.CLOSE_CONNECTION_LOST, "WebSockets connection lost"); } else if (msg.obj instanceof WebSocketMessage.ProtocolViolation) { @SuppressWarnings("unused") WebSocketMessage.ProtocolViolation protocolViolation = (WebSocketMessage.ProtocolViolation) msg.obj; failConnection(WebSocketConnectionHandler.CLOSE_PROTOCOL_ERROR, "WebSockets protocol violation"); } else if (msg.obj instanceof WebSocketMessage.Error) { WebSocketMessage.Error error = (WebSocketMessage.Error) msg.obj; failConnection(WebSocketConnectionHandler.CLOSE_INTERNAL_ERROR, "WebSockets internal error (" + error.mException.toString() + ")"); } else if (msg.obj instanceof WebSocketMessage.ServerError) { WebSocketMessage.ServerError error = (WebSocketMessage.ServerError) msg.obj; failConnection(WebSocketConnectionHandler.CLOSE_SERVER_ERROR, "Server error " + error.mStatusCode + " (" + error.mStatusMessage + ")"); } else { processAppMessage(msg.obj); } } }; } catch (Exception e) { Log.d(TAG, "createHandler fail:==>>" + e.toString()); } }
From source file:com.github.michalbednarski.intentslab.browser.ExtendedPackageInfo.java
public static void getExtendedPackageInfo(Context context, String packageName, final Callback callback) { // Ensure this is called from main thread if (BuildConfig.DEBUG && Looper.myLooper() != Looper.getMainLooper()) { throw new AssertionError("getExtendedPackageInfo called off main thread"); }//from w w w. j av a 2s . c o m // Prepare cache purging PurgeCacheReceiver.registerIfNeeded(context); // Get from cache ExtendedPackageInfo info; info = sPackageCache.get(packageName); // Create new if not ready boolean createNew = info == null; if (createNew) { info = new ExtendedPackageInfo(packageName); sPackageCache.put(packageName, info); } // Invoke or schedule callback if (info.isReady()) { // Info is ready, invoke callback immediately callback.onPackageInfoAvailable(info); } else { // Schedule our callback to be invoked when scan is ready info.mRunWhenReadyList.add(callback); // If we just created object, initialize it's scan if (createNew) { (info.new ScanManifestTask(context)).execute(); } } }
From source file:github.daneren2005.dsub.service.DownloadService.java
@Override public void onCreate() { super.onCreate(); final SharedPreferences prefs = Util.getPreferences(this); new Thread(new Runnable() { public void run() { Looper.prepare();//from w w w. j a va 2 s. c om mediaPlayer = new MediaPlayer(); mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK); audioSessionId = -1; Integer id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1); if (id != -1) { try { audioSessionId = id; mediaPlayer.setAudioSessionId(audioSessionId); } catch (Throwable e) { audioSessionId = -1; } } if (audioSessionId == -1) { mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { audioSessionId = mediaPlayer.getAudioSessionId(); prefs.edit().putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId).commit(); } catch (Throwable t) { // Froyo or lower } } mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mediaPlayer, int what, int more) { handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")")); return false; } }); try { Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION); i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId); i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName()); sendBroadcast(i); } catch (Throwable e) { // Froyo or lower } effectsController = new AudioEffectsController(DownloadService.this, audioSessionId); if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) { getEqualizerController(); } mediaPlayerLooper = Looper.myLooper(); mediaPlayerHandler = new Handler(mediaPlayerLooper); if (runListenersOnInit) { onSongsChanged(); onSongProgress(); onStateUpdate(); } Looper.loop(); } }, "DownloadService").start(); Util.registerMediaButtonEventReceiver(this); if (mRemoteControl == null) { // Use the remote control APIs (if available) to set the playback state mRemoteControl = RemoteControlClientHelper.createInstance(); ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()); mRemoteControl.register(this, mediaButtonReceiverComponent); } PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName()); wakeLock.setReferenceCounted(false); try { timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5")); } catch (Throwable e) { timerDuration = 5; } sleepTimer = null; keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false); mediaRouter = new MediaRouteManager(this); instance = this; shufflePlayBuffer = new ShufflePlayBuffer(this); artistRadioBuffer = new ArtistRadioBuffer(this); lifecycleSupport.onCreate(); }
From source file:android.bus.EventBus.java
/** Posts the given event to the event bus. */ public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get(); List<Object> eventQueue = postingState.eventQueue; eventQueue.add(event);//from w w w.ja v a2 s . c om if (!postingState.isPosting) { postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper(); postingState.isPosting = true; if (postingState.canceled) { throw new EventBusException("Internal error. Abort state was not reset"); } try { while (!eventQueue.isEmpty()) { postSingleEvent(eventQueue.remove(0), postingState); } } finally { postingState.isPosting = false; postingState.isMainThread = false; } } }
From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java
@Override public void onConnected(@Nullable Bundle bundle) { Runnable runnable = new Runnable() { @Override/*from ww w .j av a 2s .co m*/ public void run() { try { requestTimestamp = System.currentTimeMillis(); SafetyNetApi.AttestationResult result = SafetyNet.SafetyNetApi.attest(googleApiClient, nonce) .await(); if (cancel) { return; } if (!result.getStatus().isSuccess()) { onError(RESPONSE_FAILED_ATTESTATION, "An error occurred while communicating with SafetyNet."); return; } try { SafetyNetResponse response = getSafetyNetResponseFromJws(result.getJwsResult()); SafetyNetVerification verification = verify(response); onFinished(response, verification); } catch (SafetyNetError e) { onError(RESPONSE_FAILED_PARSING_JWS, e.getLocalizedMessage()); } } catch (Exception e) { onError(UNKNOWN_ERROR, e.getLocalizedMessage()); } } }; if (Looper.getMainLooper() == Looper.myLooper()) { new Thread(runnable).start(); } else { runnable.run(); } }
From source file:de.qspool.clementineremote.backend.ClementinePlayerConnection.java
/** * Close the socket and the streams//from w w w. java 2 s .c o m */ private void closeConnection(ClementineMessage clementineMessage) { // Disconnect socket closeSocket(); // Cancel Notification mNotificationManager.cancel(App.NOTIFY_ID); unregisterRemoteControlClient(); App.mApp.unregisterReceiver(mMediaButtonBroadcastReceiver); mWakeLock.release(); sendUiMessage(clementineMessage); // Close thread Looper.myLooper().quit(); try { mIncomingThread.join(); Log.d(TAG, "joined!"); } catch (InterruptedException e) { e.printStackTrace(); } // Fire the listener fireOnConnectionClosed(clementineMessage); }