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.scvngr.levelup.core.test.TestThreadingUtils.java

/**
 * Runs a runnable on the main thread, but also catches any errors thrown on the main thread and
 * re-throws them on the test thread so they can be displayed more easily.
 *
 * @param instrumentation the {@link Instrumentation} for the test.
 * @param activity the {@link Activity} that this this test is running in.
 * @param runnable the runnable to run.//  w w  w .  j  av a2 s  .  com
 */
public static void runOnMainSync(@NonNull final Instrumentation instrumentation,
        @NonNull final Activity activity, @NonNull final Runnable runnable) {
    if (activity.getMainLooper().equals(Looper.myLooper())) {
        runnable.run();
    } else {
        final FutureAssertionError futureError = new FutureAssertionError();
        instrumentation.runOnMainSync(new Runnable() {

            @Override
            public void run() {
                try {
                    runnable.run();
                } catch (final AssertionError e) {
                    futureError.setAssertionError(e);
                }
            }
        });
        futureError.throwPendingAssertionError();

        instrumentation.waitForIdleSync();
    }
}

From source file:com.rxsampleapp.RxApiTestActivity.java

public void createAnUserJSONObject(View view) {
    JSONObject jsonObject = new JSONObject();
    try {//  w  w  w. ja  va2s  . com
        jsonObject.put("firstname", "Rohit");
        jsonObject.put("lastname", "Kumar");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    RxAndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER)
            .addJSONObjectBody(jsonObject).build().setAnalyticsListener(new AnalyticsListener() {
                @Override
                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);
                }
            }).getJSONObjectObservable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<JSONObject>() {
                @Override
                public void onCompleted() {
                    Log.d(TAG, "onComplete Detail : createAnUserJSONObject 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.google.android.exoplayer2.ext.mediasession.MediaSessionConnector.java

/**
 * Creates an instance. Must be called on the same thread that is used to construct the player
 * instances passed to {@link #setPlayer(Player, PlaybackPreparer, CustomActionProvider...)}.
 *
 * @param mediaSession The {@link MediaSessionCompat} to connect to.
 * @param playbackController A {@link PlaybackController} for handling playback actions, or
 *     {@code null} if the connector should handle playback actions directly.
 * @param doMaintainMetadata Whether the connector should maintain the metadata of the session. If
 *     {@code false}, you need to maintain the metadata of the media session yourself (provide at
 *     least the duration to allow clients to show a progress bar).
 *///from   w ww  .ja v  a 2 s .co  m
public MediaSessionConnector(MediaSessionCompat mediaSession, PlaybackController playbackController,
        boolean doMaintainMetadata) {
    this.mediaSession = mediaSession;
    this.playbackController = playbackController != null ? playbackController : new DefaultPlaybackController();
    this.handler = new Handler(Looper.myLooper() != null ? Looper.myLooper() : Looper.getMainLooper());
    this.doMaintainMetadata = doMaintainMetadata;
    mediaSession.setFlags(BASE_MEDIA_SESSION_FLAGS);
    mediaController = mediaSession.getController();
    mediaSessionCallback = new MediaSessionCallback();
    exoPlayerEventListener = new ExoPlayerEventListener();
    customActionMap = Collections.emptyMap();
    commandMap = new HashMap<>();
    registerCommandReceiver(playbackController);
}

From source file:com.therealjoshua.essentials.bitmaploader.BitmapLoader.java

/**
 * Convenience method to clear the disk cache. If this is called from the UI thread, 
 * the process will automatically run in a separate thread. If it's already in a non-UI thread
 * the process will be synchronous. /*from  w ww . ja v a2 s.c o  m*/
 */
public void clearDiskCache() {
    if (diskCache == null)
        return;
    if (Looper.myLooper() == Looper.getMainLooper()) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                diskCache.clear();
                return null;
            }
        }.execute();
    }

    // if on a BG thread
    else {
        diskCache.clear();
    }
}

From source file:com.networking.ApiTestActivity.java

