类androidx.annotation.NonNull源码实例Demo

下面列出了怎么用androidx.annotation.NonNull的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: arcusandroid   文件: ButtonActionController.java
/**
 * Assigns the selected action to the current button (i.e., the button provided to
 * {@link #editButton(Button)}).
 * <p>
 * Must call {@link #editButton(Button)} before invoking this method.
 * <p>
 * If the action previously assigned to this button was not the default action, then the rule
 * associated with that action will be deleted before assigning the new, selected action.
 *
 * @param selectedAction
 */
public void assignButtonAction(@NonNull final ButtonAction selectedAction) {
    logger.debug("Assigning action {} to button {} of device {}.", selectedAction, selectedButton, selectedButtonDevice);

    if (state < STATE_EDITING_BUTTON) {
        throw new IllegalStateException("Please call editButton() before assignButtonAction().");
    }
    state = STATE_ASSIGNED_RULE;

    // If the last assigned value wasn't the default action, then delete it
    if (!currentAction.isDefaultAction()) {
        deleteButtonAction(currentAction, new ButtonActionDeletionListener() {
            @Override
            public void onButtonActionDeleted() {
                completeButtonActionAssignment(selectedAction);
            }
        });
    }

    else {
        completeButtonActionAssignment(selectedAction);
    }
}
 
源代码2 项目: mollyim-android   文件: MediaSendViewModel.java
void onSingleMediaSelected(@NonNull Context context, @NonNull Media media) {
  selectedMedia.setValue(Collections.singletonList(media));

  repository.getPopulatedMedia(context, Collections.singletonList(media), populatedMedia -> {
    Util.runOnMain(() -> {
      List<Media> filteredMedia = getFilteredMedia(context, populatedMedia, mediaConstraints);

      if (filteredMedia.isEmpty()) {
        error.setValue(Error.ITEM_TOO_LARGE);
        bucketId.setValue(Media.ALL_MEDIA_BUCKET_ID);
      } else {
        bucketId.setValue(filteredMedia.get(0).getBucketId().or(Media.ALL_MEDIA_BUCKET_ID));
      }

      selectedMedia.setValue(filteredMedia);
    });
  });
}
 
源代码3 项目: mollyim-android   文件: GroupRightsDialog.java
public GroupRightsDialog(@NonNull Context context,
                         @NonNull Type type,
                         @NonNull GroupAccessControl currentRights,
                         @NonNull GroupRightsDialog.OnChange onChange)
{
  rights = currentRights;

  builder = new AlertDialog.Builder(context)
                           .setTitle(type.message)
                           .setSingleChoiceItems(type.choices, currentRights.ordinal(), (dialog, which) -> rights = GroupAccessControl.values()[which])
                           .setNegativeButton(android.R.string.cancel, (dialog, which) -> {
                           })
                           .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                             GroupAccessControl newGroupAccessControl = rights;

                             if (newGroupAccessControl != currentRights) {
                               onChange.changed(currentRights, newGroupAccessControl);
                             }
                           });
}
 
源代码4 项目: crashx   文件: CrashActivity.java
@Nullable
private static Class<? extends Activity> getErrorActivityClassWithIntentFilter(@NonNull Context context) {
    Intent searchedIntent = new Intent().setAction(INTENT_ACTION_ERROR_ACTIVITY).setPackage(context.getPackageName());
    List<ResolveInfo> resolveInfos = context.getPackageManager().queryIntentActivities(searchedIntent,
            PackageManager.GET_RESOLVED_FILTER);

    if (resolveInfos != null && resolveInfos.size() > 0) {
        ResolveInfo resolveInfo = resolveInfos.get(0);
        try {
            return (Class<? extends Activity>) Class.forName(resolveInfo.activityInfo.name);
        } catch (ClassNotFoundException e) {
            Log.e(TAG, "Failed when resolving the error activity class via intent filter, stack trace follows!", e);
        }
    }

    return null;
}
 
