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:com.android.cts.verifier.sensors.SignificantMotionTestActivity.java

@SuppressWarnings("unused")
public String testAPWakeUpOnSMDTrigger() throws Throwable {
    SensorTestLogger logger = getTestLogger();
    logger.logInstructions(R.string.snsr_significant_motion_ap_suspend);
    waitForUserToBegin();//from  ww  w  .j  a v a  2  s.co  m
    mVerifier = new TriggerVerifier();
    mSensorManager.requestTriggerSensor(mVerifier, mSensorSignificantMotion);
    long testStartTimeNs = SystemClock.elapsedRealtimeNanos();
    Handler handler = new Handler(Looper.getMainLooper());
    SuspendStateMonitor suspendStateMonitor = new SuspendStateMonitor();

    Intent intent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + ALARM_WAKE_TIME_DELAY_MS,
            pendingIntent);
    try {
        // Wait for the first event to trigger. Device is expected to go into suspend here.
        mVerifier.verifyEventTriggered();
        long eventTimeStampNs = mVerifier.getTimeStampForTriggerEvent();
        long endTimeNs = SystemClock.elapsedRealtimeNanos();
        long lastWakeupTimeNs = TimeUnit.MILLISECONDS.toNanos(suspendStateMonitor.getLastWakeUpTime());
        Assert.assertTrue(getString(R.string.snsr_device_did_not_go_into_suspend),
                testStartTimeNs < lastWakeupTimeNs && lastWakeupTimeNs < endTimeNs);
        long timestampDelta = Math.abs(lastWakeupTimeNs - eventTimeStampNs);
        Assert.assertTrue(
                String.format(getString(R.string.snsr_device_did_not_wake_up_at_trigger),
                        TimeUnit.NANOSECONDS.toMillis(lastWakeupTimeNs),
                        TimeUnit.NANOSECONDS.toMillis(eventTimeStampNs)),
                timestampDelta < MAX_ACCEPTABLE_DELAY_EVENT_AP_WAKE_UP_NS);
    } finally {
        am.cancel(pendingIntent);
        suspendStateMonitor.cancel();
        mScreenManipulator.turnScreenOn();
        playSound();
    }
    return null;
}

From source file:com.android.incallui.ContactInfoCache.java

/**
 * Requests contact data for the Call object passed in.
 * Returns the data through callback.  If callback is null, no response is made, however the
 * query is still performed and cached.//from   ww  w .  j a v  a2  s . c  om
 *
 * @param callback The function to call back when the call is found. Can be null.
 */
public void findInfo(final Call call, final boolean isIncoming, ContactInfoCacheCallback callback) {
    Preconditions.checkState(Looper.getMainLooper().getThread() == Thread.currentThread());
    Preconditions.checkNotNull(callback);

    final String callId = call.getId();
    final ContactCacheEntry cacheEntry = mInfoMap.get(callId);
    Set<ContactInfoCacheCallback> callBacks = mCallBacks.get(callId);

    // If we have a previously obtained intermediate result return that now
    if (cacheEntry != null) {
        Log.d(TAG, "Contact lookup. In memory cache hit; lookup "
                + (callBacks == null ? "complete" : "still running"));
        callback.onContactInfoComplete(callId, cacheEntry);
        // If no other callbacks are in flight, we're done.
        if (callBacks == null) {
            return;
        }
    }

    // If the entry already exists, add callback
    if (callBacks != null) {
        callBacks.add(callback);
        return;
    }
    Log.d(TAG, "Contact lookup. In memory cache miss; searching provider.");
    // New lookup
    callBacks = Sets.newHashSet();
    callBacks.add(callback);
    mCallBacks.put(callId, callBacks);

    /**
     * Performs a query for caller information.
     * Save any immediate data we get from the query. An asynchronous query may also be made
     * for any data that we do not already have. Some queries, such as those for voicemail and
     * emergency call information, will not perform an additional asynchronous query.
     */
    final CallerInfo callerInfo = CallerInfoUtils.getCallerInfoForCall(mContext, call,
            new FindInfoCallback(isIncoming));

    findInfoQueryComplete(call, callerInfo, isIncoming, false);
}

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

