Java Code Examples for android.support.annotation.UiThread

The following are top voted examples for showing how to use android.support.annotation.UiThread. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: q-mail   File: MessageLoaderHelper.java   View source code 6 votes vote down vote up
@UiThread
private void onLoadMessageFromDatabaseFinished() {
    if (callback == null) {
        throw new IllegalStateException("unexpected call when callback is already detached");
    }

    callback.onMessageDataLoadFinished(localMessage);

    boolean messageIncomplete =
            !localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL);
    if (messageIncomplete) {
        startDownloadingMessageBody(false);
        return;
    }

    if (QMail.isOpenPgpProviderConfigured()) {
        startOrResumeCryptoOperation();
        return;
    }

    startOrResumeDecodeMessage();
}
 
Example 2
Project: GitHub   File: Utils.java   View source code 6 votes vote down vote up
@UiThread // Implicit synchronization for use of shared resource VALUE.
public static Drawable getTintedDrawable(Context context,
    @DrawableRes int id, @AttrRes int tintAttrId) {
  boolean attributeFound = context.getTheme().resolveAttribute(tintAttrId, VALUE, true);
  if (!attributeFound) {
    throw new Resources.NotFoundException("Required tint color attribute with name "
        + context.getResources().getResourceEntryName(tintAttrId)
        + " and attribute ID "
        + tintAttrId
        + " was not found.");
  }

  Drawable drawable = ContextCompat.getDrawable(context, id);
  drawable = DrawableCompat.wrap(drawable.mutate());
  int color = ContextCompat.getColor(context, VALUE.resourceId);
  DrawableCompat.setTint(drawable, color);
  return drawable;
}
 
Example 3
Project: play-billing-codelab   File: GamePlayActivity.java   View source code 6 votes vote down vote up
/**
 * Show an alert dialog to the user
 * @param messageId String id to display inside the alert dialog
 * @param optionalParam Optional attribute for the string
 */
@UiThread
void alert(@StringRes int messageId, @Nullable Object optionalParam) {
    if (Looper.getMainLooper().getThread() != Thread.currentThread()) {
        throw new RuntimeException("Dialog could be shown only from the main thread");
    }

    AlertDialog.Builder bld = new AlertDialog.Builder(this);
    bld.setNeutralButton("OK", null);

    if (optionalParam == null) {
        bld.setMessage(messageId);
    } else {
        bld.setMessage(getResources().getString(messageId, optionalParam));
    }

    bld.create().show();
}
 
Example 4
Project: Elements   File: Pager.java   View source code 6 votes vote down vote up
@UiThread
/* package */ Page openPage(int number, boolean clearContent) {
    log("openPage: called for position "+number+" clearing "+clearContent);
    int objectsBefore = 0;
    for (int i = 0; i < number; i++) {
        objectsBefore += pages.get(i).getElementsCount();
    }
    if (number >= pages.size()) {
        // Need to create a new one.
        currentPage = new Page(number, objectsBefore);
        pages.add(number, currentPage);
    } else if (clearContent) {
        // We want an already present, but with cleared content.
        clearPage(number);
        currentPage = new Page(number, objectsBefore);
        pages.set(number, currentPage);
    } else {
        // We just want the current page. it'll be erased as soon as stuff comes.
        currentPage = pages.get(number);
    }
    return currentPage;
}
 
Example 5
Project: chromium-for-android-56-debug-video   File: ChromeStrictMode.java   View source code 6 votes vote down vote up
/**
 * Always process the violation on the UI thread. This ensures other crash reports are not
 * corrupted. Since each individual user has a very small chance of uploading each violation,
 * and we have a hard cap of 3 per session, this will not affect performance too much.
 *
 * @param violationInfo The violation info from the StrictMode violation in question.
 */
@UiThread
private static void reportStrictModeViolation(Object violationInfo) {
    try {
        Field crashInfoField = violationInfo.getClass().getField("crashInfo");
        ApplicationErrorReport.CrashInfo crashInfo =
                (ApplicationErrorReport.CrashInfo) crashInfoField.get(violationInfo);
        String stackTrace = crashInfo.stackTrace;
        if (stackTrace == null) {
            Log.d(TAG, "StrictMode violation stack trace was null.");
        } else {
            Log.d(TAG, "Upload stack trace: " + stackTrace);
            JavaExceptionReporter.reportStackTrace(stackTrace);
        }
    } catch (Exception e) {
        // Ignore all exceptions.
        Log.d(TAG, "Could not handle observed StrictMode violation.", e);
    }
}
 