源代码5 项目: mollyim-android   文件: RestoreBackupFragment.java
static void searchForBackup(@NonNull OnBackupSearchResultListener listener) {
  new AsyncTask<Void, Void, BackupUtil.BackupInfo>() {
    @Override
    protected @Nullable
    BackupUtil.BackupInfo doInBackground(Void... voids) {
      try {
        return BackupUtil.getLatestBackup();
      } catch (NoExternalStorageException e) {
        Log.w(TAG, e);
        return null;
      }
    }

    @Override
    protected void onPostExecute(@Nullable BackupUtil.BackupInfo backup) {
      listener.run(backup);
    }
  }.execute();
}
 
源代码6 项目: busybee   文件: RealBusyBee.java
@Override
public void completedEverythingInCategory(@NonNull final Category category) {
    completedOnThread.execute(new Runnable() {
        @Override
        public void run() {
            lock.lock();
            try {
                for (Iterator<Object> iterator = operationsInProgress.valuesIterator(category); iterator.hasNext(); ) {
                    Object next = iterator.next();
                    completeOnCurrentThread(next, iterator);
                }
            } finally {
                lock.unlock();
            }
        }

        @Override
        public String toString() {
            return "completedEverythingInCategory(" + category.toString() + ")";
        }
    });
}
 
源代码7 项目: mollyim-android   文件: AvatarHelper.java
/**
 * Returns a {@link StreamDetails} for the local user's own avatar, or null if one does not exist.
 */
public static @Nullable StreamDetails getSelfProfileAvatarStream(@NonNull Context context) {
  RecipientId selfId = Recipient.self().getId();

  if (!hasAvatar(context, selfId)) {
    return null;
  }

  try {
    InputStream stream = getAvatar(context, selfId);
    return new StreamDetails(stream, MediaUtil.IMAGE_JPEG, getAvatarLength(context, selfId));
  } catch (IOException e) {
    Log.w(TAG,  "Failed to read own avatar!", e);
    return null;
  }
}
 
源代码8 项目: mollyim-android   文件: FuzzyPhoneNumberHelper.java
/**
 * This should be run on the list of numbers we find out are registered with the server. Based on
 * these results and our initial input set, we can decide if we need to rewrite which number we
 * have stored locally.
 */
static @NonNull OutputResult generateOutput(@NonNull Collection<String> registeredNumbers, @NonNull InputResult inputResult) {
  Set<String>         allNumbers = new HashSet<>(registeredNumbers);
  Map<String, String> rewrites   = new HashMap<>();

  for (Map.Entry<String, String> entry : inputResult.getFuzzies().entrySet()) {
    if (registeredNumbers.contains(entry.getKey()) && registeredNumbers.contains(entry.getValue())) {
      if (mxHas1(entry.getKey())) {
        rewrites.put(entry.getKey(), entry.getValue());
        allNumbers.remove(entry.getKey());
      } else {
        allNumbers.remove(entry.getValue());
      }
    } else if (registeredNumbers.contains(entry.getValue())) {
      rewrites.put(entry.getKey(), entry.getValue());
      allNumbers.remove(entry.getKey());
    }
  }

  return new OutputResult(allNumbers, rewrites);
}
 
源代码9 项目: mollyim-android   文件: Job.java
private Parameters(@NonNull String id,
                   long createTime,
                   long lifespan,
                   int maxAttempts,
                   long maxBackoff,
                   int maxInstances,
                   @Nullable String queue,
                   @NonNull List<String> constraintKeys,
                   @Nullable Data inputData)
{
  this.id             = id;
  this.createTime     = createTime;
  this.lifespan       = lifespan;
  this.maxAttempts    = maxAttempts;
  this.maxBackoff     = maxBackoff;
  this.maxInstances   = maxInstances;
  this.queue          = queue;
  this.constraintKeys = constraintKeys;
  this.inputData      = inputData;
}
 
源代码10 项目: mollyim-android   文件: MessageUtil.java
/**
 * @return If the message is longer than the allowed text size, this will return trimmed text with
 *         an accompanying TextSlide. Otherwise it'll just return the original text.
 */