private void makeFirstRequest(final Context context) {

    final RedditAccount user = RedditAccountManager.getInstance(context).getDefaultAccount();
    final CacheManager cm = CacheManager.getInstance(context);

    final URI url = Constants.Reddit.getUri("/message/inbox.json?mark=true&limit=100");

    // TODO parameterise limit
    request = new CacheRequest(url, user, null, Constants.Priority.API_INBOX_LIST, 0,
            CacheRequest.DownloadType.FORCE, Constants.FileType.INBOX_LIST, true, true, true, context) {

        @Override//  w  w  w. j  a  va2s .c  o m
        protected void onDownloadNecessary() {
        }

        @Override
        protected void onDownloadStarted() {
        }

        @Override
        protected void onCallbackException(final Throwable t) {
            request = null;
            BugReportActivity.handleGlobalError(context, t);
        }

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

            request = null;

            if (!isAdded())
                return;

            if (loadingView != null)
                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() {
                    if (isAdded())
                        notifications.addView(new ErrorView(getSupportActivity(), error));
                }
            });

            if (t != null)
                t.printStackTrace();
        }

        @Override
        protected void onProgress(final long bytesRead, final long totalBytes) {
        }

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

        @Override
        public void onJsonParseStarted(final JsonValue value, final long timestamp, final UUID session,
                final boolean fromCache) {

            if (isAdded() && loadingView != null)
                loadingView.setIndeterminate(R.string.download_downloading);

            // TODO pref (currently 10 mins)
            // TODO xml
            if (fromCache && RRTime.since(timestamp) > 10 * 60 * 1000) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        final TextView cacheNotif = new TextView(context);
                        cacheNotif.setText(context.getString(R.string.listing_cached)
                                + RRTime.formatDateTime(timestamp, context));
                        final int paddingPx = General.dpToPixels(context, 6);
                        final int sidePaddingPx = General.dpToPixels(context, 10);
                        cacheNotif.setPadding(sidePaddingPx, paddingPx, sidePaddingPx, paddingPx);
                        cacheNotif.setTextSize(13f);
                        notifications.addView(cacheNotif);
                        adapter.notifyDataSetChanged();
                    }
                });
            }

            // TODO {"error": 403} is received for unauthorized subreddits

            try {

                final JsonBufferedObject root = value.asObject();
                final JsonBufferedObject data = root.getObject("data");
                final JsonBufferedArray children = data.getArray("children");

                for (JsonValue child : children) {

                    final RedditThing thing = child.asObject(RedditThing.class);

                    switch (thing.getKind()) {
                    case COMMENT:
                        final RedditPreparedComment comment = new RedditPreparedComment(getSupportActivity(),
                                thing.asComment(), null, timestamp, false, null, user, headerItems);
                        itemHandler.sendMessage(General.handlerMessage(0, comment));

                        break;

                    case MESSAGE:
                        final RedditPreparedMessage message = new RedditPreparedMessage(getSupportActivity(),
                                thing.asMessage(), timestamp);
                        itemHandler.sendMessage(General.handlerMessage(0, message));
                        break;

                    default:
                        throw new RuntimeException("Unknown item in list.");
                    }
                }

            } catch (Throwable t) {
                notifyFailure(RequestFailureType.PARSE, t, null, "Parse failure");
                return;
            }

            if (isAdded() && loadingView != null)
                loadingView.setDone(R.string.download_done);
        }
    };

    cm.makeRequest(request);
}

From source file:com.android.volley.Request.java

/**
 * Notifies the request queue that this request has finished (successfully or with error).
 *
 * <p>Also dumps all events from this request's event log; for debugging.</p>
 *//*  w ww .  j  a v  a 2s  . c o  m*/
void finish(final String tag) {
    if (mRequestQueue != null) {
        mRequestQueue.finish(this);
    }
    if (MarkerLog.ENABLED) {
        final long threadId = Thread.currentThread().getId();
        if (Looper.myLooper() != Looper.getMainLooper()) {
            // If we finish marking off of the main thread, we need to
            // actually do it on the main thread to ensure correct ordering.
            Handler mainThread = new Handler(Looper.getMainLooper());
            mainThread.post(new Runnable() {
                @Override
                public void run() {
                    mEventLog.add(tag, threadId);
                    mEventLog.finish(this.toString());
                }
            });
            return;
        }

        mEventLog.add(tag, threadId);
        mEventLog.finish(this.toString());
    }
}

From source file:com.example.snapcacheexample.PickerActivity.java

