Example usage for android.os Looper myLooper

List of usage examples for android.os Looper myLooper

Introduction

In this page you can find the example usage for android.os Looper myLooper.

Prototype

public static @Nullable Looper myLooper() 

Source Link

Document

Return the Looper object associated with the current thread.

Usage

From source file:com.networking.ApiTestActivity.java

public void createAnUser(View view) {
    AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER)
            .addBodyParameter("firstname", "Suman").addBodyParameter("lastname", "Shekhar").setTag(this)
            .setPriority(Priority.LOW).build().setAnalyticsListener(new AnalyticsListener() {
                @Override//from  w ww  .  j av a 2s.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);
                }
            }).getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "onResponse object : " + response.toString());
                    Log.d(TAG, "onResponse isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }

                @Override
                public void onError(ANError error) {
                    if (error.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 : " + error.getErrorCode());
                        Log.d(TAG, "onError errorBody : " + error.getErrorBody());
                        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
                    } else {
                        // error.getErrorDetail() : connectionError, parseError, requestCancelledError
                        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
                    }
                }
            });
}

From source file:com.vk.sdk.api.VKRequest.java

/**
 * Starts loading of prepared request. You can use it instead of executeWithResultBlock
 *//*from   w w  w  .  j ava  2s  .com*/
public void start() {
    if ((mLoadingOperation = getOperation()) == null) {
        return;
    }
    mLooper = Looper.myLooper();
    VKHttpClient.enqueueOperation(mLoadingOperation);
}

From source file:com.networking.OkHttpResponseTestActivity.java

