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:org.opensilk.music.playback.control.PlaybackController.java

private static void ensureNotOnMainThread(Context context) {
    Looper looper = Looper.myLooper();
    if (looper != null && looper == context.getMainLooper()) {
        throw new IllegalStateException("calling this from your main thread can lead to deadlock");
    }//from  www  .  j  a  v a  2 s. co m
}

From source file:org.kegbot.app.HomeActivity.java

@Subscribe
public void onVisibleTapListUpdate(VisibleTapsChangedEvent event) {
    assert (Looper.myLooper() == Looper.getMainLooper());
    Log.d(LOG_TAG, "Got tap list change event: " + event + " taps=" + event.getTaps().size());

    final List<KegTap> newTapList = event.getTaps();
    synchronized (mTapsLock) {
        if (newTapList.equals(mTaps)) {
            Log.d(LOG_TAG, "Tap list unchanged.");
            return;
        }/*from  w  ww  .j  a v  a  2 s .  c  o m*/

        mTaps.clear();
        mTaps.addAll(newTapList);
        mTapStatusAdapter.notifyDataSetChanged();
    }

    //for progress bar
    if (mTaps.size() > 0) {
        final KegTap tap = mTaps.get(mTapStatusPager.getCurrentItem());
        if (tap.hasCurrentKeg()) {
            final Models.Keg keg = tap.getCurrentKeg();
            double remainml = keg.getRemainingVolumeMl();
            double totalml = keg.getFullVolumeMl();
            double percent = (remainml) / (totalml) * 100;

            final ProgressBar mTapProgress = (ProgressBar) findViewById(R.id.tapProgress);
            mTapProgress.setMax((int) totalml);
            mTapProgress.setProgress((int) remainml);

            final TextView mTapPercentage = (TextView) findViewById(R.id.tapPercentage);
            mTapPercentage.setText(String.format("%.2f", percent) + "%");
        }
    }

    maybeShowTapWarnings();
}

From source file:com.rxsampleapp.RxApiTestActivity.java

public void createAnUser(View view) {
    RxAndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER)
            .addBodyParameter("firstname", "Amit").addBodyParameter("lastname", "Shekhar").build()
            .setAnalyticsListener(new AnalyticsListener() {
                @Override//from   www  .j  av 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);
                }
            }).getJSONObjectObservable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<JSONObject>() {
                @Override
                public void onCompleted() {
                    Log.d(TAG, "onComplete Detail : createAnUser 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:io.requery.android.database.sqlite.SQLiteDatabase.java

private static boolean isMainThread() {
    // FIXME: There should be a better way to do this.
    // Would also be nice to have something that would work across Binder calls.
    Looper looper = Looper.myLooper();
    return looper != null && looper == Looper.getMainLooper();
}

From source file:com.wuman.androidimageloader.ImageLoader.java

private void enqueueRequest(ImageRequest request) {
    if (Looper.myLooper() != Looper.getMainLooper()) {
        throw new RuntimeException("Must be called in the main thread.");
    }/* w  w  w . ja v a2  s.c  o m*/
    ImageTask task = new ImageTask();
    task.executeOnExecutor(ImageTask.LIFO_THREAD_POOL_EXECUTOR, request);
}

From source file:com.networking.ApiTestActivity.java

public void createAnUserJSONObject(View view) {
    JSONObject jsonObject = new JSONObject();
    try {/*from  w w w. j a v a 2s  . co m*/
        jsonObject.put("firstname", "Rohit");
        jsonObject.put("lastname", "Kumar");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER).addJSONObjectBody(jsonObject)
            .setTag(this).setPriority(Priority.LOW).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);
                }
            }).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.networking.OkHttpResponseTestActivity.java

public void createAnUserJSONObject(View view) {
    JSONObject jsonObject = new JSONObject();
    try {/*from   w ww  . j a v  a 2s. c om*/
        jsonObject.put("firstname", "Rohit");
        jsonObject.put("lastname", "Kumar");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER).addJSONObjectBody(jsonObject)
            .setTag(this).setPriority(Priority.LOW).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);
                }
            }).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.vk.sdk.payments.VKIInAppBillingService.java

/**
 * Method for save transaction if you can't use
 * VKIInAppBillingService mService = new VKIInAppBillingService(IInAppBillingService.Stub.asInterface(service));
 * WARNING!!! this method must call before consume google and is it returned true
 *
 * @param apiVersion - version google apis
 * @param purchaseToken - purchase token
 * @return true is send is ok//  w  ww .  j  a  v  a2s. c  om
 * @throws android.os.RemoteException
 */