public static SplitResult getSplitMessage(@NonNull Context context, @NonNull String rawText, int maxPrimaryMessageSize) {
  String              bodyText  = rawText;
  Optional<TextSlide> textSlide = Optional.absent();

  if (bodyText.length() > maxPrimaryMessageSize) {
    bodyText = rawText.substring(0, maxPrimaryMessageSize);

    byte[] textData  = rawText.getBytes();
    String timestamp = new SimpleDateFormat("yyyy-MM-dd-HHmmss", Locale.US).format(new Date());
    String filename  = String.format("signal-%s.txt", timestamp);
    Uri    textUri   = BlobProvider.getInstance()
                                   .forData(textData)
                                   .withMimeType(MediaUtil.LONG_TEXT)
                                   .withFileName(filename)
                                   .createForSingleSessionInMemory();

    textSlide = Optional.of(new TextSlide(context, textUri, filename, textData.length));
  }

  return new SplitResult(bodyText, textSlide);
}
 
源代码11 项目: arcusandroid   文件: CareStatusController.java
protected AlertTrigger getBehaviorTrigger(
      @NonNull String causedByTrigger,
      String currentTrigger,
      Date time
) {
    Map<String, Object> behavior = CareBehaviorsProvider.instance().getById(currentTrigger);
    if (behavior == null) {
        return getOtherTriggerCause(causedByTrigger, currentTrigger, time);
    }

    AlertTrigger trigger = new AlertTrigger();
    trigger.setTriggerTitle(causedByTrigger.equals(currentTrigger) ? ALARM_TRIGGERED : BEHAVIOR_TRIGGERED);
    trigger.setTriggerType(AlertTrigger.TriggerType.BEHAVIOR);
    trigger.setTriggerDescription(String.format(BY_BEH_FMT, CareBehaviorModel.fromMap(behavior, "").getName()));
    trigger.setTriggerID(currentTrigger);
    trigger.setTriggerTime(time);
    return trigger;
}
 
源代码12 项目: ShizuruNotes   文件: BackgroundSpan.java
@Override
public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {

    //先填充文字
    paint.setStyle(Paint.Style.FILL);
    canvas.drawText(text, start, end, x, y, paint);

    //设置边框粗细
    paint.setStrokeWidth(3.0f);
    //设置绘制矩形范围
    RectF rectF = new RectF(x, top + 5, x + measureText(paint, text, start, end), bottom - 5);

    switch (type){
        case BORDER_RECT:
            drawBorderRect(canvas, paint, rectF);
            break;
    }
}
 
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    isEditMode = !isEditMode;

    if (isEditMode) {
        item.setTitle(getString(R.string.card_menu_done));
    } else {
        item.setTitle(getString(R.string.card_menu_edit));
    }

    if (editModeChangeListener != null) {
        editModeChangeListener.onEditModeChanged(isEditMode);
    }

    return true;
}
 
源代码14 项目: arcusandroid   文件: CareTopCardBehaviorView.java
@Override
public void build(@NonNull CareStatusCard card) {
    super.build(card);

    mDashedCircleView = (DashedCircleView) findViewById(R.id.dashed_circle);

    mCenterTopTextView = (Version1TextView) findViewById(R.id.center_top_text);
    mCenterBottomTextView = (Version1TextView) findViewById(R.id.center_bottom_text);

    mTopIconView = (ImageView) findViewById(R.id.top_icon);
    mTopLineView = findViewById(R.id.top_line);
    mLeftAlarmIcon = (ImageView) findViewById(R.id.left_alarm_icon);
    mCenterAlarmText = (Version1TextView) findViewById(R.id.center_alarm_text);
    mRightAlarmIcon = (ImageView) findViewById(R.id.right_alarm_icon);

    CardView cardView = (CardView) findViewById(R.id.cardView);
    if (cardView != null) {
        cardView.setCardBackgroundColor(Color.TRANSPARENT);
    }

    if (card.isDividerShown()) {
        showDivider();
    }

    // Configure the card view based on the alarmstate
    handleAlarmState(card);
}
 
源代码15 项目: ShadowsocksRR   文件: TrafficMonitorThread.java
public TrafficMonitorThread(Context context) {
    PATH = context.getApplicationInfo().dataDir + File.separator + "stat_path";
    pool = new ScheduledThreadPoolExecutor(3, new ThreadFactory() {
        @Override
        public Thread newThread(@NonNull Runnable r) {
            Thread thread = new Thread(r);
            thread.setName(TAG);
            return thread;
        }
    });
}
 
源代码16 项目: MHViewer   文件: RecaptchaView.java
@Override
public void onSuccess(@NonNull String challenge, @NonNull String image) {
  this.loading = false;
  this.challenge = challenge;
  this.image = image;

  load(image, image);
}
 