public void createAnUser(View view) {
    AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER)
            .addBodyParameter("firstname", "Suman").addBodyParameter("lastname", "Shekhar").setTag(this)
            .setPriority(Priority.LOW).build().setAnalyticsListener(new AnalyticsListener() {
                @Override/*from  w w  w  . j  a  v a  2 s .  c  o 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);
                }
            }).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.github.michalbednarski.intentslab.browser.ExtendedPackageInfo.java

public static void getAllPackageInfos(Context context, final AllCallback 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  a  va2 s .  co  m*/

    // Check for cached value
    if (sAllPackageInfos != null) {
        callback.onAllPackagesInfosAvailable(sAllPackageInfos);
        return;
    }

    // A closure...
    class L {
        int packagesToLoadLeft;
    }
    final L state = new L();

    // Get list of installed packages
    List<PackageInfo> installedPackages = context.getPackageManager().getInstalledPackages(0);
    state.packagesToLoadLeft = installedPackages.size();

    // Prepare result array
    final ExtendedPackageInfo[] allInfos = new ExtendedPackageInfo[installedPackages.size()];

    // Scan all packages
    int index = 0;
    for (PackageInfo installedPackage : installedPackages) {
        final int ii = index++;
        getExtendedPackageInfo(context, installedPackage.packageName, new Callback() {
            @Override
            public void onPackageInfoAvailable(ExtendedPackageInfo extendedPackageInfo) {
                // Fill in result array
                allInfos[ii] = extendedPackageInfo;

                // If all package infos are ready
                if (--state.packagesToLoadLeft == 0) {
                    // Save to cache
                    sAllPackageInfos = allInfos;

                    // Invoke callback
                    callback.onAllPackagesInfosAvailable(allInfos);
                }
            }
        });
    }
}

From source file:com.albedinsky.android.support.universi.UniversiActivity.java

/**
 * Requests performing of data binding specific for this activity via {@link #onBindData()}.
 * If this activity has its view hierarchy already created {@link #onBindData()} will be invoked
 * immediately, otherwise will wait until {@link #onContentChanged()} is invoked.
 * <p>/*from   ww  w .  j a  v  a  2 s  .  co m*/
 * <b>This method can be invoked from a background-thread</b>.
 */
protected void requestBindData() {
    // Check whether this call has been made on the UI thread, if not post on the UI thread the request runnable.
    if (Looper.getMainLooper().equals(Looper.myLooper())) {
        this.requestBindDataInner();
    } else {
        if (mRequestBindDataInner == null) {
            this.mRequestBindDataInner = new Runnable() {
                @Override
                public void run() {
                    requestBindDataInner();
                }
            };
        }
        runOnUiThread(mRequestBindDataInner);
    }
}

From source file:io.realm.Realm.java

/**
 * Set the auto-refresh status of the Realm instance.
 * <p>/* w  ww  .  j a  va 2 s .com*/
 * Auto-refresh is a feature that enables automatic update of the current Realm instance and all its derived objects
 * (RealmResults and RealmObjects instances) when a commit is performed on a Realm acting on the same file in another thread.
 * This feature is only available if the Realm instance lives is a {@link android.os.Looper} enabled thread.
 *
 * @param autoRefresh true will turn auto-refresh on, false will turn it off.
 * @throws java.lang.IllegalStateException if trying to enable auto-refresh in a thread without Looper.
 */
public void setAutoRefresh(boolean autoRefresh) {
    if (autoRefresh && Looper.myLooper() == null) {
        throw new IllegalStateException("Cannot set auto-refresh in a Thread without a Looper");
    }

    if (autoRefresh && !this.autoRefresh) { // Switch it on
        handler = new Handler(new RealmCallback());
        handlers.put(handler, configuration.getPath());
    } else if (!autoRefresh && this.autoRefresh && handler != null) { // Switch it off
        removeHandler(handler);
    }
    this.autoRefresh = autoRefresh;
}

From source file:com.honeywell.printer.net.autobaln_websocket.WebSocketWriter.java

/**
 * Process WebSockets or control message from master. Normally,
 * there should be no reason to override this. If you do, you
 * need to know what you are doing./*from ww w . j av  a  2 s.c  o  m*/
 *
 * @param msg     An instance of the message types within WebSocketMessage
 *                or a message that is handled in processAppMessage().
 */
protected void processMessage(Object msg) throws IOException, WebSocketException {

    if (msg instanceof WebSocketMessage.TextMessage) {
        sendTextMessage((WebSocketMessage.TextMessage) msg);
    } else if (msg instanceof WebSocketMessage.RawTextMessage) {
        sendRawTextMessage((WebSocketMessage.RawTextMessage) msg);
    } else if (msg instanceof WebSocketMessage.BinaryMessage) {
        sendBinaryMessage((WebSocketMessage.BinaryMessage) msg);
    } else if (msg instanceof WebSocketMessage.Ping) {
        sendPing((WebSocketMessage.Ping) msg);
    } else if (msg instanceof WebSocketMessage.Pong) {
        sendPong((WebSocketMessage.Pong) msg);
    } else if (msg instanceof WebSocketMessage.Close) {
        sendClose((WebSocketMessage.Close) msg);
    } else if (msg instanceof WebSocketMessage.ClientHandshake) {
        sendClientHandshake((WebSocketMessage.ClientHandshake) msg);
    } else if (msg instanceof WebSocketMessage.Quit) {
        Looper.myLooper().quit();

        Log.d(TAG, "WebSocket writer ended.");
    } else {
        processAppMessage(msg);
    }
}

From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java

@Override
protected void onDestroy() {
    super.onDestroy();

    mLastSegmentOverlay = null;/*w w w  .  j  a v  a 2  s  .c  o m*/
    mMapView.getOverlays().clear();
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            Looper.myLooper().quit();
        }
    });

    if (mWakeLock != null && mWakeLock.isHeld()) {
        mWakeLock.release();
        Log.w(this, "onDestroy(): Released lock to keep screen on!");
    }
    if (mLoggerServiceManager.getLoggingState() == ExternalConstants.STATE_STOPPED) {
        stopService(new Intent(this, GPSLoggerService.class));
    }
    mUnits = null;
}

From source file:com.example.android.wearable.runtimepermissions.MainPhoneActivity.java

private void logToUi(final String message) {

    boolean mainUiThread = (Looper.myLooper() == Looper.getMainLooper());

    if (mainUiThread) {

        if (!message.isEmpty()) {
            Log.d(TAG, message);/*from w ww . j a  v a2s.co  m*/
            mOutputTextView.setText(message);
        }

    } else {
        if (!message.isEmpty()) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Log.d(TAG, message);
                    mOutputTextView.setText(message);
                }
            });
        }
    }
}

From source file:github.popeen.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  v  a2  s .c o m

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            // We want to change audio session id's between upgrading Android versions.  Upgrading to Android 7.0 is broken (probably updated session id format)
            audioSessionId = -1;
            int id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            int versionCode = prefs.getInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, -1);
            if (versionCode == Build.VERSION.SDK_INT && id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    Log.w(TAG, "Failed to use cached audio session", e);
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();

                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId);
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, Build.VERSION.SDK_INT);
                    editor.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);
    audioNoisyReceiver = new AudioNoisyReceiver();
    registerReceiver(audioNoisyReceiver, audioNoisyIntent);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientBase.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);

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "downloadServiceLock");

    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();

    if (Build.VERSION.SDK_INT >= 26) {
        Notifications.shutGoogleUpNotification(this);
    }
}