androidx.annotation.MainThread Java Examples

The following examples show how to use androidx.annotation.MainThread. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ContactUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@MainThread
public static void selectRecipientThroughDialog(@NonNull Context context, @NonNull List<Recipient> choices, @NonNull Locale locale, @NonNull RecipientSelectedCallback callback) {
  if (choices.size() > 1) {
    CharSequence[] values = new CharSequence[choices.size()];

    for (int i = 0; i < values.length; i++) {
      values[i] = getPrettyPhoneNumber(choices.get(i).requireE164(), locale);
    }

    new AlertDialog.Builder(context)
                   .setItems(values, ((dialog, which) -> callback.onSelected(choices.get(which))))
                   .create()
                   .show();
  } else {
    callback.onSelected(choices.get(0));
  }
}
 
Example #2
Source File: ApplicationContext.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@MainThread
public void onLock() {
  Log.i(TAG, "onLock()");

  stopService(new Intent(this, WebRtcCallService.class));

  finalizeRevealableMessageManager();
  finalizeExpiringMessageManager();
  finalizeMessageRetrieval();
  unregisterKeyEventReceiver();

  Util.runOnMainDelayed(() -> {
    ApplicationDependencies.getJobManager().shutdown(TimeUnit.SECONDS.toMillis(10));
    KeyCachingService.clearMasterSecret();
    WipeMemoryService.run(this, true);
  }, TimeUnit.SECONDS.toMillis(1));
}
 
Example #3
Source File: MediatorLiveData.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Starts to listen the given {@code source} LiveData, {@code onChanged} observer will be called
 * when {@code source} value was changed.
 * <p>
 * {@code onChanged} callback will be called only when this {@code MediatorLiveData} is active.
 * <p> If the given LiveData is already added as a source but with a different Observer,
 * {@link IllegalArgumentException} will be thrown.
 *
 * @param source    the {@code LiveData} to listen to
 * @param onChanged The observer that will receive the events
 * @param <S>       The type of data hold by {@code source} LiveData
 */
@MainThread
public <S> void addSource(@NonNull LiveData<S> source, @NonNull Observer<? super S> onChanged) {
    Source<S> e = new Source<>(source, onChanged);
    Source<?> existing = mSources.putIfAbsent(source, e);
    if (existing != null && existing.mObserver != onChanged) {
        throw new IllegalArgumentException(
                "This source was already added with the different observer");
    }
    if (existing != null) {
        return;
    }
    if (hasActiveObservers()) {
        e.plug();
    }
}
 
Example #4
Source File: HidDataSender.java    From wearmouse with Apache License 2.0 6 votes vote down vote up
@Override
@MainThread
public void onAppStatusChanged(boolean registered) {
    synchronized (lock) {
        if (isAppRegistered == registered) {
            // We are already in the correct state.
            return;
        }
        isAppRegistered = registered;

        for (ProfileListener listener : listeners) {
            listener.onAppStatusChanged(registered);
        }
        if (registered && waitingForDevice != null) {
            // Fulfill the postponed request to connect.
            requestConnect(waitingForDevice);
        }
    }
}
 
Example #5
Source File: HidDataSender.java    From wearmouse with Apache License 2.0 6 votes vote down vote up
@Override
@MainThread
public void onConnectionStateChanged(BluetoothDevice device, int state) {
    synchronized (lock) {
        if (state == BluetoothProfile.STATE_CONNECTED) {
            // A new connection was established. If we weren't expecting that, it
            // must be an incoming one. In that case, we shouldn't try to disconnect
            // from it.
            waitingForDevice = device;
        } else if (state == BluetoothProfile.STATE_DISCONNECTED) {
            // If we are disconnected from a device we are waiting to connect to, we
            // ran into a timeout and should no longer try to connect.
            if (device == waitingForDevice) {
                waitingForDevice = null;
            }
        }
        updateDeviceList();
        for (ProfileListener listener : listeners) {
            listener.onConnectionStateChanged(device, state);
        }
    }
}
 
Example #6
Source File: HidDataSender.java    From wearmouse with Apache License 2.0 6 votes vote down vote up
/**
 * Initiate connection sequence for the specified HID Host. If another device is already
 * connected, it will be disconnected first. If the parameter is {@code null}, then the service
 * will only disconnect from the current device.
 *
 * @param device New HID Host to connect to or {@code null} to disconnect.
 */