Example 6
Project: android-api   File: NativeApiObject.java   View source code 6 votes vote down vote up
@UiThread
protected void destroyNativeHandle(Callable<Integer> destroyHandleCallable) {
    new NativeHandleFuture(destroyHandleCallable)
            .then(new Ready<Integer>() {
                @Override
                public void ready(Integer result) {
                    if (m_nativeHandle == null)
                        throw new RuntimeException();

                    if (!m_tasks.isEmpty())
                        throw new RuntimeException();

                    m_nativeHandle = null;
                }
            });
}
 
Example 7
Project: mvvm-template   File: AnimHelper.java   View source code 6 votes vote down vote up
@UiThread public static void dismissDialog(@NonNull DialogFragment dialogFragment, int duration, AnimatorListenerAdapter listenerAdapter) {
    Dialog dialog = dialogFragment.getDialog();
    if (dialog != null) {
        if (dialog.getWindow() != null) {
            View view = dialog.getWindow().getDecorView();
            if (view != null) {
                int centerX = view.getWidth() / 2;
                int centerY = view.getHeight() / 2;
                float radius = (float) Math.sqrt(view.getWidth() * view.getWidth() / 4 + view.getHeight() * view.getHeight() / 4);
                view.post(() -> {
                    if (ViewCompat.isAttachedToWindow(view)) {
                        Animator animator = ViewAnimationUtils.createCircularReveal(view, centerX, centerY, radius, 0);
                        animator.setDuration(duration);
                        animator.addListener(listenerAdapter);
                        animator.start();
                    } else {
                        listenerAdapter.onAnimationEnd(null);
                    }
                });
            }
        }
    } else {
        listenerAdapter.onAnimationEnd(null);
    }
}
 
Example 8
Project: android-api   File: EegeoNativeMapView.java   View source code 6 votes vote down vote up
@UiThread
public void surfaceCreated(final SurfaceHolder holder) {
    runOnNativeThread(new Runnable() {
        @WorkerThread
        @Override
        public void run() {
            m_surfaceHolder = holder;
            Surface surface = m_surfaceHolder.getSurface();
            if (surface.isValid()) {
                nativeSetSurface(m_jniApiRunnerPtr, surface);
                notifySurfaceCreated();

            }
        }
    });
}
 
Example 9
Project: android-api   File: EegeoMap.java   View source code 5 votes vote down vote up
/**
 * Stops any running camera animation.
 */
@UiThread
public void stopAnimation() {
    m_nativeRunner.runOnNativeThread(new Runnable() {
        @Override
        public void run() {
            CameraApiJniCalls.tryStopTransition(m_eegeoMapApiPtr);
        }
    });
}
 
Example 10
Project: android-api   File: BlueSphere.java   View source code 5 votes vote down vote up
@UiThread
private void updateIndoors() {
    final String indoorMap = m_indoorMapId;
    final int floorId = m_indoorFloorId;

    submit(new Runnable() {
        @WorkerThread
        public void run() {
            m_bluesphereApi.setIndoorMap(BlueSphere.m_allowHandleAccess, indoorMap, floorId);
        }
    });
}
 
Example 11
Project: Nird2   File: ScreenFilterMonitorImpl.java   View source code 5 votes vote down vote up
@Override
@UiThread
public Set<String> getApps() {
	if (!serviceStarted) {
		apps.addAll(getInstalledScreenFilterApps());
	}
	TreeSet<String> buf = new TreeSet<>();
	if (apps.isEmpty()) {
		return buf;
	}
	buf.addAll(apps);
	buf.removeAll(shownApps);
	return buf;
}
 