源代码17 项目: mollyim-android   文件: JobInstantiator.java
public @NonNull Job instantiate(@NonNull String jobFactoryKey, @NonNull Job.Parameters parameters, @NonNull Data data) {
  if (jobFactories.containsKey(jobFactoryKey)) {
    return jobFactories.get(jobFactoryKey).create(parameters, data);
  } else {
    throw new IllegalStateException("Tried to instantiate a job with key '" + jobFactoryKey + "', but no matching factory was found.");
  }
}
 
源代码18 项目: bitgatt   文件: AlwaysConnectedScanner.java
/**
 * Will add a list of filters to the existing set of filters, will not check for duplicates
 * and will not clear the existing filter set.  This method will only change the current set of
 * filters once every 30s so if you call this method multiple times, the changes will be spread
 * over 30s x n calls.
 *
 * @param context The android context
 * @param filters The list of filters
 */
public synchronized void addScanFilters(@NonNull Context context, @NonNull List<ScanFilter> filters) {
    scanFilters.addAll(filters);
    if (FitbitGatt.getInstance().getPeripheralScanner() != null) {
        FitbitGatt.getInstance().getPeripheralScanner().setScanFilters(scanFilters);
    }
    // let's only change this once per scan too much warn interval
    mainHandlerForScheduling.postDelayed(() -> {
        FitbitGatt.getInstance().getPeripheralScanner().cancelPendingIntentBasedBackgroundScan();
        FitbitGatt.getInstance().getPeripheralScanner().startPendingIntentBasedBackgroundScan(scanFilters, context);
    }, PeripheralScanner.SCAN_TOO_MUCH_WARN_INTERVAL);
}
 
源代码19 项目: mollyim-android   文件: ProfileUtil.java
private static Optional<UnidentifiedAccess> getUnidentifiedAccess(@NonNull Context context, @NonNull Recipient recipient) {
  Optional<UnidentifiedAccessPair> unidentifiedAccess = UnidentifiedAccessUtil.getAccessFor(context, recipient);

  if (unidentifiedAccess.isPresent()) {
    return unidentifiedAccess.get().getTargetUnidentifiedAccess();
  }

  return Optional.absent();
}
 
源代码20 项目: arcusandroid   文件: ArcusProductFragment.java
public final void updateTemperatureTextView(@NonNull TextView view, Object doubleNumber) {
    try {
        Double number = Double.valueOf(String.valueOf(doubleNumber));
        if (temperatureDisplayType.equals(TemperatureDisplayType.FAHRENHEIT)) {
            updateTextView(view, decimalFormat.format(TemperatureUtils.celsiusToFahrenheit(number)) + (char) 0x00B0);
        }
        else {
            updateTextView(view, decimalFormat.format(number) + (char) 0x00B0);
        }
    }
    catch (Exception ex) {
        logger.error("Could not updateTemperatureTextView, Ex: [{}], Value: [{}]", getSimpleName(ex), doubleNumber);
    }
}
 
private StickerKeyboardPageViewModel(@NonNull Application application, @NonNull StickerKeyboardRepository repository) {
  this.application       = application;
  this.repository        = repository;
  this.stickers          = new MutableLiveData<>();
  this.observerThrottler = new Throttler(500);
  this.observer          = new ContentObserver(new Handler()) {
    @Override
    public void onChange(boolean selfChange) {
      observerThrottler.publish(() -> getStickers(packId));
    }
  };

  application.getContentResolver().registerContentObserver(DatabaseContentProviders.Sticker.CONTENT_URI, true, observer);
}
 
public synchronized void addController(@NonNull RequestController controller) {
  if (canceled) {
    controller.cancel();
  } else {
    controllers.add(controller);
  }
}
 
public static @Nullable Long getFileSize(@NonNull Context context, Uri persistentBlobUri) {
  if (!isAuthority(context, persistentBlobUri))      return null;
  if (isExternalBlobUri(context, persistentBlobUri)) return null;
  if (MATCHER.match(persistentBlobUri) == MATCH_OLD) return null;

  try {
    return Long.valueOf(persistentBlobUri.getPathSegments().get(FILESIZE_PATH_SEGMENT));
  } catch (NumberFormatException e) {
    Log.w(TAG, e);
    return null;
  }
}
 
