下面列出了怎么用androidx.annotation.UiThread的API类实例代码及写法,或者点击链接到github查看源代码。
@NonNull
@UiThread
public List<BaseCard> findAndRemoveFaceUpCards() {
List<BaseCard> faceUp = new ArrayList<>();
for (int i = 0; i < cards.size(); i++) {
CardsGroup group = cards.get(i);
if (!group.isUnknwon()) {
faceUp.addAll(group);
cards.remove(i);
notifyItemRemoved(i);
break;
}
}
return faceUp;
}
@UiThread
public static ListenableFuture<IdentityRecord> getRemoteIdentityKey(final Context context, final Recipient recipient) {
final SettableFuture<IdentityRecord> future = new SettableFuture<>();
Observable.create(new ObservableOnSubscribe<IdentityRecord>() {
@Override
public void subscribe(ObservableEmitter<IdentityRecord> emitter) throws Exception {
emitter.onNext(Repository.getIdentityRepo(recipient.getAddress().context()).getIdentityRecord(recipient.getAddress().serialize()));
emitter.onComplete();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> future.set(result), throwable -> future.set(null));
return future;
}
@UiThread
public static SpiderQueen obtainSpiderQueen(@NonNull Context context,
@NonNull GalleryInfo galleryInfo, @Mode int mode) {
OSUtils.checkMainLoop();
SpiderQueen queen = sQueenMap.get(galleryInfo.getCid());
if (queen == null) {
EhApplication application = (EhApplication) context.getApplicationContext();
queen = new SpiderQueen(application, galleryInfo);
sQueenMap.put(galleryInfo.getCid(), queen);
// Set mode
queen.setMode(mode);
queen.start();
} else {
// Set mode
queen.setMode(mode);
}
return queen;
}
@UiThread
@Nullable
public GeckoResult<boolean[]> getVisited(@NonNull GeckoSession geckoSession, @NonNull String[] urls) {
if (mSession.isPrivateMode()) {
return GeckoResult.fromValue(new boolean[]{});
}
GeckoResult<boolean[]> result = new GeckoResult<>();
SessionStore.get().getHistoryStore().getVisited(Arrays.asList(urls)).thenAcceptAsync(list -> {
final boolean[] primitives = new boolean[list.size()];
int index = 0;
for (Boolean object : list) {
primitives[index++] = object;
}
result.complete(primitives);
}, mUIThreadExecutor).exceptionally(throwable -> {
Log.d(LOGTAG, "Error getting history: " + throwable.getLocalizedMessage());
throwable.printStackTrace();
return null;
});
return result;
}
@UiThread
private HttpClient(@NonNull MultiProfile.UserProfile profile, @NonNull OnConnect connectionListener, boolean close) throws GeneralSecurityException, IOException, NetUtils.InvalidUrlException {
this(profile);
executorService.submit(() -> {
try (Socket socket = new Socket()) {
final long initializedAt = System.currentTimeMillis();
socket.connect(new InetSocketAddress(profile.serverAddr, profile.serverPort), (int) TimeUnit.SECONDS.toMillis(Prefs.getInt(PK.A2_NETWORK_TIMEOUT)));
handler.post(() -> {
if (connectionListener.onConnected(HttpClient.this))
connectionListener.onPingTested(HttpClient.this, System.currentTimeMillis() - initializedAt);
});
if (close) close();
} catch (IOException ex) {
handler.post(() -> connectionListener.onFailedConnecting(profile, ex));
close();
}
});
}
/**
* Sets the completer and the size. The completer will only be set if the current size of
* the Surface matches the target size.
*/
@UiThread
void setSurfaceRequest(@NonNull SurfaceRequest surfaceRequest) {
cancelPreviousRequest();
mSurfaceRequest = surfaceRequest;
Size targetSize = surfaceRequest.getResolution();
mTargetSize = targetSize;
if (!tryToComplete()) {
// The current size is incorrect. Wait for it to change.
Log.d(TAG, "Wait for new Surface creation.");
mSurfaceView.getHolder().setFixedSize(targetSize.getWidth(),
targetSize.getHeight());
}
}
@UiThread
void playerChange(@NonNull GameInfo.Player player) {
playerChange(player, players);
for (int i = 0; i < players.size(); i++) {
if (players.get(i).name.equals(player.name)) {
synchronized (players) {
players.set(i, player);
}
if (playersInterface != null) playersInterface.notifyItemChanged(i);
return;
}
}
}
@UiThread
private void cancelPreviousRequest() {
if (mSurfaceRequest != null) {
Log.d(TAG, "Request canceled: " + mSurfaceRequest);
mSurfaceRequest.willNotProvideSurface();
mSurfaceRequest = null;
}
mTargetSize = null;
}
@UiThread
public CardsAdapter(boolean forGrid, List<? extends BaseCard> cards, @Nullable GameCardView.Action primary, @Nullable GameCardView.Action secondary, boolean isSelectable, @NonNull Listener listener) {
this.primary = primary;
this.secondary = secondary;
this.isSelectable = isSelectable;
this.listener = listener;
this.cards = new ArrayList<>();
this.forGrid = forGrid;
addCardsAsSingleton(cards);
notifyDataSetChanged();
}
@Override
@UiThread
public void error(String errorCode, String errorMessage, Object errorDetails) {
if (hasEnded.get() || streams.get(id).sink != this) {
return;
}
StreamsChannel.this.messenger.send(
name,
codec.encodeErrorEnvelope(errorCode, errorMessage, errorDetails));
}
@UiThread
private void displayAppList(List<AppInfo> appInfoList) {
if (mWorkInAllowMode) {
mView.showAllowAppList(appInfoList);
} else {
mView.showBlockAppList(appInfoList);
}
}
@UiThread
void updateBadge(E which, int badgeNumber) {
int pos = indexOf(which);
if (pos != -1) {
BaseDrawerItem item = items.get(pos);
if (item.badgeNumber != badgeNumber) {
item.badgeNumber = badgeNumber;
notifyItemChanged(pos);
}
}
}
@UiThread
void setActiveItem(E which) {
int pos = indexOf(which);
for (int i = 0; i < getItemCount(); i++) {
BaseDrawerItem item = items.get(i);
boolean active = i == pos;
if (item.active != active) {
item.active = active;
notifyItemChanged(pos);
}
}
}
@UiThread
void update(@NonNull GameInfo info, @Nullable GameCards cards, @Nullable GameLayout layout) {
update(info.game);
List<GameInfo.Player> oldPlayers = new ArrayList<>(players);
synchronized (players) {
players.clear();
players.addAll(info.players);
}
if (layout != null) {
layout.setup(this);
if (cards != null) {
layout.setHand(cards.hand);
layout.setBlackCard(cards.blackCard);
layout.setTable(cards.whiteCards, cards.blackCard);
}
}
synchronized (spectators) {
for (String spectator : spectators) {
if (spectator.equals(me))
listener.playerIsSpectator();
}
}
synchronized (players) {
for (GameInfo.Player player : players)
playerChange(player, oldPlayers);
}
if (playersInterface != null)
playersInterface.dispatchUpdate(DiffUtil.calculateDiff(new PlayersDiff(oldPlayers, players), false));
}
@UiThread
public void tryShowingTutorials(final Activity activity) {
if (isShowingTutorial || !DialogUtils.isContextValid(activity)) return;
for (BaseTutorial tutorial : tutorials) {
if (shouldShowFor(tutorial) && listener.canShow(tutorial)) {
show(activity, tutorial);
return;
}
}
}
@UiThread
private void show(@NonNull Activity activity, @NonNull final BaseTutorial tutorial) {
tutorial.newSequence(activity);
if (listener.buildSequence(tutorial)) {
isShowingTutorial = true;
activity.runOnUiThread(() -> tutorial.show(TutorialManager.this));
}
}
@UiThread
public static void start() {
// Call Telemetry.scheduleUpload() early.
// See https://github.com/MozillaReality/FirefoxReality/issues/1353
TelemetryHolder.get()
.queuePing(TelemetryCorePingBuilder.TYPE)
.queuePing(TelemetryMobileEventPingBuilder.TYPE)
.scheduleUpload();
TelemetryHolder.get().recordSessionStart();
TelemetryEvent.create(Category.ACTION, Method.FOREGROUND, Object.APP).queue();
}
@UiThread
public static void urlBarEvent(boolean aIsUrl) {
if (aIsUrl) {
TelemetryWrapper.browseEvent();
} else {
TelemetryWrapper.searchEnterEvent();
}
}
@UiThread
public static void urlBarEvent(boolean aIsUrl) {
if (aIsUrl) {
Url.INSTANCE.getQueryType().get("type_link").add();
} else {
Url.INSTANCE.getQueryType().get("type_query").add();
// Record search engines.
String searchEngine = getDefaultSearchEngineIdentifierForTelemetry();
Searches.INSTANCE.getCounts().get(searchEngine).add();
}
}
@UiThread
public static void voiceInputEvent() {
Url.INSTANCE.getQueryType().get("voice_query").add();
// Record search engines.
String searchEngine = getDefaultSearchEngineIdentifierForTelemetry();
Searches.INSTANCE.getCounts().get(searchEngine).add();
}
@UiThread
@Nullable
public GeckoResult<boolean[]> getVisited(@NonNull GeckoSession aSession, @NonNull String[] urls) {
if (mState.mSession == aSession) {
if (mHistoryDelegate != null) {
return mHistoryDelegate.getVisited(aSession, urls);
} else {
final GeckoResult<boolean[]> response = new GeckoResult<>();
mQueuedCalls.add(() -> {
if (mHistoryDelegate != null) {
try {
requireNonNull(mHistoryDelegate.getVisited(aSession, urls)).then(aBoolean -> {
response.complete(aBoolean);
return null;
}).exceptionally(throwable -> {
Log.d(LOGTAG, "Null GeckoResult from getVisited");
return null;
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
return response;
}
}
return GeckoResult.fromValue(new boolean[]{});
}
@UiThread
private WebSocketClient(@NonNull MultiProfile.UserProfile profile, boolean close) throws GeneralSecurityException, NetUtils.InvalidUrlException, IOException {
super(profile);
webSocket = new WeakReference<>(client.newWebSocket(NetUtils.createWebsocketRequest(profile), new Listener()));
initializedAt = System.currentTimeMillis();
closeAfterTest = close;
}
@UiThread
public void setCardGroups(List<CardsGroup> cards, @Nullable BaseCard blackCard) {
if (blackCard != null) {
for (CardsGroup group : cards) {
if (group.isUnknwon()) {
for (int i = 1; i < blackCard.numPick(); i++)
group.add(Card.newBlankCard());
}
}
}
this.cards.clear();
this.cards.addAll(cards);
notifyDataSetChanged();
}
@UiThread
public void removeCard(@NonNull BaseCard card) {
for (int i = cards.size() - 1; i >= 0; i--) {
CardsGroup group = cards.get(i);
if (group.contains(card)) {
cards.remove(i);
notifyItemRemoved(i);
break;
}
}
}
@UiThread
private HttpClient(@NonNull MultiProfile.UserProfile profile) throws GeneralSecurityException, IOException, NetUtils.InvalidUrlException {
super(profile);
ErrorHandler.get().unlock();
this.executorService = Executors.newCachedThreadPool();
this.url = NetUtils.createHttpURL(profile);
}
@UiThread
public void update(@NonNull DownloadWithUpdate download, @NonNull AriaFiles files) {
AriaDirectory dir = AriaDirectory.createRoot(download, files);
if (currentDir == null) {
changeDir(dir);
} else {
AriaDirectory currentDirUpdated = dir.findDirectory(currentDir.path);
if (currentDirUpdated == null) changeDir(dir);
else updateDir(currentDirUpdated);
}
}
@UiThread
private void publishResult(MultiProfile.UserProfile profile, MultiProfile.TestStatus status) {
if (profileListener != null) {
profileListener.statusUpdated(profile.getParent().id, status);
return;
}
switch (status.status) {
case OFFLINE:
publishMessage("Host is offline, check your connection parameters", Level.ERROR);
break;
case ERROR:
publishMessage("Failed establishing a connection", Level.ERROR);
break;
case ONLINE:
publishMessage("Host is online, connection parameters are configured correctly", Level.SUCCESS);
break;
default:
case UNKNOWN:
break;
}
if (status.ex != null) {
if (status.ex.getMessage() == null) {
Throwable cause = status.ex.getCause();
if (cause != null && cause.getMessage() != null)
publishMessage(cause.getMessage(), Level.ERROR);
} else {
publishMessage(status.ex.getMessage(), Level.ERROR);
}
}
}
@UiThread
void resetToIdleAndHost() {
synchronized (players) {
for (GameInfo.Player player : players) {
if (player.name.equals(host)) player.status = GameInfo.PlayerStatus.HOST;
else player.status = GameInfo.PlayerStatus.IDLE;
}
}
playersInterface.clearPool();
playersInterface.notifyDataSetChanged();
}
@Override
@UiThread
public void endOfStream() {
if (hasEnded.getAndSet(true) || streams.get(id).sink != this) {
return;
}
StreamsChannel.this.messenger.send(name, null);
}
@UiThread
public void remove(Download download) {
int index = indexOf(download);
if (index != -1) {
downloads.remove(index);
notifyItemRemoved(index);
}
}