@Override
protected void onStart() {
    super.onStart();
    if (FRIEND_PICKER.equals(getIntent().getData())) {
        try {//from  w ww .  j  av a  2s  .  c om
            friendPickerFragment.loadData(false);
        } catch (Exception ex) {
            onError(ex);
        }
    } else if (PLACE_PICKER.equals(getIntent().getData())) {
        try {
            Location location = null;
            Criteria criteria = new Criteria();
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String bestProvider = locationManager.getBestProvider(criteria, false);
            if (bestProvider != null) {
                location = locationManager.getLastKnownLocation(bestProvider);
                if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) {
                    locationListener = new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            float distance = location.distanceTo(placePickerFragment.getLocation());
                            if (distance >= LOCATION_CHANGE_THRESHOLD) {
                                placePickerFragment.setLocation(location);
                                placePickerFragment.loadData(true);
                            }
                        }

                        @Override
                        public void onStatusChanged(String s, int i, Bundle bundle) {
                        }

                        @Override
                        public void onProviderEnabled(String s) {
                        }

                        @Override
                        public void onProviderDisabled(String s) {
                        }
                    };
                    locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD,
                            locationListener, Looper.getMainLooper());
                }
            }
            if (location == null) {
                String model = Build.MODEL;
                if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
                    // this may be the emulator, pretend we're in an exotic place
                    location = SAN_FRANCISCO_LOCATION;
                }
            }
            if (location != null) {
                placePickerFragment.setLocation(location);
                placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
                placePickerFragment.setSearchText(SEARCH_TEXT);
                placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
                placePickerFragment.loadData(false);
            } else {
                onError(getResources().getString(R.string.no_location_error), true);
            }
        } catch (Exception ex) {
            onError(ex);
        }
    }
}

From source file:com.cmgapps.android.util.CMGAppRater.java

/**
 * Shows a default {@link AlertDialog}//from   w  w w . ja v  a  2 s  . c  o m
 *
 * @param context A Context to show the dialog
 */
public void show(final Context context) {
    if (context == null) {
        throw new IllegalArgumentException("context cannot be null");
    }

    if (Looper.getMainLooper().getThread() != Thread.currentThread()) {
        throw new RuntimeException("CMGAppRater.show() must be called from main thread");
    }

    if (mDialog != null && mDialog.isShowing())
        return;

    final Editor editor = mPref.edit();
    final PackageManager pm = context.getPackageManager();

    String appName;
    try {
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        appName = (String) pm.getApplicationLabel(ai);
    } catch (NameNotFoundException e) {
        LOGE(TAG, "Application name can not be found");
        appName = "App";
    }

    mDialog = new AlertDialog.Builder(context).setTitle(R.string.dialog_cmgrate_title)
            .setMessage(context.getString(R.string.dialog_cmgrate_message, appName)).setCancelable(false)
            .setIcon(context.getApplicationInfo().icon)
            .setPositiveButton(context.getString(R.string.dialog_cmgrate_ok),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            editor.putBoolean(APP_RATED, true);
                            Intent intent = new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("market://details?id=" + context.getPackageName()));
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context.startActivity(intent);

                            PreferenceEditorHelper.commit(editor);
                            dialog.dismiss();
                        }
                    })
            .setNegativeButton(R.string.dialog_cmgrate_no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    PreferenceEditorHelper.commit(editor.putBoolean(DECLINED_RATE, true));
                    dialog.dismiss();
                }
            }).setNeutralButton(R.string.dialog_cmgrate_later, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    PreferenceEditorHelper
                            .commit(editor.putLong(REMIND_LATER_DATE, System.currentTimeMillis()));
                    dialog.dismiss();
                }
            }).show();
    PreferenceEditorHelper.commit(editor);
}

From source file:com.vk.sdkweb.api.httpClient.VKHttpClient.java

/**
 * Starts operation in the one of network threads
 *
 * @param operation Operation to start/*  ww  w .  ja  va  2 s. c  om*/
 */
public static void enqueueOperation(final VKAbstractOperation operation) {
    //Check thread
    if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
        mBackgroundExecutor.execute(new Runnable() {
            @Override
            public void run() {
                enqueueOperation(operation);
            }
        });
        return;
    }

    operation.start();
}

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

@Override
public boolean registerViewList(View view, List<View> clickables, NativeAdEventListener listener) {
    if (imNative != null && !registered && !expired) {
        InMobiNative.bind(view, imNative);
        for (View clickable : clickables) {
            clickable.setOnClickListener(clickListener);
        }//from  w w w .  j  av a  2  s .  c  om
        registeredView = view;
        registeredClickables = clickables;
        registered = true;
        Handler handler = new Handler(Looper.getMainLooper());
        handler.removeCallbacks(runnable);
    }
    this.nativeAdEventlistener = listener;
    return registered;
}