源代码24 项目: EasyPhotos   文件: UCropFragment.java
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.ucrop_fragment_photobox, container, false);

    Bundle args = getArguments();

    setupViews(rootView, args);
    setImageData(args);
    setInitialState();
    addBlockingView(rootView);

    return rootView;
}
 
源代码25 项目: mollyim-android   文件: StorageSyncHelper.java
private static @NonNull <E extends SignalRecord> RecordMergeResult<E> resolveRecordConflict(@NonNull Collection<E> remoteOnlyRecords,
                                                                                            @NonNull Collection<E> localOnlyRecords,
                                                                                            @NonNull ConflictMerger<E> merger)
{
  Set<E>               localInserts  = new HashSet<>(remoteOnlyRecords);
  Set<E>               remoteInserts = new HashSet<>(localOnlyRecords);
  Set<RecordUpdate<E>> localUpdates  = new HashSet<>();
  Set<RecordUpdate<E>> remoteUpdates = new HashSet<>();
  Set<E>               remoteDeletes = new HashSet<>(merger.getInvalidEntries(remoteOnlyRecords));

  remoteOnlyRecords.removeAll(remoteDeletes);
  localInserts.removeAll(remoteDeletes);

  for (E remote : remoteOnlyRecords) {
    Optional<E> local = merger.getMatching(remote);

    if (local.isPresent()) {
      E merged = merger.merge(remote, local.get(), keyGenerator);

      if (!merged.equals(remote)) {
        remoteUpdates.add(new RecordUpdate<>(remote, merged));
      }

      if (!merged.equals(local.get())) {
        localUpdates.add(new RecordUpdate<>(local.get(), merged));
      }

      localInserts.remove(remote);
      remoteInserts.remove(local.get());
    }
  }

  return new RecordMergeResult<>(localInserts, localUpdates, remoteInserts, remoteUpdates, remoteDeletes);
}
 
源代码26 项目: mollyim-android   文件: CameraContactsRepository.java
@WorkerThread
private @NonNull List<Recipient> getContacts(@NonNull String query) {
  List<Recipient> recipients = new ArrayList<>();

  try (Cursor cursor = contactRepository.querySignalContacts(query)) {
    while (cursor.moveToNext()) {
      RecipientId id        = RecipientId.from(cursor.getLong(cursor.getColumnIndexOrThrow(ContactRepository.ID_COLUMN)));
      Recipient   recipient = Recipient.resolved(id);
      recipients.add(recipient);
    }
  }

  return recipients;
}
 
源代码27 项目: arcusandroid   文件: LightAndSwitchController.java
protected @NonNull Collection<String> getCaps() {
    DeviceModel model = getDevice();
    if (model == null || model.getCaps() == null) {
        return Collections.emptySet();
    }

    return model.getCaps();
}
 
@Override
public @Nullable View onCreateView(@NonNull LayoutInflater inflater,
                                   @Nullable ViewGroup container,
                                   @Nullable Bundle savedInstanceState)
{
  return inflater.inflate(R.layout.react_with_any_emoji_bottom_sheet_dialog_fragment, container, false);
}
 
源代码29 项目: arcusandroid   文件: LightSwitchFragment.java
@Override
public void showBanner(@NonNull Banner banner) {
    Activity activity = getActivity();
    if (activity != null) {
        presenter.showBannerHelper(activity, banner);
    }
}
 
源代码30 项目: mollyim-android   文件: AttachmentUtil.java
@WorkerThread
private static boolean isFromUnknownContact(@NonNull Context context, @NonNull DatabaseAttachment attachment) {
  try (Cursor messageCursor = DatabaseFactory.getMmsDatabase(context).getMessage(attachment.getMmsId())) {
    final MessageRecord message = DatabaseFactory.getMmsDatabase(context).readerFor(messageCursor).getNext();

    if (message == null || (!message.getRecipient().isSystemContact()  &&
                            !message.getRecipient().isProfileSharing() &&
                            !message.isOutgoing()                      &&
                            !message.getRecipient().isLocalNumber())) {
      return true;
    }
  }

  return false;
}