Example 12
Project: Nird2   File: CameraView.java   View source code 5 votes vote down vote up
@UiThread
private void surfaceCreatedUi(SurfaceHolder holder) {
	LOG.info("Surface created");
	if (surface != null && surface != holder.getSurface()) {
		LOG.info("Releasing old surface");
		surface.release();
	}
	surface = holder.getSurface();
	// Start the preview when the camera and the surface are both ready
	if (camera != null && !previewStarted) startPreview(holder);
}
 
Example 13
Project: Watermark   File: MvpNullObjectBasePresenter.java   View source code 5 votes vote down vote up
@UiThread
@NonNull protected V getView() {
    if (!viewAttachedAtLeastOnce){
        throw new IllegalStateException("No view has ever been attached to this presenter!");
    }
    if (view != null) {
        V realView = view.get();
        if (realView != null) {
            return realView;
        }
    }

    return nullView;
}
 
Example 14
Project: GitHub   File: Utils.java   View source code 5 votes vote down vote up
@UiThread // Implicit synchronization for use of shared resource VALUE.
public static float getFloat(Context context, @DimenRes int id) {
  TypedValue value = VALUE;
  context.getResources().getValue(id, value, true);
  if (value.type == TypedValue.TYPE_FLOAT) {
    return value.getFloat();
  }
  throw new Resources.NotFoundException("Resource ID #0x" + Integer.toHexString(id)
      + " type #0x" + Integer.toHexString(value.type) + " is not valid");
}
 
Example 15
Project: Elements   File: Pager.java   View source code 5 votes vote down vote up
/**
 * Remove the specified element from this page, if present.
 * @param element element to be removed
 */
@UiThread
public void removeElement(Element element) {
    int position = this.elements.indexOf(element);
    if (position != -1) {
        removeElement(position);
    }
}
 
Example 16
Project: android-api   File: Polygon.java   View source code 5 votes vote down vote up
@UiThread
private void updateNativeStyleAttributes() {
    final int fillColorARGB = m_fillColorARGB;

    submit(new Runnable() {
        @WorkerThread
        public void run() {
            m_polygonApi.setStyleAttributes(
                    getNativeHandle(),
                    Polygon.m_allowHandleAccess,
                    fillColorARGB);
        }
    });
}
 
Example 17
Project: pokequest   File: HomeActivity.java   View source code 5 votes vote down vote up
@UiThread
private void onLoadPokemonError() {
    new AlertDialog.Builder(this)
        .setTitle(R.string.loading_error)
        .setMessage(R.string.loading_pokemon_list_error_msg)
        .setPositiveButton(R.string.retry, (dialog, which) -> loadPokemons())
        .setNegativeButton(R.string.cancel, null)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .show();
}
 
Example 18
Project: ChipsLayoutManager   File: RTLRowTest.java   View source code 5 votes vote down vote up
@UiThread
@Override
protected ChipsLayoutManager getLayoutManager() {
    ChipsLayoutManager layoutManager = super.getLayoutManager();
    if (activityTestRule.getActivity() != null) {
        View recyclerView = activityTestRule.getActivity().findViewById(R.id.rvTest);
        ViewCompat.setLayoutDirection(recyclerView, ViewCompat.LAYOUT_DIRECTION_RTL);
    }
    return layoutManager;
}
 
Example 19
Project: FriendBook   File: MvpBasePresenter.java   View source code 5 votes vote down vote up
@UiThread
@Override
public void destroy() {
    if (isViewAttached()) {
        detachView();
    }
}
 
Example 20
Project: Nird2   File: AndroidNotificationManagerImpl.java   View source code 5 votes vote down vote up
@UiThread
private void clearGroupMessageNotification() {
	groupCounts.clear();
	groupTotal = 0;
	Object o = appContext.getSystemService(NOTIFICATION_SERVICE);
	NotificationManager nm = (NotificationManager) o;
	nm.cancel(GROUP_MESSAGE_NOTIFICATION_ID);
}
 
Example 21
Project: Nird2   File: AndroidNotificationManagerImpl.java   View source code 5 votes vote down vote up
@UiThread
private void clearForumPostNotification() {
	forumCounts.clear();
	forumTotal = 0;
	Object o = appContext.getSystemService(NOTIFICATION_SERVICE);
	NotificationManager nm = (NotificationManager) o;
	nm.cancel(FORUM_POST_NOTIFICATION_ID);
}
 