From source file:com.adkdevelopment.earthquakesurvival.ui.PagerActivity.java

/**
 * The {@link ViewPager} that will host the section contents.
 *///from  ww w  . ja  va2  s .  c  o  m

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pager_activity);

    _rxBus = App.getRxBusSingleton();

    mGeofenceList = new ArrayList<>();

    ButterKnife.bind(this);

    setSupportActionBar(mToolbar);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mPagerAdapter = new PagerAdapter(getSupportFragmentManager(), getApplicationContext());

    // Set up the ViewPager with the sections adapter.
    mViewPager.setAdapter(mPagerAdapter);
    mViewPager.setOffscreenPageLimit(mPagerAdapter.getCount());
    mViewPager.setPageTransformer(true, new ZoomOutPageTransformer());
    mTab.setupWithViewPager(mViewPager);
    setTabImages();

    // start SyncAdapter
    SyncAdapter.initializeSyncAdapter(this);

    loadPermissions(Manifest.permission.ACCESS_FINE_LOCATION, REQUEST_FINE_LOCATION);

    if (Utilities.checkPlayServices(this)) {
        // Set up GoogleApiClient
        mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
                .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
    }

    // Observe SyncAdapter work and update Geofences
    mObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {
        public void onChange(boolean selfChange) {
            populateGeofenceList();
            observeGeofences();
        }
    };
    getContentResolver().registerContentObserver(EarthquakeColumns.CONTENT_URI, false, mObserver);
}

From source file:com.android.settings.security.SecurityFeatureProviderImpl.java

@VisibleForTesting
void updatePreferencesToRunOnWorkerThread(Context context, PreferenceScreen preferenceScreen,
        DashboardCategory dashboardCategory) {

    int tilesCount = (dashboardCategory != null) ? dashboardCategory.getTilesCount() : 0;
    Map<String, IContentProvider> providerMap = new ArrayMap<>();
    for (int i = 0; i < tilesCount; i++) {
        Tile tile = dashboardCategory.getTile(i);
        // If the tile does not have a key or appropriate meta data, skip it.
        if (TextUtils.isEmpty(tile.key) || (tile.metaData == null)) {
            continue;
        }/*from  w w w  .j  a  va 2  s.c  o m*/
        Preference matchingPref = preferenceScreen.findPreference(tile.key);
        // If the tile does not have a matching preference, skip it.
        if (matchingPref == null) {
            continue;
        }
        // Check if the tile has content providers for dynamically updatable content.
        final String iconUri = tile.metaData.getString(TileUtils.META_DATA_PREFERENCE_ICON_URI, null);
        final String summaryUri = tile.metaData.getString(TileUtils.META_DATA_PREFERENCE_SUMMARY_URI, null);
        if (!TextUtils.isEmpty(iconUri)) {
            String packageName = null;
            if (tile.intent != null) {
                Intent intent = tile.intent;
                if (!TextUtils.isEmpty(intent.getPackage())) {
                    packageName = intent.getPackage();
                } else if (intent.getComponent() != null) {
                    packageName = intent.getComponent().getPackageName();
                }
            }
            Pair<String, Integer> icon = TileUtils.getIconFromUri(context, packageName, iconUri, providerMap);
            if (icon != null) {
                sIconCache.put(iconUri, icon);
                // Icon is only returned if the icon belongs to Settings or the target app.
                // setIcon must be called on the UI thread.
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            matchingPref.setIcon(context.getPackageManager()
                                    .getResourcesForApplication(icon.first /* package name */)
                                    .getDrawable(icon.second /* res id */, context.getTheme()));
                        } catch (PackageManager.NameNotFoundException | Resources.NotFoundException e) {
                            // Intentionally ignored. If icon resources cannot be found, do not
                            // update.
                        }
                    }
                });
            }
        }
        if (!TextUtils.isEmpty(summaryUri)) {
            String summary = TileUtils.getTextFromUri(context, summaryUri, providerMap,
                    TileUtils.META_DATA_PREFERENCE_SUMMARY);
            sSummaryCache.put(summaryUri, summary);
            // setSummary must be called on UI thread.
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // Only update the summary if it has actually changed.
                    if (summary == null) {
                        if (matchingPref.getSummary() != null) {
                            matchingPref.setSummary(summary);
                        }
                    } else if (!summary.equals(matchingPref.getSummary())) {
                        matchingPref.setSummary(summary);
                    }
                }
            });
        }
    }
}