Example usage for android.os Looper getMainLooper

List of usage examples for android.os Looper getMainLooper

Introduction

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

Prototype

public static Looper getMainLooper() 

Source Link

Document

Returns the application's main looper, which lives in the main thread of the application.

Usage

From source file:io.v.syncslides.DeckChooserFragment.java

/**
 * Creates a toast in the main looper.  Useful since lots of this class runs in a
 * background thread.//  www. ja v a 2 s .  co  m
 */
private void toast(final String msg) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(() -> Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show());
}

From source file:com.quantcast.measurement.service.QCLocation.java

void start() {
    QCLog.i(TAG, "Start retrieving location ");
    Location bestLocation = findBestLocation();
    if (bestLocation != null) {
        sendLocation(bestLocation);//ww  w .ja v  a 2  s .  c om
    } else if (_myProvider != null) {
        try {
            if (_locManager.isProviderEnabled(_myProvider)) {
                _locManager.requestLocationUpdates(_myProvider, 0, 0, singleUpdateListener,
                        Looper.getMainLooper());
            }
        } catch (Exception e) {
            QCLog.e(TAG, "Available location provider not found.  Skipping Location Event", e);
        }
    } else {
        QCLog.i(TAG, "Available location provider not found.  Skipping Location Event");
    }

}

From source file:com.digium.respokesdk.RespokeDirectConnection.java

/**
 *  Notify the direct connection instance that the peer connection has opened the specified data channel
 *
 *  @param newDataChannel    The DataChannel that has opened
 *//*from w  ww . ja va 2 s .co  m*/
public void peerConnectionDidOpenDataChannel(DataChannel newDataChannel) {
    if (null != dataChannel) {
        // Replacing the previous connection, so disable observer messages from the old instance
        dataChannel.unregisterObserver();
    } else {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            public void run() {
                if (null != listenerReference) {
                    Listener listener = listenerReference.get();
                    if (null != listener) {
                        listener.onStart(RespokeDirectConnection.this);
                    }
                }
            }
        });
    }

    dataChannel = newDataChannel;
    newDataChannel.registerObserver(this);
}