Example 22
Project: Nird2   File: ScreenFilterMonitorImpl.java   View source code 5 votes vote down vote up
@Override
@UiThread
public Set<String> getApps() {
	if (!serviceStarted) {
		apps.addAll(getInstalledScreenFilterApps());
	}
	TreeSet<String> buf = new TreeSet<>();
	if (apps.isEmpty()) {
		return buf;
	}
	buf.addAll(apps);
	buf.removeAll(shownApps);
	return buf;
}
 
Example 23
Project: gmlrva   File: GenericMultipleLayoutAdapter.java   View source code 5 votes vote down vote up
/**
 * Procedure meant to remove a list of Generic Layout Implementation items on this adapter's data set.
 * @param items the list of Generic Layout Implementation items to be removed.
 *              See {@link IGenericRecyclerViewLayout} for more information.
 */
@UiThread
public void remove(@NonNull final List<IGenericRecyclerViewLayout> items) {
    final List<IGenericRecyclerViewLayout> newList
            = new ArrayList<>(mPendingUpdates.isEmpty() ? mDataSet : mPendingUpdates.peekLast());
    if (!newList.isEmpty() && !items.isEmpty()) {
        newList.removeAll(items);
        updateList(newList);
    }
}
 
Example 24
Project: Nird2   File: CameraView.java   View source code 5 votes vote down vote up
@UiThread
private void startPreview(SurfaceHolder holder) {
	LOG.info("Starting preview");
	try {
		camera.setPreviewDisplay(holder);
		camera.startPreview();
		previewStarted = true;
		startConsumer();
	} catch (IOException | RuntimeException e) {
		LOG.log(WARNING, "Error starting camera preview", e);
	}
}
 
Example 25
Project: android-api   File: RouteView.java   View source code 5 votes vote down vote up
/**
 * Sets the width of this RouteView's polylines.
 *
 * @param width The width of the polyline in screen pixels.
 */
@UiThread
public void setWidth(float width) {
    m_width = width;
    for (Polyline polyline: m_polylines) {
        polyline.setWidth(m_width);
    }
}
 
Example 26
Project: android-api   File: Polygon.java   View source code 5 votes vote down vote up
/**
 * This constructor is for internal SDK use only -- use EegeoMap.addPolygon to create a polygon
 *
 * @eegeo.internal
 */
@UiThread
public Polygon(@NonNull final PolygonApi polygonApi,
              @NonNull final PolygonOptions polygonOptions) {
    super(polygonApi.getNativeRunner(), polygonApi.getUiRunner(),
            new Callable<Integer>() {
                @WorkerThread
                @Override
                public Integer call() throws Exception {
                    return polygonApi.create(polygonOptions, m_allowHandleAccess);
                }
            });

    m_polygonApi = polygonApi;
    m_indoorMapId = polygonOptions.getIndoorMapId();
    m_indoorFloorId = polygonOptions.getIndoorFloorId();
    m_elevation = polygonOptions.getElevation();
    m_elevationMode = polygonOptions.getElevationMode();
    m_points = polygonOptions.getPoints();
    m_holes = polygonOptions.getHoles();
    m_fillColorARGB = polygonOptions.getFillColor();

    submit(new Runnable() {
        @WorkerThread
        @Override
        public void run() {
            polygonApi.register(Polygon.this, m_allowHandleAccess);
        }
    });
}
 
Example 27
Project: Nird2   File: CameraView.java   View source code 5 votes vote down vote up
@UiThread
public void stop() {
	if (camera == null) return;
	stopPreview();
	try {
		LOG.info("Releasing camera");
		camera.release();
	} catch (RuntimeException e) {
		LOG.log(WARNING, "Error releasing camera", e);
	}
	camera = null;
}
 
Example 28
Project: play-billing-codelab   File: GamePlayActivity.java   View source code 5 votes vote down vote up
/**
 * Update UI to reflect model
 */
@UiThread
private void updateUi() {
    Log.d(TAG, "Updating the UI. Thread: " + Thread.currentThread().getName());

    // Update gas gauge to reflect tank status
    mGasImageView.setImageResource(mViewController.getTankResId());
}
 