@MainThread
public void requestConnect(BluetoothDevice device) {
    synchronized (lock) {
        waitingForDevice = device;
        if (!isAppRegistered) {
            // Request will be fulfilled as soon the as app becomes registered.
            return;
        }

        connectedDevice = null;
        updateDeviceList();

        if (device != null && device.equals(connectedDevice)) {
            for (ProfileListener listener : listeners) {
                listener.onConnectionStateChanged(device, BluetoothProfile.STATE_CONNECTED);
            }
        }
    }
}
 
Example #7
Source File: HidDataSender.java    From wearmouse with Apache License 2.0 6 votes vote down vote up
/**
 * Ensure that the HID Device SDP record is registered and start listening for the profile proxy
 * and HID Host connection state changes.
 *
 * @param context Context that is required to listen for battery charge.
 * @param listener Callback that will receive the profile events.
 * @return Interface for managing the paired HID Host devices.
 */
@MainThread
public HidDeviceProfile register(Context context, ProfileListener listener) {
    synchronized (lock) {
        if (!listeners.add(listener)) {
            // This user is already registered
            return hidDeviceProfile;
        }
        if (listeners.size() > 1) {
            // There are already some users
            return hidDeviceProfile;
        }

        context = checkNotNull(context).getApplicationContext();
        hidDeviceProfile.registerServiceListener(context, profileListener);
        hidDeviceApp.registerDeviceListener(profileListener);
        context.registerReceiver(
                batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }
    return hidDeviceProfile;
}
 
Example #8
Source File: DynamicLanguageActivityHelper.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * If the activity isn't in the specified language, it will restart the activity.
 */
@MainThread
public static void recreateIfNotInCorrectLanguage(Activity activity, String language) {
  Locale currentActivityLocale = ConfigurationCompat.getLocales(activity.getResources().getConfiguration()).get(0);
  Locale selectedLocale        = LocaleParser.findBestMatchingLocaleForLanguage(language);

  if (currentActivityLocale.equals(selectedLocale)) {
    reentryProtection = "";
    return;
  }

  String reentryKey = activity.getClass().getName() + ":" + selectedLocale;
  if (!reentryKey.equals(reentryProtection)) {
    reentryProtection = reentryKey;
    Log.d(TAG, String.format("Activity Locale %s, Selected locale %s, restarting", currentActivityLocale, selectedLocale));
    activity.recreate();
  } else {
    Log.d(TAG, String.format("Skipping recreate as looks like looping, Activity Locale %s, Selected locale %s", currentActivityLocale, selectedLocale));
  }
}
 
Example #9
Source File: CachedInflater.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Identical to {@link LayoutInflater#inflate(int, ViewGroup, boolean)}, but will prioritize
 * pulling a cached view first.
 */
@MainThread
@SuppressWarnings("unchecked")
public <V extends View> V inflate(@LayoutRes int layoutRes, @Nullable ViewGroup parent, boolean attachToRoot) {
  View cached = ViewCache.getInstance().pull(layoutRes);
  if (cached != null) {
    if (parent != null && attachToRoot) {
      parent.addView(cached);
    }
    return (V) cached;
  } else {
    return (V) LayoutInflater.from(context).inflate(layoutRes, parent, attachToRoot);
  }
}
 
Example #10
Source File: MediatorLiveData.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Stops to listen the given {@code LiveData}.
 *
 * @param toRemote {@code LiveData} to stop to listen
 * @param <S>      the type of data hold by {@code source} LiveData
 */
@MainThread
public <S> void removeSource(@NonNull LiveData<S> toRemote) {
    Source<?> source = mSources.remove(toRemote);
    if (source != null) {
        source.unplug();
    }
}
 
Example #11
Source File: UploadProgressReporter.java    From flutter_uploader with MIT License 5 votes vote down vote up
@MainThread
public static UploadProgressReporter getInstance() {
  if (_instance == null) {
    _instance = new UploadProgressReporter();
  }
  return _instance;
}
 
Example #12
Source File: WorkflowModel.java    From mlkit-material-android with Apache License 2.0 5 votes vote down vote up
@MainThread
public void confirmingObject(DetectedObject object, float progress) {
  boolean isConfirmed = (Float.compare(progress, 1f) == 0);
  if (isConfirmed) {
    confirmedObject = object;
    if (PreferenceUtils.isAutoSearchEnabled(getContext())) {
      setWorkflowState(WorkflowState.SEARCHING);
      triggerSearch(object);
    } else {
      setWorkflowState(WorkflowState.CONFIRMED);
    }
  } else {
    setWorkflowState(WorkflowState.CONFIRMING);
  }
}
 
Example #13
Source File: ConversationAdapter.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Provided a pool, this will initialize it with view counts that make sense.
 */
@MainThread
static void initializePool(@NonNull RecyclerView.RecycledViewPool pool) {
  pool.setMaxRecycledViews(MESSAGE_TYPE_INCOMING_TEXT, 15);
  pool.setMaxRecycledViews(MESSAGE_TYPE_INCOMING_MULTIMEDIA, 15);
  pool.setMaxRecycledViews(MESSAGE_TYPE_OUTGOING_TEXT, 15);
  pool.setMaxRecycledViews(MESSAGE_TYPE_OUTGOING_MULTIMEDIA, 15);
  pool.setMaxRecycledViews(MESSAGE_TYPE_PLACEHOLDER, 15);
  pool.setMaxRecycledViews(MESSAGE_TYPE_HEADER, 1);
  pool.setMaxRecycledViews(MESSAGE_TYPE_FOOTER, 1);
  pool.setMaxRecycledViews(MESSAGE_TYPE_UPDATE, 5);
}
 
Example #14
Source File: HidDataSender.java    From wearmouse with Apache License 2.0 5 votes vote down vote up
@MainThread
private void onBatteryChanged(Intent intent) {
    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    if (level >= 0 && scale > 0) {
        float batteryLevel = (float) level / (float) scale;
        hidDeviceApp.sendBatteryLevel(batteryLevel);
    } else {
        Log.e(TAG, "Bad battery level data received: level=" + level + ", scale=" + scale);
    }
}
 
Example #15
Source File: ViewModelProviders.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity
 * is alive. More detailed explanation is in {@link ViewModel}.
 * <p>
 * It uses the given {@link Factory} to instantiate new ViewModels.
 *
 * @param activity an activity, in whose scope ViewModels should be retained
 * @param factory  a {@code Factory} to instantiate new ViewModels
 * @return a ViewModelProvider instance
 */
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity,
        @Nullable Factory factory) {
    Application application = checkApplication(activity);
    if (factory == null) {
        factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
    }
    return new ViewModelProvider(activity.getViewModelStore(), factory);
}
 
Example #16
Source File: VerificationCodeView.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@MainThread
public void append(int value) {
  if (index >= codes.size()) return;

  setInactive(containers);
  setActive(containers.get(index));

  TextView codeView = codes.get(index++);

  Animation translateIn = new TranslateAnimation(0, 0, codeView.getHeight(), 0);
  translateIn.setInterpolator(new OvershootInterpolator());
  translateIn.setDuration(500);

  Animation fadeIn = new AlphaAnimation(0, 1);
  fadeIn.setDuration(200);

  AnimationSet animationSet = new AnimationSet(false);
  animationSet.addAnimation(fadeIn);
  animationSet.addAnimation(translateIn);
  animationSet.reset();
  animationSet.setStartTime(0);

  codeView.setText(String.valueOf(value));
  codeView.clearAnimation();
  codeView.startAnimation(animationSet);

  if (index == codes.size() && listener != null) {
    listener.onCodeComplete(Stream.of(codes).map(TextView::getText).collect(Collectors.joining()));
  }
}
 
Example #17
Source File: InputPanel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
@MainThread
public void run() {
  long localStartTime = startTime;
  if (localStartTime > 0) {
    long elapsedTime = System.currentTimeMillis() - localStartTime;
    long elapsedSeconds = TimeUnit.MILLISECONDS.toSeconds(elapsedTime);
    if (elapsedSeconds >= limitSeconds) {
      onLimitHit.run();
    } else {
      recordTimeView.setText(DateUtils.formatElapsedTime(elapsedSeconds));
      Util.runOnMainDelayed(this, TimeUnit.SECONDS.toMillis(1));
    }
  }
}
 
Example #18
Source File: LiveData.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Removes all observers that are tied to the given {@link LifecycleOwner}.
 *
 * @param owner The {@code LifecycleOwner} scope for the observers to be removed.
 */
@SuppressWarnings("WeakerAccess")
@MainThread
public void removeObservers(@NonNull final LifecycleOwner owner) {
    assertMainThread("removeObservers");
    for (Map.Entry<Observer<? super T>, ObserverWrapper> entry : mObservers) {
        if (entry.getValue().isAttachedTo(owner)) {
            removeObserver(entry.getKey());
        }
    }
}
 
Example #19
Source File: InviteReminderModel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@MainThread
public void loadReminder(LiveRecipient liveRecipient, Runnable reminderCheckComplete) {
  SimpleTask.run(() -> createReminderInfo(liveRecipient.resolve()), result -> {
    reminderInfo.set(result);
    reminderCheckComplete.run();
  });
}
 
Example #20
Source File: HidDeviceProfile.java    From wearmouse with Apache License 2.0 5 votes vote down vote up
@Override
@MainThread
public void onServiceDisconnected(int profile) {
    service = null;
    if (serviceStateListener != null) {
        serviceStateListener.onServiceStateChanged(null);
    }
}
 
Example #21
Source File: LiveData.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the given observer from the observers list.
 *
 * @param observer The Observer to receive events.
 */
@MainThread
public void removeObserver(@NonNull final Observer<? super T> observer) {
    assertMainThread("removeObserver");
    ObserverWrapper removed = mObservers.remove(observer);
    if (removed == null) {
        return;
    }
    removed.detachObserver();
    removed.activeStateChanged(false);
}
 
Example #22
Source File: KeyboardInputController.java    From wearmouse with Apache License 2.0 5 votes vote down vote up
@Override
@MainThread
public void onAppStatusChanged(boolean registered) {
    if (!registered) {
        ui.onDeviceDisconnected();
    }
}
 
Example #23
Source File: InputPanel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@MainThread
public long hide() {
  long elapsedTime = System.currentTimeMillis() - startTime;
  this.startTime = 0;
  ViewUtil.fadeOut(this.recordTimeView, FADE_TIME, View.INVISIBLE);
  microphone.clearAnimation();
  ViewUtil.fadeOut(this.microphone, FADE_TIME, View.INVISIBLE);
  return elapsedTime;
}
 
Example #24
Source File: TouchpadController.java    From wearmouse with Apache License 2.0 5 votes vote down vote up
@Override
@MainThread
public void onAppStatusChanged(boolean registered) {
    if (!registered) {
        ui.onDeviceDisconnected();
    }
}
 
Example #25
Source File: WorkflowModel.java    From mlkit-material-android with Apache License 2.0 5 votes vote down vote up
@MainThread
public void setWorkflowState(WorkflowState workflowState) {
  if (!workflowState.equals(WorkflowState.CONFIRMED)
      && !workflowState.equals(WorkflowState.SEARCHING)
      && !workflowState.equals(WorkflowState.SEARCHED)) {
    confirmedObject = null;
  }
  this.workflowState.setValue(workflowState);
}
 
Example #26
Source File: ComputableLiveData.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@MainThread
@Override
public void run() {
    boolean isActive = mLiveData.hasActiveObservers();
    if (mInvalid.compareAndSet(false, true)) {
        if (isActive) {
            mExecutor.execute(mRefreshRunnable);
        }
    }
}
 
Example #27
Source File: MouseController.java    From wearmouse with Apache License 2.0 5 votes vote down vote up
@Override
@MainThread
public void onAppStatusChanged(boolean registered) {
    if (!registered) {
        ui.onDeviceDisconnected();
    }
}
 
Example #28
Source File: KeypadController.java    From wearmouse with Apache License 2.0 5 votes vote down vote up
@Override
@MainThread
public void onAppStatusChanged(boolean registered) {
    if (!registered) {
        ui.onDeviceDisconnected();
    }
}
 
Example #29
Source File: MeteredConnectivityObserver.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@MainThread
MeteredConnectivityObserver(@NonNull Context context, @NonNull LifecycleOwner lifecycleOwner) {
  this.context             = context;
  this.connectivityManager = ServiceUtil.getConnectivityManager(context);
  this.metered             = new MutableLiveData<>();

  this.metered.setValue(ConnectivityManagerCompat.isActiveNetworkMetered(connectivityManager));
  lifecycleOwner.getLifecycle().addObserver(this);
}
 
Example #30
Source File: StaticObjectDetectionActivity.java    From mlkit-material-android with Apache License 2.0 5 votes vote down vote up
@MainThread
private void onObjectsDetected(FirebaseVisionImage image, List<FirebaseVisionObject> objects) {
  detectedObjectNum = objects.size();
  Log.d(TAG, "Detected objects num: " + detectedObjectNum);
  if (detectedObjectNum == 0) {
    loadingView.setVisibility(View.GONE);
    showBottomPromptChip(getString(R.string.static_image_prompt_detected_no_results));
  } else {
    searchedObjectMap.clear();
    for (int i = 0; i < objects.size(); i++) {
      searchEngine.search(new DetectedObject(objects.get(i), i, image), /* listener= */ this);
    }
  }
}