From source file:com.ryan.ryanreader.fragments.ImageViewFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    final Context context = inflater.getContext();

    final LoadingView loadingView = new LoadingView(context, R.string.download_loading, true, false);

    final LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(loadingView);/*w  w w  .j  a  v  a 2 s  . co m*/

    CacheManager.getInstance(context)
            .makeRequest(new CacheRequest(url, RedditAccountManager.getAnon(), null,
                    Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                    Constants.FileType.IMAGE, false, false, false, context) {

                private void setContentView(View v) {
                    layout.removeAllViews();
                    layout.addView(v);
                    v.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
                    v.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
                }

                @Override
                protected void onCallbackException(Throwable t) {
                    BugReportActivity.handleGlobalError(context.getApplicationContext(),
                            new RRError(null, null, t));
                }

                @Override
                protected void onDownloadNecessary() {
                    loadingView.setIndeterminate(R.string.download_waiting);
                }

                @Override
                protected void onDownloadStarted() {
                    loadingView.setIndeterminate(R.string.download_downloading);
                }

                @Override
                protected void onFailure(final RequestFailureType type, Throwable t, StatusLine status,
                        final String readableMessage) {

                    loadingView.setDone(R.string.download_failed);
                    final RRError error = General.getGeneralErrorForFailure(context, type, t, status);

                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        public void run() {
                            // TODO handle properly
                            layout.addView(new ErrorView(getSupportActivity(), error));
                        }
                    });
                }

                @Override
                protected void onProgress(long bytesRead, long totalBytes) {
                    loadingView.setProgress(R.string.download_downloading,
                            (float) ((double) bytesRead / (double) totalBytes));
                }

                @Override
                protected void onSuccess(final CacheManager.ReadableCacheFile cacheFile, long timestamp,
                        UUID session, boolean fromCache, final String mimetype) {

                    if (mimetype == null || !Constants.Mime.isImage(mimetype)) {
                        revertToWeb();
                        return;
                    }

                    if (Constants.Mime.isImageGif(mimetype)) {

                        try {

                            gifThread = new GifDecoderThread(cacheFile.getInputStream(),
                                    new GifDecoderThread.OnGifLoadedListener() {

                                        public void onGifLoaded() {
                                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                                public void run() {
                                                    imageView = new ImageView(context);
                                                    imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                                    setContentView(imageView);
                                                    gifThread.setView(imageView);

                                                    imageView.setOnClickListener(new View.OnClickListener() {
                                                        public void onClick(View v) {
                                                            getSupportActivity().finish();
                                                        }
                                                    });
                                                }
                                            });
                                        }

                                        public void onOutOfMemory() {
                                            General.quickToast(context, R.string.imageview_oom);
                                            revertToWeb();
                                        }

                                        public void onGifInvalid() {
                                            General.quickToast(context, R.string.imageview_invalid_gif);
                                            revertToWeb();
                                        }
                                    });

                            gifThread.start();

                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }

                    } else {

                        final Bitmap finalResult;

                        try {

                            final int maxTextureSize = 2048;
                            final Bitmap imageOrig = BitmapFactory.decodeStream(cacheFile.getInputStream());

                            if (imageOrig == null) {
                                General.quickToast(context,
                                        "Couldn't load the image. Trying internal browser.");
                                revertToWeb();
                                return;
                            }

                            final int maxDim = Math.max(imageOrig.getWidth(), imageOrig.getHeight());

                            if (maxDim > maxTextureSize) {

                                imageOrig.recycle();

                                final double scaleFactorPowerOfTwo = Math
                                        .log((double) maxDim / (double) maxTextureSize) / Math.log(2);
                                final int scaleFactor = (int) Math
                                        .round(Math.pow(2, Math.ceil(scaleFactorPowerOfTwo)));

                                final BitmapFactory.Options options = new BitmapFactory.Options();
                                options.inSampleSize = scaleFactor;
                                finalResult = BitmapFactory.decodeStream(cacheFile.getInputStream(), null,
                                        options);
                            } else {
                                finalResult = imageOrig;
                            }

                        } catch (IOException e) {
                            throw new RuntimeException(e);

                        } catch (OutOfMemoryError e) {
                            General.quickToast(context, "Out of memory. Trying internal browser.");
                            revertToWeb();
                            return;
                        }

                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            public void run() {
                                imageView = new GestureImageView(context);
                                imageView.setImageBitmap(finalResult);
                                imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                                setContentView(imageView);

                                imageView.setOnClickListener(new View.OnClickListener() {
                                    public void onClick(View v) {
                                        getSupportActivity().finish();
                                    }
                                });
                            }
                        });
                    }
                }
            });

    final RedditPost src_post = getArguments().getParcelable("post");
    final RedditPreparedPost post = src_post == null ? null
            : new RedditPreparedPost(context, CacheManager.getInstance(context), 0, src_post, -1, false,
                    new RedditSubreddit("/r/" + src_post.subreddit, src_post.subreddit, false), false, false,
                    false, RedditAccountManager.getInstance(context).getDefaultAccount());

    final FrameLayout outerFrame = new FrameLayout(context);
    outerFrame.addView(layout);

    if (post != null) {

        final SideToolbarOverlay toolbarOverlay = new SideToolbarOverlay(context);

        final BezelSwipeOverlay bezelOverlay = new BezelSwipeOverlay(context,
                new BezelSwipeOverlay.BezelSwipeListener() {

                    public boolean onSwipe(BezelSwipeOverlay.SwipeEdge edge) {

                        toolbarOverlay.setContents(
                                post.generateToolbar(context, ImageViewFragment.this, toolbarOverlay));
                        toolbarOverlay.show(edge == BezelSwipeOverlay.SwipeEdge.LEFT
                                ? SideToolbarOverlay.SideToolbarPosition.LEFT
                                : SideToolbarOverlay.SideToolbarPosition.RIGHT);
                        return true;
                    }

                    public boolean onTap() {

                        if (toolbarOverlay.isShown()) {
                            toolbarOverlay.hide();
                            return true;
                        }

                        return false;
                    }
                });

        outerFrame.addView(bezelOverlay);
        outerFrame.addView(toolbarOverlay);

        bezelOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        bezelOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

        toolbarOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        toolbarOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

    }

    return outerFrame;
}

From source file:com.nuvolect.securesuite.data.SqlSyncTest.java

public JSONObject pong_test(final Context ctx) {

    managePayloadSize();//from ww  w.  ja v a  2 s  . co  m

    /**
     * Build the payload and generate MD5
     */
    Map<String, String> parameters = makeParameters();
    parameters.put(CConst.CMD, SyncRest.CMD.pong_test.toString());
    parameters.put(CConst.COUNTER, String.valueOf(++pong_counter));

    String url = WebUtil.getCompanionServerUrl(CConst.SYNC);
    startTime = System.currentTimeMillis();

    Comm.sendPost(ctx, url, parameters, new Comm.CommPostCallbacks() {
        @Override
        public void success(String response) {

            LogUtil.log(LogUtil.LogType.SQL_SYNC_TEST, SyncRest.CMD.pong_test + " response: " + response);

            if (WebUtil.responseMatch(response, CConst.RESPONSE_CODE_SUCCESS_100)) {

                if (m_pingPongCallbacks != null) {

                    Handler handler = new Handler(Looper.getMainLooper());
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {

                            m_pingPongCallbacks.progressUpdate(m_pingPongCallbacksAct, ping_counter,
                                    pong_counter, payloadSize);

                            if (!m_continueTest)
                                m_pingPongCallbacks.cancelDialog(m_pingPongCallbacksAct);
                        }
                    };
                    handler.post(r);
                }
                if (m_continueTest)
                    WorkerCommand.quePingTest(ctx);
            }
        }

        @Override
        public void fail(String error) {
            LogUtil.log(LogUtil.LogType.SQL_SYNC_TEST, SyncRest.CMD.pong_test + " error: " + error);
        }
    });
    if (m_continueTest)
        return WebUtil.response(CConst.RESPONSE_CODE_SUCCESS_100);
    else
        return WebUtil.response(CConst.RESPONSE_CODE_USER_CANCEL_102);
}