Example 29
Project: Nird2   File: ShowQrCodeFragment.java   View source code 5 votes vote down vote up
@UiThread
private void generateBitmapQR(final Payload payload) {
	// Get narrowest screen dimension
	Context context = getContext();
	if (context == null) return;
	final DisplayMetrics dm = context.getResources().getDisplayMetrics();
	new AsyncTask<Void, Void, Bitmap>() {

		@Override
		protected Bitmap doInBackground(Void... params) {
			byte[] encoded = payloadEncoder.encode(payload);
			if (LOG.isLoggable(INFO))
				LOG.info("Local payload is " + encoded.length + " bytes");
			String input = Base64.encodeToString(encoded, 0);
			return QrCodeUtils.createQrCode(dm, input);
		}

		@Override
		protected void onPostExecute(@Nullable Bitmap bitmap) {
			if (bitmap != null && !isDetached()) {
				qrCode.setImageBitmap(bitmap);
				// Simple fade-in animation
				AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
				anim.setDuration(200);
				qrCode.startAnimation(anim);
			}
		}
	}.execute();
}
 
Example 30
Project: gmlrva   File: GenericMultipleLayoutAdapter.java   View source code 5 votes vote down vote up
/**
 * Procedure meant to insert a Generic Layout Implementation item on this adapter's data set.
 * @param item a Generic Layout Implementation item to be inserted.
 *             See {@link IGenericRecyclerViewLayout} for more information.
 */
@UiThread
public void add(@NonNull final IGenericRecyclerViewLayout item) {
    final List<IGenericRecyclerViewLayout> newList
            = new ArrayList<>(mPendingUpdates.isEmpty() ? mDataSet : mPendingUpdates.peekLast());
    newList.add(item);
    updateList(newList);
}
 
Example 31
Project: Nird2   File: AndroidNotificationManagerImpl.java   View source code 5 votes vote down vote up
@UiThread
private int getDefaults() {
	int defaults = DEFAULT_LIGHTS;
	boolean sound = settings.getBoolean(PREF_NOTIFY_SOUND, true);
	String ringtoneUri = settings.get(PREF_NOTIFY_RINGTONE_URI);
	if (sound && StringUtils.isNullOrEmpty(ringtoneUri))
		defaults |= DEFAULT_SOUND;
	if (settings.getBoolean(PREF_NOTIFY_VIBRATION, true))
		defaults |= DEFAULT_VIBRATE;
	return defaults;
}
 
Example 32
Project: chromium-for-android-56-debug-video   File: BookmarkWidgetService.java   View source code 5 votes vote down vote up
@UiThread
private void loadBookmarks(BookmarkId folderId) {
    mFolder = new BookmarkFolder();

    // Load the requested folder if it exists. Otherwise, fall back to the default folder.
    if (folderId != null) {
        mFolder.folder = Bookmark.fromBookmarkItem(mBookmarkModel.getBookmarkById(
                folderId));
    }
    if (mFolder.folder == null) {
        folderId = mBookmarkModel.getDefaultFolder();
        mFolder.folder = Bookmark.fromBookmarkItem(mBookmarkModel.getBookmarkById(
                folderId));
    }

    mFolder.parent = Bookmark.fromBookmarkItem(mBookmarkModel.getBookmarkById(
            mFolder.folder.parentId));

    List<BookmarkItem> items = mBookmarkModel.getBookmarksForFolder(folderId);

    // Move folders to the beginning of the list.
    Collections.sort(items, new Comparator<BookmarkItem>() {
        @Override
        public int compare(BookmarkItem lhs, BookmarkItem rhs) {
            return lhs.isFolder() == rhs.isFolder() ? 0 : lhs.isFolder() ? -1 : 1;
        }
    });

    for (BookmarkItem item : items) {
        Bookmark bookmark = Bookmark.fromBookmarkItem(item);
        loadFavicon(bookmark);
        mFolder.children.add(bookmark);
    }

    taskFinished();
}
 
