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.OkHttpResponseTestActivity.java

public void uploadImage(final View view) {
    AndroidNetworking.upload(ApiEndPoint.BASE_URL + ApiEndPoint.UPLOAD_IMAGE).setPriority(Priority.MEDIUM)
            .addMultipartFile("image",
                    new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.png"))
            .setTag(this).build().setAnalyticsListener(new AnalyticsListener() {
                @Override/* ww  w  . j  a v a 2s  .c om*/
                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);
                }
            }).setUploadProgressListener(new UploadProgressListener() {
                @Override
                public void onProgress(long bytesUploaded, long totalBytes) {
                    Log.d(TAG, "bytesUploaded : " + bytesUploaded + " totalBytes : " + totalBytes);
                    Log.d(TAG, "setUploadProgressListener isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }
            }).getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() {
                @Override
                public void onResponse(Response okHttpResponse, JSONObject response) {
                    Log.d(TAG, "Image upload Completed");
                    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.tcl.lzhang1.mymusic.MusicUtil.java

/**
 * ] is in main thread
 * 
 * @return
 */
public static boolean isMainThread() {
    return Looper.getMainLooper() == Looper.myLooper();
}

From source file:com.networking.ApiTestActivity.java

public void uploadImage(final View view) {
    AndroidNetworking.upload(ApiEndPoint.BASE_URL + ApiEndPoint.UPLOAD_IMAGE).setPriority(Priority.MEDIUM)
            .addMultipartFile("image",
                    new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.png"))
            .setTag(this).build().setAnalyticsListener(new AnalyticsListener() {
                @Override//from   ww  w .  jav  a2s  .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);
                }
            }).setUploadProgressListener(new UploadProgressListener() {
                @Override
                public void onProgress(long bytesUploaded, long totalBytes) {
                    Log.d(TAG, "bytesUploaded : " + bytesUploaded + " totalBytes : " + totalBytes);
                    Log.d(TAG, "setUploadProgressListener isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }
            }).getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "Image upload Completed");
                    Log.d(TAG, "onResponse object : " + response.toString());
                }

                @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:br.com.bioscada.apps.biotracks.TrackListActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;/*from  www.  j a  v a 2s .c o m*/
    switch (item.getItemId()) {
    case R.id.track_list_search:
        return ApiAdapterFactory.getApiAdapter().handleSearchMenuSelection(this);
    case R.id.track_list_start_gps:
        MyTracksLocationManager myTracksLocationManager = new MyTracksLocationManager(this, Looper.myLooper(),
                false);
        if (!myTracksLocationManager.isGpsProviderEnabled()) {
            intent = GoogleLocationUtils.newLocationSettingsIntent(TrackListActivity.this);
            startActivity(intent);
        } else {
            startGps = !TrackRecordingServiceConnectionUtils.isRecordingServiceRunning(this);

            // Show toast
            Toast toast = Toast.makeText(this, startGps ? R.string.gps_starting : R.string.gps_stopping,
                    Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();

            // Invoke trackRecordingService
            if (startGps) {
                trackRecordingServiceConnection.startAndBind();
                bindChangedCallback.run();
            } else {
                ITrackRecordingService trackRecordingService = trackRecordingServiceConnection
                        .getServiceIfBound();
                if (trackRecordingService != null) {
                    try {
                        trackRecordingService.stopGps();
                    } catch (RemoteException e) {
                        Log.e(TAG, "Unable to stop gps.", e);
                    }
                }
                trackRecordingServiceConnection.unbindAndStop();
            }

            // Update menu after starting or stopping gps
            ApiAdapterFactory.getApiAdapter().invalidMenu(this);
        }
        myTracksLocationManager.close();
        return true;
    case R.id.track_list_play_mutliple:
        PlayMultipleDialogFragment.newInstance(-1L).show(getSupportFragmentManager(),
                PlayMultipleDialogFragment.PLAY_MULTIPLE_DIALOG_TAG);
        return true;
    case R.id.track_list_sync_now:
        if (driveSync) {
            SyncUtils.syncNow(this);
        } else {
            new ChooseAccountDialogFragment().show(getSupportFragmentManager(),
                    ChooseAccountDialogFragment.CHOOSE_ACCOUNT_DIALOG_TAG);
        }
        return true;
    case R.id.track_list_aggregated_statistics:
        intent = IntentUtils.newIntent(this, AggregatedStatsActivity.class);
        startActivity(intent);
        return true;
    case R.id.track_list_export_all:
        FileTypeDialogFragment.newInstance(R.id.track_list_export_all, R.string.export_all_title,
                R.string.export_all_option, 4)
                .show(getSupportFragmentManager(), FileTypeDialogFragment.FILE_TYPE_DIALOG_TAG);
        return true;
    case R.id.track_list_import_all:
        FileTypeDialogFragment
                .newInstance(R.id.track_list_import_all, R.string.import_selection_title,
                        R.string.import_selection_option, 2)
                .show(getSupportFragmentManager(), FileTypeDialogFragment.FILE_TYPE_DIALOG_TAG);
        return true;
    case R.id.track_list_delete_all:
        deleteTracks(new long[] { -1L });
        return true;
    case R.id.track_list_settings:
        intent = IntentUtils.newIntent(this, SettingsActivity.class);
        startActivity(intent);
        return true;
    case R.id.track_list_help_feedback:
        intent = IntentUtils.newIntent(this, HelpActivity.class);
        startActivity(intent);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.example.android.bluetoothchat.BluetoothChatFragment2.java

private void showToast(Context context, String str, int duration) {
    Runnable action = new ToastRunable(context, str, duration);
    if (Looper.myLooper() == Looper.getMainLooper()) {
        action.run();/*from   w ww.j a v a2  s  .c o  m*/
    } else {
        mMainHandler.post(action);
    }
}

From source file:com.einzig.ipst2.activities.MainActivity.java

/**
 * Wrapper function for parseEmailWork./*from  w w  w  . ja va2 s .  c o  m*/
 * <p>
 * Builds the progress dialog for, then calls parseEmailWork
 * </p>
 *
 * @see MainActivity#parseEmailWork(Account, ProgressDialog)
 */
private void parseEmail() {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        Logger.d("IS MAIN THREAD?!");
    }
    final Account account = getAccount();
    if (account != null) {
        final ProgressDialog dialog = new ProgressDialog(this, ThemeHelper.getDialogTheme(this));
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setIndeterminate(true);
        dialog.setTitle(getString(R.string.searching_email));
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
        new Thread() {
            public void run() {
                parseEmailWork(account, dialog);
            }
        }.start();
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}

From source file:io.realm.Realm.java

private static Realm create(RealmConfiguration configuration) {
    boolean autoRefresh = Looper.myLooper() != null;
    try {//from   www  .j a va2s  .com
        return createAndValidate(configuration, true, autoRefresh);
    } catch (RealmMigrationNeededException e) {
        if (configuration.shouldDeleteRealmIfMigrationNeeded()) {
            deleteRealm(configuration);
        } else {
            migrateRealm(configuration);
        }

        return createAndValidate(configuration, true, autoRefresh);
    }
}

From source file:cn.openwatch.internal.http.loopj.AsyncHttpClient.java

/**
 * Cancels any pending (or potentially active) requests associated with the
 * passed Context.//www  .j  a  va2s . c om
 * <p>
 * &nbsp;
 * </p>
 * <b>Note:</b> This will only affect requests which were created with a
 * non-null android Context. This method is intended to be used in the
 * onDestroy method of your android activities to destroy all requests which
 * are no longer required.
 *
 * @param context               the android Context instance associated to the request.
 * @param mayInterruptIfRunning specifies if active requests should be cancelled along with
 *                              pending requests.
 */
public void cancelRequests(final Context context, final boolean mayInterruptIfRunning) {
    if (context == null) {
        return;
    }

    final List<RequestHandle> requestList = requestMap.get(context);
    requestMap.remove(context);

    if (Looper.myLooper() == Looper.getMainLooper()) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                cancelRequests(requestList, mayInterruptIfRunning);
            }
        };
        threadPool.submit(runnable);
    } else {
        cancelRequests(requestList, mayInterruptIfRunning);
    }
}

From source file:com.networking.OkHttpResponseTestActivity.java

public void doNotCacheResponse(View view) {
    AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0")
            .addQueryParameter("limit", "3").setTag(this).setPriority(Priority.LOW).doNotCacheResponse().build()
            .setAnalyticsListener(new AnalyticsListener() {
                @Override//w w  w .  j ava2  s .  c om
                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);
                }
            }).getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() {
                @Override
                public void onResponse(Response okHttpResponse, JSONArray 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.rxsampleapp.RxApiTestActivity.java

public void uploadImage(final View view) {
    RxAndroidNetworking.upload(ApiEndPoint.BASE_URL + ApiEndPoint.UPLOAD_IMAGE)
            .addMultipartFile("image",
                    new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.png"))
            .build().setAnalyticsListener(new AnalyticsListener() {
                @Override//from w w w  . ja v  a 2 s.c om
                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);
                }
            }).setUploadProgressListener(new UploadProgressListener() {
                @Override
                public void onProgress(long bytesUploaded, long totalBytes) {
                    Log.d(TAG, "bytesUploaded : " + bytesUploaded + " totalBytes : " + totalBytes);
                    Log.d(TAG, "setUploadProgressListener isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }
            }).getJSONObjectObservable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<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, "Image upload Completed");
                    Log.d(TAG, "onResponse object : " + response.toString());
                }
            });
}