From source file:com.android.nfc.beam.BeamTransferManager.java

public BeamTransferManager(Context context, Callback callback, BeamTransferRecord pendingTransfer,
        boolean incoming) {
    mContext = context;/*  ww w. j  a  va  2  s  . c  o m*/
    mCallback = callback;
    mRemoteDevice = pendingTransfer.remoteDevice;
    mIncoming = incoming;
    mTransferId = pendingTransfer.id;
    mBluetoothTransferId = -1;
    mDataLinkType = pendingTransfer.dataLinkType;
    mRemoteActivating = pendingTransfer.remoteActivating;
    mStartTime = 0L;
    // For incoming transfers, count can be set later
    mTotalCount = (pendingTransfer.uris != null) ? pendingTransfer.uris.length : 0;
    mLastUpdate = SystemClock.elapsedRealtime();
    mProgress = 0.0f;
    mState = STATE_NEW;
    mUris = pendingTransfer.uris == null ? new ArrayList<Uri>()
            : new ArrayList<Uri>(Arrays.asList(pendingTransfer.uris));
    mTransferMimeTypes = new ArrayList<String>();
    mMimeTypes = new HashMap<String, String>();
    mPaths = new ArrayList<String>();
    mMediaUris = new HashMap<String, Uri>();
    mCancelIntent = buildCancelIntent();
    mUrisScanned = 0;
    mCurrentCount = 0;
    mSuccessCount = 0;
    mOutgoingUris = pendingTransfer.uris;
    mHandler = new Handler(Looper.getMainLooper(), this);
    mHandler.sendEmptyMessageDelayed(MSG_TRANSFER_TIMEOUT, ALIVE_CHECK_MS);
    mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
}

From source file:com.scoreflex.ScoreflexGcmClient.java

private static void registerInBackground(final String senderId, final Context activity) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        public void run() {
            new AsyncTask<Object, Object, Object>() {
                @Override/*w  w  w .  j a  va2 s .  c  o m*/
                protected Object doInBackground(Object... arg0) {
                    String msg = "";
                    try {
                        String regid = ScoreflexGcmWrapper.register(Scoreflex.getApplicationContext(),
                                senderId);
                        if (regid == null) {
                            return null;
                        }
                        msg = "Device registered, registration ID=" + regid;
                        storeRegistrationId(regid, activity);
                        storeRegistrationIdToScoreflex(regid);
                    } catch (IOException ex) {
                        msg = "Error :" + ex.getMessage();
                    }
                    return msg;
                }

                @Override
                protected void onPostExecute(Object msg) {

                }
            }.execute(null, null, null);
        }
    });
}

From source file:com.appnexus.opensdk.mediatednativead.InMobiNativeAdResponse.java

@Override
public boolean registerView(View view, NativeAdEventListener listener) {
    if (imNative != null && !registered && !expired) {
        InMobiNative.bind(view, imNative);
        view.setOnClickListener(clickListener);
        registeredView = view;//  w ww. j a va 2s .c om
        registered = true;
        Handler handler = new Handler(Looper.getMainLooper());
        handler.removeCallbacks(runnable);
    }
    this.nativeAdEventlistener = listener;
    return registered;
}

From source file:arun.com.chromer.appdetect.AppDetectService.java

@SuppressWarnings("unused")
void toast(final String toast) {
    new Handler(Looper.getMainLooper())
            .post(() -> Toast.makeText(AppDetectService.this, toast, Toast.LENGTH_SHORT).show());
}

From source file:org.chromium.android_webview.test.AwContentsTest.java

private int callDocumentHasImagesSync(final AwContents awContents) throws Throwable, InterruptedException {
    // Set up a container to hold the result object and a semaphore to
    // make the test wait for the result.
    final AtomicInteger val = new AtomicInteger();
    final Semaphore s = new Semaphore(0);
    final Message msg = Message.obtain(new Handler(Looper.getMainLooper()) {
        @Override// w w w .  ja v a  2  s  .c  o  m
        public void handleMessage(Message msg) {
            val.set(msg.arg1);
            s.release();
        }
    });
    runTestOnUiThread(new Runnable() {
        @Override
        public void run() {
            awContents.documentHasImages(msg);
        }
    });
    assertTrue(s.tryAcquire(WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS));
    int result = val.get();
    return result;
}