下面列出了怎么用android.support.annotation.UiThread的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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();
}
/** {@see ConnectionsActivity#onReceive(Endpoint, Payload)} */
@Override
protected void onReceive(Endpoint endpoint, Payload payload) {
if (payload.getType() == Payload.Type.STREAM) {
AudioPlayer player =
new AudioPlayer(payload.asStream().asInputStream()) {
@WorkerThread
@Override
protected void onFinish() {
final AudioPlayer audioPlayer = this;
post(
new Runnable() {
@UiThread
@Override
public void run() {
mAudioPlayers.remove(audioPlayer);
}
});
}
};
mAudioPlayers.add(player);
player.start();
}
}
/** Transitions from the old state to the new state with an animation implying moving backward. */
@UiThread
private void transitionBackward(State oldState, final State newState) {
mPreviousStateView.setVisibility(View.VISIBLE);
mCurrentStateView.setVisibility(View.VISIBLE);
updateTextView(mCurrentStateView, oldState);
updateTextView(mPreviousStateView, newState);
if (ViewCompat.isLaidOut(mCurrentStateView)) {
mCurrentAnimator = createAnimator(true /* reverse */);
mCurrentAnimator.addListener(
new AnimatorListener() {
@Override
public void onAnimationEnd(Animator animator) {
updateTextView(mCurrentStateView, newState);
}
});
mCurrentAnimator.start();
}
}
@UiThread
private void checkAndConnect() {
log("checkAndConnect");
if (!Utils.isServiceInstalled()) {
showConnectFail(FAIL_REASON_NOT_INSTALLED);
return;
}
layout.setHeaderText(R.string.wizard_connect);
checkPermissionAndRun(() -> {
log("Checking pass");
if (mConnectTask != null && !mConnectTask.isCancelled()) {
mConnectTask.cancel(true);
mConnectTask = null;
}
mConnectTask = new ConnectTask();
mConnectTask.execute();
});
}
@UiThread
public void start() {
mStartTime = System.currentTimeMillis();
if (Looper.getMainLooper() != Looper.myLooper()) {
throw new RuntimeException("must be called from UiThread");
}
if (mAllTasks.size() > 0) {
mAnalyseCount.getAndIncrement();
printDependedMsg();
mAllTasks = TaskSortUtil.getSortResult(mAllTasks, mClsAllTasks);
mCountDownLatch = new CountDownLatch(mNeedWaitCount.get());
sendAndExecuteAsyncTasks();
DispatcherLog.i("task analyse cost " + (System.currentTimeMillis() - mStartTime) + " begin main ");
executeTaskMain();
}
DispatcherLog.i("task analyse cost startTime cost " + (System.currentTimeMillis() - mStartTime));
}
@UiThread
public void extendRangeInto(int[] range, int[] outRange, int scrollHint) {
int i;
int fullRange = (range[1] - range[0]) + 1;
int halfRange = fullRange / 2;
int i2 = range[0];
if (scrollHint == 1) {
i = fullRange;
} else {
i = halfRange;
}
outRange[0] = i2 - i;
i = range[1];
if (scrollHint != 2) {
fullRange = halfRange;
}
outRange[1] = i + fullRange;
}
/**
* start asynchronous compress thread
*/
@UiThread
private void launch(final Context context) {
if (mFile == null && onCompressListener != null) {
onCompressListener.onError(new NullPointerException("image mFile cannot be null"));
}
new Thread(new Runnable() {
@Override
public void run() {
try {
mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_START));
File result = new Engine(mFile, getImageCacheFile(context), mFilterSize).compress();
mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_SUCCESS, result));
} catch (IOException e) {
mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_ERROR, e));
}
}
}).start();
}
/**
* Cancels the sequence, if the current target is cancelable.
* When the sequence is canceled, the current target is dismissed and the remaining targets are
* removed from the sequence.
* @return whether the sequence was canceled or not
*/
@UiThread
public boolean cancel() {
if (targets.isEmpty() || !active) {
return false;
}
if (currentView == null || !currentView.cancelable) {
return false;
}
currentView.dismiss(false);
active = false;
targets.clear();
if (listener != null) {
listener.onSequenceCanceled(currentView.target);
}
return true;
}
/**
* 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();
}
@UiThread
public static NotificationCenter getInstance(int num)
{
NotificationCenter localInstance = Instance[num];
if (localInstance == null)
{
synchronized (NotificationCenter.class)
{
localInstance = Instance[num];
if (localInstance == null)
{
Instance[num] = localInstance = new NotificationCenter(num);
}
}
}
return localInstance;
}
@UiThread
public static NotificationCenter getGlobalInstance()
{
NotificationCenter localInstance = globalInstance;
if (localInstance == null)
{
synchronized (NotificationCenter.class)
{
localInstance = globalInstance;
if (localInstance == null)
{
globalInstance = localInstance = new NotificationCenter(-1);
}
}
}
return localInstance;
}
@Override
@UiThread
public void createWriteOrEmulateDataOperation(AppCompatActivity activity, CardData cardData,
boolean write, int callbackId) {
ensureOperationCreatedCallbackSupported(activity);
((OnOperationCreatedCallback) activity).onOperationCreated(
new WriteOrEmulateHIDOperation(this, cardData, write), callbackId);
}
/** {@see ConnectionsActivity#onReceive(Endpoint, Payload)} */
@Override
protected void onReceive(Endpoint endpoint, Payload payload) {
if (payload.getType() == Payload.Type.STREAM) {
if (mAudioPlayer != null) {
mAudioPlayer.stop();
mAudioPlayer = null;
}
AudioPlayer player =
new AudioPlayer(payload.asStream().asInputStream()) {
@WorkerThread
@Override
protected void onFinish() {
runOnUiThread(
new Runnable() {
@UiThread
@Override
public void run() {
mAudioPlayer = null;
}
});
}
};
mAudioPlayer = player;
player.start();
}
}
@Override
@UiThread
public void createReadCardDataOperation(AppCompatActivity activity,
Class<? extends CardData> cardDataClass, int callbackId) {
ensureOperationCreatedCallbackSupported(activity);
throw new UnsupportedOperationException("Device does not support ReadCardDataOperation");
}
@Override
@UiThread
public void createReadCardDataOperation(AppCompatActivity activity,
Class<? extends CardData> cardDataClass, int callbackId) {
ensureOperationCreatedCallbackSupported(activity);
((OnOperationCreatedCallback) activity).onOperationCreated(
new ReadAnyOperation(this, cardDataClass), callbackId);
}
@Override
@UiThread
public void createReadCardDataOperation(AppCompatActivity activity,
Class<? extends CardData> cardDataClass, int callbackId) {
ensureOperationCreatedCallbackSupported(activity);
((OnOperationCreatedCallback) activity).onOperationCreated(new ReadMifareOperation(this),
callbackId);
}
@UiThread
public void start(TransferModel model) {
List<TransferModel> list = mPipe.mDownloadingQueue;
if (list.size() - 1 > 0) {
pause(list.get(list.size() - 1));
}
startImpl(model);
}
/**
* 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());
}
@UiThread public static void startBeatsAnimation(@NonNull View view) {
view.clearAnimation();
if (view.getAnimation() != null) {
view.getAnimation().cancel();
}
List<ObjectAnimator> animators = getBeats(view);
for (ObjectAnimator anim : animators) {
anim.setDuration(300).start();
anim.setInterpolator(interpolator);
}
}
/**
* Unregisters the given subscriber from all event classes.
*/
@UiThread
public synchronized void unregister(Callback subscriber) {
if (subscriber != null) {
mCallbacks.remove(subscriber);
}
}
@UiThread
@Override
public void onError(Throwable e) {
for (int i = 0; i < mCallbacks.size(); i++) {
Callback l = mCallbacks.get(i);
if (l != null) {
l.onError(e);
}
}
}
@SuppressWarnings("unused")
@UiThread
public static void release(Context context) {
if (context == null) {
return;
}
FrameCacheManager.getIns(context.getApplicationContext()).release();
}
@UiThread
public void stopDotAnimation() {
isAnimationStarted = false;
// There is a report saying NPE here. Not sure how is it possible.
try {
handler.removeCallbacks(dotAnimationRunnable);
} catch (Exception ex) {
Log.e(TAG, "stopDotAnimation: weird crash", ex);
}
}
@UiThread
@Override
public void onCancel() {
for (int i = 0; i < mCallbacks.size(); i++) {
Callback l = mCallbacks.get(i);
if (l != null) {
l.onCancel();
}
}
}
@UiThread
public void add(TransferModel item) {
for (int i = 0; i < mList.size(); i++) {
TransferModel transfer = mList.get(i);
if (transfer.type.equals(item.type)
&& TextUtils.equals(transfer.songId, item.songId)) {
return;
}
}
mDownloading.add(item);
mList.add(item);
notifyItemInserted(item);
}
@SuppressWarnings("unused")
@UiThread
public static void clear(View view) {
if (view == null) {
return;
}
view.setTag(getTag(), "");
}
/**
* 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());
}
@UiThread
protected PresentationComponent getPresentationComponent() {
if (mIsInjectorUsed) {
throw new RuntimeException("there is no need to use injector more than once");
}
mIsInjectorUsed = true;
return getApplicationComponent()
.newPresentationComponent(new PresentationModule(getActivity()));
}
@UiThread
private void appendStderr(final CharSequence str) {
mHandler.post(new Runnable() {
@Override
public void run() {
SpannableString spannableString = new SpannableString(str);
spannableString.setSpan(new ForegroundColorSpan(Color.RED), 0, str.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
append(spannableString);
}
});
}
@UiThread
@Override
public void destroy() {
if (isViewAttached()) {
detachView();
}
}