public void downloadFile(final View view) {
    String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP";
    AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip")
            .setPriority(Priority.HIGH).setTag(this).build().setAnalyticsListener(new AnalyticsListener() {
                @Override/*  w w  w. j a v  a 2  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);
                }
            }).setDownloadProgressListener(new DownloadProgressListener() {
                @Override
                public void onProgress(long bytesDownloaded, long totalBytes) {
                    Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes);
                    Log.d(TAG, "setDownloadProgressListener isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }
            }).startDownload(new DownloadListener() {
                @Override
                public void onDownloadComplete() {
                    Log.d(TAG, "File download Completed");
                    Log.d(TAG, "onDownloadComplete 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 an 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.facebook.notifications.NotificationsManager.java

/**
 * Present a {@link Notification} to be presented from a GCM push bundle.
 * <p/>/*from ww  w  .  j  a  va 2 s. co  m*/
 * This does not present a notification immediately, instead it caches the assets from the
 * notification bundle, and then presents a notification to the user. This allows for a smoother
 * interaction without loading indicators for the user.
 * <p/>
 * Note that only one notification can be created for a specific push bundle, should you attempt
 * to present a new notification with the same payload bundle as an existing notification, it will
 * replace and update the old notification.
 *
 * @param context              The context to send the notification from
 * @param notificationBundle   The content of the push notification
 * @param launcherIntent       The launcher intent that contains your Application's activity.
 *                             This will be modified with the FLAG_ACTIVITY_CLEAR_TOP and
 *                             FLAG_ACTIVITY_SINGLE_TOP flags, in order to properly show the
 *                             notification in an already running application.
 *                             <p/>
 *                             Should you not want this behavior, you may use the notificationExtender
 *                             parameter to customize the contentIntent of the notification before
 *                             presenting it.
 * @param notificationExtender A nullable argument that allows you to customize the notification
 *                             before displaying it. Use this to configure Icons, text, sounds,
 *                             etc. before we pass the notification off to the OS.
 */
public static boolean presentNotification(@NonNull final Context context,
        @NonNull final Bundle notificationBundle, @NonNull final Intent launcherIntent,
        @Nullable final NotificationExtender notificationExtender) {
    final JSONObject alert;
    final int payloadHash;

    try {
        String payload = notificationBundle.getString(CARD_PAYLOAD_KEY);
        if (payload == null) {
            return false;
        }
        payloadHash = payload.hashCode();

        JSONObject payloadObject = new JSONObject(payload);
        alert = payloadObject.optJSONObject("alert") != null ? payloadObject.optJSONObject("alert")
                : new JSONObject();
    } catch (JSONException ex) {
        Log.e(LOG_TAG, "Error while parsing notification bundle JSON", ex);
        return false;
    }

    final boolean[] success = new boolean[1];

    final Thread backgroundThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            prepareCard(context, notificationBundle, new PrepareCallback() {
                @Override
                public void onPrepared(@NonNull Intent presentationIntent) {
                    Intent contentIntent = new Intent(launcherIntent);
                    contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    contentIntent.putExtra(EXTRA_PAYLOAD_INTENT, presentationIntent);

                    NotificationManager manager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    Notification.Builder builder = new Notification.Builder(context)
                            .setSmallIcon(android.R.drawable.ic_dialog_alert)
                            .setContentTitle(alert.optString("title")).setContentText(alert.optString("body"))
                            .setAutoCancel(true)
                            .setContentIntent(PendingIntent.getActivity(context.getApplicationContext(),
                                    payloadHash, contentIntent, PendingIntent.FLAG_ONE_SHOT));

                    if (notificationExtender != null) {
                        builder = notificationExtender.extendNotification(builder);
                    }

                    manager.notify(NOTIFICATION_TAG, payloadHash, builder.getNotification());
                    success[0] = true;
                    Looper.myLooper().quit();
                }

                @Override
                public void onError(@NonNull Exception exception) {
                    Log.e(LOG_TAG, "Error while preparing card", exception);
                    Looper.myLooper().quit();
                }
            });

            Looper.loop();
        }
    });

    backgroundThread.start();

    try {
        backgroundThread.join();
    } catch (InterruptedException ex) {
        Log.e(LOG_TAG, "Failed to wait for background thread", ex);
        return false;
    }
    return success[0];
}

From source file:com.barbrdo.app.activities.SignUpActivity.java

private void startLocationUpdates() {
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
            .addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
                @Override//  w  ww .j a v a2  s .c  om
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    Log.i(TAG, "All location settings are satisfied.");

                    //noinspection MissingPermission
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback,
                            Looper.myLooper());

                }
            }).addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade "
                                + "location settings ");
                        try {
                            ResolvableApiException rae = (ResolvableApiException) e;
                            rae.startResolutionForResult(SignUpActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException sie) {
                            Log.i(TAG, "PendingIntent unable to execute request.");
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        String errorMessage = "Location settings are inadequate, and cannot be "
                                + "fixed here. Fix in Settings.";
                        Log.e(TAG, errorMessage);
                        Toast.makeText(SignUpActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                        mRequestingLocationUpdates = false;
                    }
                }
            });
}

From source file:org.gdg.frisbee.android.cache.ModelCache.java

private static void checkNotOnMainThread() {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        throw new IllegalStateException("This method should not be called from the main/UI thread.");
    }/*  w  w w  . j  a  v a  2  s  . com*/
}

From source file:com.rxsampleapp.RxApiTestActivity.java

public void downloadFile(final View view) {
    String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP";
    RxAndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip").build()
            .setAnalyticsListener(new AnalyticsListener() {
                @Override/*from  w  w w. j av a  2s  .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);
                }
            }).setDownloadProgressListener(new DownloadProgressListener() {
                @Override
                public void onProgress(long bytesDownloaded, long totalBytes) {
                    Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes);
                    Log.d(TAG, "setDownloadProgressListener isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }
            }).getDownloadObservable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<String>() {
                @Override
                public void onCompleted() {
                    Log.d(TAG, "File download Completed");
                    Log.d(TAG, "onDownloadComplete isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }

                @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(String s) {
                    Log.d(TAG, "onNext : " + s);
                }
            });
}

From source file:com.android.volley.toolbox.ImageLoader.java

private void throwIfNotOnMainThread() {
    if (Looper.myLooper() != Looper.getMainLooper()) {
        throw new IllegalStateException("ImageLoader must be invoked from the main thread.");
    }//w  w w . jav  a 2  s .c  om
}