Example 33
Project: android-api   File: EegeoNativeMapView.java   View source code 5 votes vote down vote up
@UiThread
public void onPointerMove(final int primaryActionIndex, final int primaryActionIdentifier, final int pointerCount, final float[] x, final float y[], final int[] pointerIdentity, final int[] pointerIndex) {
    runOnNativeThread(new Runnable() {
        @WorkerThread
        @Override
        public void run() {
            nativeProcessPointerMove(m_jniApiRunnerPtr, primaryActionIndex, primaryActionIdentifier, pointerCount, x, y, pointerIdentity, pointerIndex);
        }
    });

}
 
Example 34
Project: GitHub   File: MaterialDialog.java   View source code 5 votes vote down vote up
/**
 * Convenience method for setting the currently selected indices of a multi choice list. This
 * only works if you are not using a custom adapter; if you're using a custom adapter, an
 * IllegalStateException is thrown. Note that this does not call the respective multi choice
 * callback.
 *
 * @param indices The indices of the list items to check.
 */
@UiThread
public void setSelectedIndices(@NonNull Integer[] indices) {
    selectedIndicesList = new ArrayList<>(Arrays.asList(indices));
    if (builder.adapter != null && builder.adapter instanceof DefaultRvAdapter) {
        builder.adapter.notifyDataSetChanged();
    } else {
        throw new IllegalStateException("You can only use setSelectedIndices() with the default adapter implementation.");
    }
}
 
Example 35
Project: Quran   File: RecentPageModel.java   View source code 5 votes vote down vote up
@UiThread
public void updateLatestPage(int page) {
  if (initialDataSubscription != null) {
    // it is possible (though unlikely) for a page update to come in while we're still waiting
    // for the initial query of recent pages from the database. if so, unsubscribe from the initial
    // query since its data will be stale relative to this data.
    initialDataSubscription.dispose();
  }
  lastPageSubject.onNext(page);
}
 
Example 36
Project: mapbox-events-android   File: ConnectivityReceiver.java   View source code 5 votes vote down vote up
@UiThread
public void removeConnectivityUpdates() {
  activationCounter--;
  if (activationCounter == 0) {
    context.unregisterReceiver(this);
  }
}
 
Example 37
Project: butterknife-parent   File: Utils.java   View source code 5 votes vote down vote up
@UiThread // Implicit synchronization for use of shared resource VALUE.
public static float getFloat(Context context, @DimenRes int id) {
  TypedValue value = VALUE;
  context.getResources().getValue(id, value, true);
  if (value.type == TypedValue.TYPE_FLOAT) {
    return value.getFloat();
  }
  throw new Resources.NotFoundException("Resource ID #0x" + Integer.toHexString(id)
      + " type #0x" + Integer.toHexString(value.type) + " is not valid");
}
 
Example 38
Project: android-api   File: EegeoNativeMapView.java   View source code 5 votes vote down vote up
@UiThread
public void postTo(Runnable runnable) {
    if (!m_threadExiting) {
        m_nativeThreadHandler.post(runnable);
    } else {
        Log.d("eegeo-android-sdk", "thread exiting, ignoring runnable");
    }
}
 
Example 39
Project: android-api   File: EegeoNativeMapView.java   View source code 5 votes vote down vote up
@UiThread
public void quit() {
    //m_nativeThreadHandler.dump(new LogPrinter(Log.DEBUG, "eegeo-android-sdk"), "");
    m_threadExiting = true;
    m_nativeThreadHandler.removeCallbacksAndMessages(null);
    m_nativeThreadHandler.post(new Runnable() {
        @WorkerThread
        @Override
        public void run() {
            Looper.myLooper().quit();
        }
    });
}
 
Example 40
Project: android-api   File: MapView.java   View source code 5 votes vote down vote up
/**
 * Constructor for a MapView object.
 *
 * @param context      The Android context for the view.
 * @param attributeSet Attributes which may be used to initialize the view.  Attributes may be defined
 *                     in the view's layout xml by setting eegeo_MapView styleable resources.
 */
@UiThread
public MapView(@NonNull Context context, AttributeSet attributeSet) {
    super(context, attributeSet);
    if (isInEditMode()) {
        LayoutInflater.from(context).inflate(R.layout.eegeo_mapview_preview, this);
    } else {
        EegeoMapOptions eegeoMapOptions = EegeoMapOptions.createFromAttributeSet(context, attributeSet);
        initialise(context, eegeoMapOptions);
    }
}