public static boolean consumePurchaseToVk(final int apiVersion, @NonNull final String purchaseToken)
        throws android.os.RemoteException {
    if (Looper.getMainLooper().equals(Looper.myLooper())) {
        throw new RuntimeException("Network on main thread");
    }
    final Context ctx = VKUIHelper.getApplicationContext();
    if (ctx == null) {
        return false;
    }

    final PurchaseData purchaseData = new PurchaseData();

    if (!VKPaymentsServerSender.isNotVkUser()) {
        final SyncServiceConnection serviceConnection = new SyncServiceConnection() {
            @Override
            public void onServiceConnectedImpl(ComponentName name, IBinder service) {
                Object iInAppBillingService = null;

                final Class<?> iInAppBillingServiceClassStub;
                try {
                    iInAppBillingServiceClassStub = Class
                            .forName("com.android.vending.billing.IInAppBillingService$Stub");
                    Method asInterface = iInAppBillingServiceClassStub.getMethod("asInterface",
                            android.os.IBinder.class);
                    iInAppBillingService = asInterface.invoke(iInAppBillingServiceClassStub, service);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(PARAMS_ARE_NOT_VALID_ERROR);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                try {
                    purchaseData.purchaseData = getPurchaseData(iInAppBillingService, apiVersion,
                            ctx.getPackageName(), purchaseToken);
                } catch (Exception e) {
                    Log.e("VKSDK", "error", e);
                    purchaseData.hasError = true;
                }
            }

            @Override
            public void onServiceDisconnectedImpl(ComponentName name) {

            }
        };

        Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
        serviceIntent.setPackage("com.android.vending");
        if (!ctx.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
            // bind
            ctx.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
            // wait bind
            synchronized (serviceConnection.syncObj) {
                while (!serviceConnection.isFinish) {
                    try {
                        serviceConnection.syncObj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            // unbind
            ctx.unbindService(serviceConnection);
        } else {
            return false;
        }
    } else {
        return true;
    }

    if (purchaseData.hasError) {
        return false;
    } else if (!TextUtils.isEmpty(purchaseData.purchaseData)) {
        VKPaymentsServerSender.getInstance(ctx).saveTransaction(purchaseData.purchaseData);
    }

    return true;
}

From source file:com.sonymobile.android.media.testmediaplayer.MainActivity.java

public void init() {
    if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer(getApplicationContext());
        mMediaPlayer.setScreenOnWhilePlaying(true);
    }/* w  w  w .j av a2 s  .  c om*/
    mHandler = new Handler();
    mDecorView = getWindow().getDecorView();
    mSeekbar = (SeekBar) findViewById(R.id.activity_main_seekbar);
    mSeekbar.setMax(1000);
    mPlayPauseButton = (ImageView) findViewById(R.id.activity_main_playpause_button);
    mSeekBarUpdater = new SeekbarUpdater(mSeekbar, mMediaPlayer);
    mTopLayout = (RelativeLayout) findViewById(R.id.activity_main_mainlayout);
    mTrackDialog = new AudioSubtitleTrackDialog(this);
    mAudioPos = mSubPos = 0;
    mTimeView = (TextView) findViewById(R.id.activity_main_time);
    mDurationView = (TextView) findViewById(R.id.activity_main_duration);
    mTimeLayout = (LinearLayout) findViewById(R.id.activity_main_timelayout);
    mTimeTracker = new TimeTracker(mMediaPlayer, mTimeView);
    mSubtitleView = (TextView) findViewById(R.id.activity_main_subtitleView);
    mSubtitleRenderer = new SubtitleRenderer(mSubtitleView, Looper.myLooper(), mMediaPlayer);
    mSubtitleLayoutAboveTimeView = (RelativeLayout.LayoutParams) mSubtitleView.getLayoutParams();
    mSubtitleLayoutBottom = (RelativeLayout.LayoutParams) ((TextView) findViewById(
            R.id.activity_main_subtitleView_params)).getLayoutParams();
    mTimeSeekView = (TextView) findViewById(R.id.activity_main_time_seek);
    mMediaPlayer.setOnInfoListener(this);
    RelativeLayout browsingL = (RelativeLayout) findViewById(R.id.activity_main_browsing_layout);
    ExpandableListView elv = (ExpandableListView) browsingL.findViewById(R.id.file_browsing_exp_list_view);
    ListView lv = (ListView) browsingL.findViewById(R.id.file_browsing_listview);
    RelativeLayout debugLayout = (RelativeLayout) findViewById(R.id.activity_main_debug_view);
    LinearLayout debugLinearLayout = (LinearLayout) debugLayout.findViewById(R.id.activity_main_debug_linear);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerLayout.setScrimColor(Color.TRANSPARENT);
    mDrawerLayout.setDrawerListener(this);
    mFileBrowser = new MediaBrowser(this, elv, lv, mMediaPlayer, (MainActivity) this, mDrawerLayout,
            debugLinearLayout);
    mIsFileBrowsing = false;
    mPreview = (SurfaceView) findViewById(R.id.mSurfaceView);
    mPreview.setOnTouchListener(this);
    mTopLayout.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
    mPreview.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    mSubtitleTracker = new HashMap<Integer, Integer>();
    mAudioTracker = new HashMap<Integer, Integer>();
    findViewById(R.id.activity_main_loading_panel).bringToFront();
    findViewById(R.id.activity_main_browsing_layout).bringToFront();
    mUpperControls = (RelativeLayout) findViewById(R.id.UpperButtonLayout);
    mBottomControls = (RelativeLayout) findViewById(R.id.ButtonLayout);
    mSlideInAnimation = AnimationUtils.loadAnimation(this, R.anim.in_top);
    mSlideInAnimation.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationEnd(Animation animation) {
            mUpperControls.setVisibility(View.VISIBLE);
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    mBottomControls.setVisibility(View.INVISIBLE);
                }
            };
            mHandler.postDelayed(r, 3500);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationStart(Animation animation) {
            mBottomControls.setVisibility(View.INVISIBLE);
        }
    });
    mHolder = mPreview.getHolder();
    mHolder.addCallback(this);
    mFadeOutRunnable = new Runnable() {
        @Override
        public void run() {
            mSeekbar.setEnabled(false);
            Animation fadeoutBottom = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.out_bottom);
            fadeoutBottom.setAnimationListener(new AnimationListener() {

                @Override
                public void onAnimationEnd(Animation animation) {
                    if (mOngoingAnimation) {
                        mOngoingAnimation = false;
                        mBottomControls.setVisibility(View.INVISIBLE);
                        mUpperControls.setVisibility(View.INVISIBLE);
                        mSeekbar.setVisibility(View.GONE);
                        mTimeLayout.setVisibility(View.GONE);
                        mSubtitleView.setLayoutParams(mSubtitleLayoutBottom);
                    }
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationStart(Animation animation) {
                    mOngoingAnimation = true;
                }
            });
            Animation fadeoutTop = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.out_top);
            mBottomControls.startAnimation(fadeoutBottom);
            mUpperControls.startAnimation(fadeoutTop);
            mSeekbar.startAnimation(fadeoutBottom);
            mTimeLayout.startAnimation(fadeoutBottom);
        }
    };
    mHideNavigationRunnable = new Runnable() {
        @Override
        public void run() {
            mPreview.setSystemUiVisibility(mUiOptions);
        }
    };

    mDecorView.setOnSystemUiVisibilityChangeListener(this);
    mSeekbar.setOnSeekBarChangeListener(new OwnOnSeekBarChangeListener(mMediaPlayer));
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setOnSeekCompleteListener(this);
    mMediaPlayer.setOnErrorListener(this);
    mMediaPlayer.setOnSubtitleDataListener(this);

    RelativeLayout browsingLayout = (RelativeLayout) findViewById(R.id.activity_main_browsing_layout);
    DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) browsingLayout.getLayoutParams();
    Resources resources = getResources();
    int top = 0;
    int bottom = 0;
    RelativeLayout.LayoutParams tempParams;
    int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        top = resources.getDimensionPixelSize(resourceId);
    }
    resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
    if (resourceId > 0) {
        bottom = resources.getDimensionPixelSize(resourceId);
    }
    if (navigationBarAtBottom()) {
        tempParams = (RelativeLayout.LayoutParams) mBottomControls.getLayoutParams();
        tempParams.bottomMargin += bottom;
        mBottomControls.setLayoutParams(tempParams);
        tempParams = (RelativeLayout.LayoutParams) mSeekbar.getLayoutParams();
        tempParams.bottomMargin += bottom;
        mSeekbar.setLayoutParams(tempParams);
        params.setMargins(0, top, 0, bottom);
    } else {
        tempParams = (RelativeLayout.LayoutParams) mBottomControls.getLayoutParams();
        tempParams.rightMargin += bottom;
        mBottomControls.setLayoutParams(tempParams);
        params.setMargins(0, top, 0, 0);
    }
    browsingLayout.setLayoutParams(params);
    mDrawerLayout.openDrawer(Gravity.START);

    mMediaPlayer.setOnOutputControlListener(this);
}

From source file:com.vendsy.bartsy.venue.BartsyApplication.java

synchronized private void update() {

    if (Looper.myLooper() == Looper.getMainLooper()) {
        // We're in the main thread - execute the update in the background with a new asynchronous task
        Log.w(TAG, "Running updateOrders() in an async task");
        //         mHandler.post(new Runnable() {

        //            @Override
        //            public void run() {
        new Thread() {
            @Override/*from w w  w . j  a v a2s  . c om*/
            public void run() {
                accessOrders(BartsyApplication.ACCESS_ORDERS_UPDATE);
            };
        }.start();
        //            };
        //         });

        //         new UpdateAsync().execute();
    } else {
        // We're not in the main thread - don't spin up a thread
        Log.w(TAG, "Running updateOrders()");
        accessOrders(ACCESS_ORDERS_UPDATE);
    }

    return;
}