Java 类org.greenrobot.eventbus.EventBus 实例源码

项目:streaminglib    文件:RtspServer.java   
/**
 * Listen for client connections
 *
 * @throws IOException server socket cannot be created on port
 */
private void listen() throws IOException {
    try {
        Log.d(TAG, "listen: Create server socket");
        ServerSocket rtspServerSocket = new ServerSocket();
        rtspServerSocket.setReuseAddress(true);
        rtspServerSocket.bind(new InetSocketAddress(port));

        while (!Thread.interrupted()) {
            Log.d(TAG, "listening");

            // Blocking
            EventBus.getDefault().post(new RtspServerEvent.Connection(this, rtspServerSocket.accept()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:DOUSalaries    文件:MainActivity.java   
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onEvent(SyncEvent event) {
    switch (event.getCode()) {
        case SyncEvent.START_SYNC:
            showLoading();
            break;
        case SyncEvent.END_SYNC:
            hideLoading();
            EventBus.getDefault().post(new SyncEvent(SyncEvent.UPDATE_SYNC, ""));
            EventBus.getDefault().removeStickyEvent(event);
            break;
    }
    if(!event.getStatus().isEmpty()){
        Toast.makeText(this, event.getStatus(), Toast.LENGTH_SHORT).show();
    }
}
项目:ActivityMonitor    文件:RecorderService.java   
@Override
protected void onHandleIntent(@Nullable Intent intent) {
    isRunning = true;
    showForegroundNotification();
    name = intent.getStringExtra(EXTRA_ACTIVITY_TYPE);
    storage = new StorageUtil(name);
    startAccelerometer();
    try {
        Thread.sleep(Config.LENGTH_RECORDING_IN_MINUTES * 60 * 1000);
    } catch (InterruptedException e) {
    }
    stopAccelerometer();
    storage.close();
    RecorderFinishedEvent event = new RecorderFinishedEvent();
    event.activityType = name;
    EventBus.getDefault().post(event);
    isRunning = false;
    hideForegroundNotification();
    ToneGenerator beep = new ToneGenerator(AudioManager.STREAM_MUSIC, 500);
    beep.startTone(ToneGenerator.TONE_CDMA_HIGH_L, 1000);
}
项目:SofaTime    文件:MainActivity.java   
@Override
public void onProgressChanged(final SeekBar seekBar,
                              final int progress,
                              final boolean fromUser) {
    if (!fromUser) {
        // Ignore all changes if they are not from user
        return;
    }

    // Ignore the next status update to avoid the seek bar to
    // be updated from a response sent before this request
    skipNextStatus = true;

    // Send request
    EventBus.getDefault().post(new RequestEvent(Cmd.VOLUME,
            String.valueOf(progress), true));
}
项目:QiangHongBao    文件:QHBService.java   
@Override
public void onDestroy() {
    isRun = false;
    EventBus.getDefault().post(new MessageEvent(MessageEvent.QHB_SERVICE_STATE, false));
    EventBus.getDefault().unregister(this);
    mQHBNotificationManager.stopNotification();
    unregisterReceiver(mBroadcastReceiver);
    super.onDestroy();
    LogUtils.printOut(TAG, "QHBService onDestroy");
    if(mPkgAccessibilityJobMap != null) {
        mPkgAccessibilityJobMap.clear();
    }
    if(mAccessibilityJobs != null && !mAccessibilityJobs.isEmpty()) {
        for (IAccessibilityJob job : mAccessibilityJobs) {
            job.onDestroy();
        }
        mAccessibilityJobs.clear();
    }

    mAccessibilityJobs = null;
    mPkgAccessibilityJobMap = null;
}
项目:AndroidThings-BurglarAlarm    文件:GpioHandler.java   
private GpioHandler() {
    EventBus.getDefault().register(this);
    mContext = ContextHolder.getAppContext();
    manager = new PeripheralManagerService();
    try {
        mAlarmGpio = manager.openGpio(GPIO_ALARM_TRIGGER);
        mAlarmGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);

        mMotion = new Button(GPIO_ALARM_MOTION,
                Button.LogicState.PRESSED_WHEN_HIGH
        );

        mMotion.setOnButtonEventListener(this);
    } catch (IOException e) {
        Log.e(BurglarAlarmConstants.LOG_TAG, "IOException :" + e);
    }

}
项目:A.scribe    文件:TimePickerDialogFragment.java   
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    DateTime currentDateTime = new DateTime();
    int currentHour = currentDateTime.getHourOfDay();
    int currentMinute = currentDateTime.getMinuteOfHour();
    final Bundle args = getArguments();

    MinTimePickerDialog timePickerDialog = new MinTimePickerDialog(getActivity(), R.style.MyPicker,
            (view, hourOfDay, minute) -> {
                DateTime dateTime = new DateTime(
                        args.getInt(ARGUMENT_PICKED_YEAR),
                        args.getInt(ARGUMENT_PICKED_MONTH) + 1,
                        args.getInt(ARGUMENT_PICKED_DAY), hourOfDay, minute);
                EventBus.getDefault().post(new ReminderSetEvent(dateTime.getMillis()));
            }, currentHour, currentMinute, DateFormat.is24HourFormat(getActivity()));
    if (args.getBoolean(ARGUMENT_IS_TODAY)) {
        timePickerDialog.setMin(currentHour, currentMinute);
    }

    return timePickerDialog;
}
项目:grblcontroller    文件:FileStreamerIntentService.java   
private void streamLine(GcodeCommand gcodeCommand){

        String command = gcodeCommand.getCommandString();
        int commandSize = command.length() + 1;
        if(commandSize <= 1) return;

        // Wait until there is room, if necessary.
        while (MAX_RX_SERIAL_BUFFER < (CURRENT_RX_SERIAL_BUFFER + command.length() + 1)) {
            try {
                completedCommands.take();
                if(activeCommandSizes.size() > 0) CURRENT_RX_SERIAL_BUFFER -= activeCommandSizes.removeFirst();
            } catch (InterruptedException e) {
                Log.e(TAG, e.getMessage(), e);
                return;
            }

            if(!shouldContinue) return;
        }

        if(shouldContinue){
            activeCommandSizes.offer(commandSize);
            CURRENT_RX_SERIAL_BUFFER += commandSize;
            EventBus.getDefault().post(gcodeCommand);
        }

    }
项目:Android-Code-Demos    文件:MainActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // If you want to handle sticky message, please comment out the following code
    EventBus.getDefault().register(this);
}
项目:Android-Code-Demos    文件:MainActivity.java   
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.intent_to_second_button:
            startActivity(new Intent(MainActivity.this, SecondActivity.class));
            break;
        case R.id.handle_sticky_button:
            EventBus.getDefault().register(this);
            break;
    }
    startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
项目:localcloud_fe    文件:UpdatesInstaller.java   
private static void execute(final WorkerTask task) {
    isInstalling = true;
    new Thread(new Runnable() {
        @Override
        public void run() {
            task.run();
            isInstalling = false;

            // dispatch resulting event
            EventBus.getDefault().post(task.result());
        }
    }).start();
}
项目:Transmission    文件:OnlineRecyclerAdapter.java   
public void setDataList(final List<OnlineModel> modelss, final int position) {


        Observable.just(models)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<OnlineModel>>() {
                    @Override
                    public void call(List<OnlineModel> onlineModels) {
                        synchronized (models) {
                            if (models.size() == modelss.size()) {
                                models.clear();
                                models.addAll(modelss);
                                notifyItemChanged(position);
                            } else if (models.size() < modelss.size()) {
                                models.clear();
                                models.addAll(modelss);
                                notifyItemInserted(0);
                            } else if (models.size() > modelss.size()) { //删除
                                notifyItemRemoved(position);
                                models.clear();
                                models.addAll(modelss);
                            }
                            EventBus.getDefault().post(new OnlineEvent(1, models.size(), 0));
                        }
                    }
                });

    }
项目:https-github.com-hyb1996-NoRootScriptDroid    文件:SublimePluginClient.java   
public void close() throws IOException {
    if (mSocket != null) {
        mSocket.close();
        mExecutor.shutdownNow();
        mSocket = null;
        mOutputStream = null;
        mExecutor = null;
        EventBus.getDefault().post(new ConnectionStateChangeEvent(false));
    }
}
项目:lrs_android    文件:GameActivity.java   
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    EventBus.getDefault().register(this);
    init();
    initUIandEvent();
}
项目:netty-dovakin-android-client    文件:NGLSClientHandler.java   
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    super.channelInactive(ctx);
    try {
        EventBus.getDefault().post(new ChannelEvent(EventType.ON_INACTIVE, null));
    }catch (Exception e){
        e.printStackTrace();
    }
}
项目:atlant-android    文件:TransactionRestHandler.java   
@Override
public void onResponse(Response<SendTransactions> response) {
  //ok
  if (response.body().getResult() != null) {
    EventBus.getDefault().post(new OnStatusSuccess(BaseActivity.REQUEST_CODE_SEND));
  } else {
    //fail
    if (response.body().getError() != null) {
      EventBus.getDefault()
          .post(new OnStatusError(BaseActivity.REQUEST_CODE_SEND, response.body().getError().getMessage()));
    } else {
      EventBus.getDefault().post(new OnStatusError(BaseActivity.REQUEST_CODE_SEND));
    }
  }
}
项目:EazyBaseMVP    文件:BasePresenter.java   
@Override
public void onDestroy() {
    if (useEventBus()) {
        EventBus.getDefault().unregister(this);
    }
    unDispose();
    if (mModel != null) {
        mModel.onDestroy();
    }
    this.mModel = null;
    this.mView = null;
    this.mCompositeDisposable = null;
}
项目:Auto.js    文件:MainActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    checkPermissions();
    mVersionGuard = new VersionGuard(this);
    showAnnunciationIfNeeded();
    EventBus.getDefault().register(this);
}
项目:Cable-Android    文件:WebRtcCallActivity.java   
private void handleTerminate(@NonNull Recipient recipient /*, int terminationType */) {
  Log.w(TAG, "handleTerminate called");

  callScreen.setActiveCall(recipient, getString(R.string.RedPhone_ending_call));
  EventBus.getDefault().removeStickyEvent(WebRtcViewModel.class);

  delayedFinish();
}
项目:AssistantBySDK    文件:VoiceWaveComponent.java   
public void onRecord() {
    if (rLock.tryLock()) {
        try {
            EventBus.getDefault().post(new IntroduceShowEvent(false));
            if (recording) {
                stopRecord();
            } else {
                stopWakeup();
                prepareToRecord();
            }
        } finally {
            rLock.unlock();
        }
    }
}
项目:Android-Scrapper    文件:DashAdapter.java   
public void addGame(Game game) {
    if (!data.contains(game)) {
        data.add(game);
        Collections.sort(data, comparator);
        setGroupStatus();
        EventBus.getDefault().post(new DashCountEvent(data.size(), dateLag));
    }
    if (data.size() > 0) {
        dashPresenter.isEmpty(false);  // Broadcast that dataset is not empty.
    }
    this.notifyDataSetChanged();
}
项目:phonk    文件:IDEcommunication.java   
public IDEcommunication(Context appActivity) {
    this.a = new WeakReference<>(appActivity);

    /*
    try {
        ws = PhonkWebsocketServer.getInstance(a.get());
        MLog.d(TAG, "websocket started");
    } catch (UnknownHostException e) {
        e.printStackTrace();
        MLog.d(TAG, "websocket :(");
    }
    */

    ws.addListener("phonkApp", new PhonkWebsocketServer.WebSocketListener() {
        @Override
        public void onUpdated(JSONObject jsonObject) {
            try {
                String type = jsonObject.getString("type");

                if (type.equals("project_highlight")) {
                    String folder = jsonObject.getString("folder");
                    String name = jsonObject.getString("name");

                    Events.SelectedProjectEvent evt = new Events.SelectedProjectEvent(folder, name);
                    EventBus.getDefault().post(evt);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

}
项目:AndroidThings-BurglarAlarm    文件:BurglarService.java   
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onLoginFailure(LoginFailedEvent event) {
    int tryCount = checker.getAndAdd(1);
    Log.w(TAG, "Could not login, try again #" + tryCount);
    if (tryCount < 3) {
        getDevice();
    } else {
        EventBus.getDefault().post(new ConnectionFailedEvent());
    }
}
项目:Remote    文件:ShowSettingsJob.java   
@Override
public void onRun() throws Throwable {
    String result = new PopcornService().showsettings();
    ShowViewEvent event = new ShowViewEvent(NetworkState.SUCCESS, ShowViewEvent.SETTINGS);
    event.setResponse(result);
    EventBus.getDefault().post(event);
}
项目:tumbviewer    文件:MainActivity.java   
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void refreshData(EventRefresh refreshEvent) {
    EventBus.getDefault().removeStickyEvent(refreshEvent);
    videoFragment.refreshData();
    photoFragment.refreshData();
    searchFragment.refreshData();
    userFragment.refreshData();
    viewPager.setCurrentItem(0);
}
项目:localcloud_fe    文件:UpdatesLoader.java   
private static void executeTask(final WorkerTask task) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            task.run();
            isExecuting = false;

            EventBus.getDefault().post(task.result());
        }
    }).start();
}
项目:USay    文件:CreatePostActivity.java   
@Override
public void onItemClicked(int position) {
    if (position == mAdapter.getItemCount()-1) {
        startActivity(new Intent(CreatePostActivity.this, PhotosSelectActivity.class));
        EventBus.getDefault().postSticky(new EventEntry(mAdapter.getData(),EventEntry.SELECTED_PHOTOS_ID));
    }
}
项目:atlant-android    文件:CredentialHolder.java   
public static void changePasswordWallet(final Context context, final String password) {
  Thread myThread = new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        myWallet = new MyWallet(myWallet.getPrivateKey());
        myWallet.saveWallet(password, getFile(context, PATH_WALLET));
        EventBus.getDefault().post(new SuccessfulChangePassword());
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  });
  myThread.start();
}
项目:PandwarfDefenderProject    文件:GuardianFragment.java   
/**
 * Start protection, check if frequency && decibel values are regular.
 * If not a toast will be showed.
 *
 * Otherwise an event "START_PROTECTION" will be sent to the main activity.
 */
private void startProtection() {

    if (!Tools.isValidDb(dbToleranceEditText.getText().toString()) ||
            !Tools.isValidFrequency(frequencyEditText.getText().toString())) {
        Toast toast = Toast.makeText(getContext(), "wrong parameters", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.show();
        return;
    }
    refreshCurrentConfiguration();
    historyLogArrayList.clear();
    resetFragment();
    showHistoryButton.setVisibility(View.VISIBLE);
    showHistoryButton.setText(getString(R.string.no_attack_detected_flat_button));
    currentState = PROTECTION_ON_RUN;
    progressBarPandwarfRunning.setVisibility(View.VISIBLE);
    startStopProtectionButton.setText(R.string.stop_protection_text_button); // change text value
    HashMap<String, String> parameters = new HashMap<>(); // parameters will contains the frequency, db, peak tolerance & margin error values.

    parameters.put(Parameter.FREQUENCY.toString(), String.valueOf(currentConfiguration.getFrequency()));
    parameters.put(Parameter.RSSI_VALUE.toString(), String.valueOf(currentConfiguration.getDbTolerance()));
    parameters.put(Parameter.PEAK_TOLERANCE.toString(), String.valueOf(currentConfiguration.getPeakTolerance()));
    parameters.put(Parameter.MARGIN_ERROR.toString(), String.valueOf(currentConfiguration.getMarginError()));
    EventBus.getDefault().postSticky(new ActionEvent(Action.START_PROTECTION, parameters));
    addLog(HistoryLog.WARNING_LEVEL.LOW, "Protection started");

}
项目:PADC-SFC-News    文件:SFCCallback.java   
@Override
public void onResponse(Call<T> call, Response<T> response) {
    SFCResponse sfcResponse = response.body();
    if (sfcResponse == null) {
        RestApiEvents.ErrorInvokingAPIEvent errorEvent
                = new RestApiEvents.ErrorInvokingAPIEvent("No data could be loaded for now. Pls try again later.");
        EventBus.getDefault().post(errorEvent);
    }
}
项目:QiangHongBao    文件:QHBService.java   
@Override
public void onInterrupt() { // 服务中断,如授权关闭或者将服务杀死
    ToastUtils.show("抢红包服务中断");
    LogUtils.printErr("抢红包服务中断");
    isRun = false;
    EventBus.getDefault().post(new MessageEvent(MessageEvent.QHB_SERVICE_STATE, false));
}
项目:PeSanKita-android    文件:AttachmentDownloadJob.java   
private void retrieveAttachment(MasterSecret masterSecret,
                                long messageId,
                                final AttachmentId attachmentId,
                                final Attachment attachment)
    throws IOException
{

  AttachmentDatabase database       = DatabaseFactory.getAttachmentDatabase(context);
  File               attachmentFile = null;

  try {
    attachmentFile = createTempFile();

    SignalServiceAttachmentPointer pointer = createAttachmentPointer(masterSecret, attachment);
    InputStream                    stream  = messageReceiver.retrieveAttachment(pointer, attachmentFile, 0, new ProgressListener() {
      @Override
      public void onAttachmentProgress(long total, long progress) {
        EventBus.getDefault().postSticky(new PartProgressEvent(attachment, total, progress));
      }
    });

    database.insertAttachmentsForPlaceholder(masterSecret, messageId, attachmentId, stream);
  } catch (InvalidPartException | NonSuccessfulResponseCodeException | InvalidMessageException | MmsException e) {
    Log.w(TAG, e);
    markFailed(messageId, attachmentId);
  } finally {
    if (attachmentFile != null)
      attachmentFile.delete();
  }
}
项目:atlant-android    文件:TransactionRestHandler.java   
private void requestNonce(final AtlantClient atlantClient, final String address) {
  BaseRequest<Nonce> callback = new BaseRequest<>(new BaseRequest.Callback<Nonce>() {
    @Override
    public void onResponse(Response<Nonce> response) {
      nonce = response.body();
      if (nonce != null && gasPrice != null) {
        EventBus.getDefault().post(new OnStatusSuccess(BaseActivity.REQUEST_CODE_SEND, nonce, gasPrice));
      }
    }
  }, BaseActivity.REQUEST_CODE_SEND);
  callNonce = atlantClient.getNonce(callback, address);
}
项目:BizareChat    文件:BizareChatMessageService.java   
void processPrivateMessage(Message message) {
    JobExecutor.getInstance().execute(() -> {
        MessageModel messageModel = getMessageModel(message);
        savePrivateMessageToDb(messageModel);

        EventBus.getDefault().post(new PrivateMessageEvent(messageModel));
    });
}
项目:Weather-Guru-MVP    文件:ManageCityActivity.java   
@Override public void onCityDelete(int position) {
  EventBus.getDefault().postSticky(new RefreshCitiesEvent());
  adapter.remove(position);
  if (adapter.getData().isEmpty()) {
    showEmptyView();
  }
}
项目:AssistantBySDK    文件:MusicOptProcessor.java   
/**
 * 合成语音并显示文本
 **/
private void speakAndShow(Command cmd, String text, int inputType, SpeechMsgBuilder msgBuilder) {
    if (EventBus.getDefault().hasSubscriberForEvent(RobotTipsEvent.class))
        EventBus.getDefault().post(new RobotTipsEvent(cmd.getTtext()));
    if (inputType == AssistantService.INPUT_VOICE) {
        msgBuilder.setText(text);
        SynthesizerBase.get().startSpeakAbsolute(msgBuilder.build())
                /* 合成是在Observable的subscribe()开始的,所以要在这之前通知动画播放。
                 *  doOnSubscribe 执行在离它最近的 subscribeOn() 所指定的线程。*/
                .doOnNext(new Consumer<SpeechMsg>() {
                    @Override
                    public void accept(SpeechMsg speechMsg) throws Exception {
                        if (speechMsg.state() == SpeechMsg.State.OnBegin)
                            EventBus.getDefault().post(new SynthesizeEvent(SynthesizeEvent.SYNTH_START));
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        EventBus.getDefault().post(new SynthesizeEvent(SynthesizeEvent.SYNTH_END));
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.computation())
                .subscribe();
    }
}
项目:A.scribe    文件:NoteViewHolder.java   
@Override
public void onItemClear(int droppedAt) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        itemView.setTranslationZ(NOTE_DEFAULT_HEIGHT);
    } else {
        itemView.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
    }
    if (droppedAt != dragStartPosition) {
        EventBus.getDefault().post(new NoteMovedEvent(dragStartPosition, droppedAt));
    }
}
项目:android-ponewheel    文件:OWDevice.java   
public void processUnknownUuid(String incomingUuid, byte[] incomingValue) {
    StringBuilder sb = new StringBuilder();
    for (byte b : incomingValue) {
        sb.append(String.format("%02x", b));
    }
    //this.unknownUUID.set(c_uuid);
    //this.unknownValue.set("hex:" + sb.toString() + " (" + Integer.toString(unsignedShort(c_value)) + ")");
    EventBus.getDefault().post(new DeviceStatusEvent("UNKNOWN " + incomingUuid + ":" +
            "hex:" + sb.toString() + " (" + Integer.toString(unsignedShort(incomingValue)) + ")"));
    Log.i(TAG, "UNKNOWN Device characteristic:" + incomingUuid + " value=" + sb.toString() + "|" + Integer.toString(unsignedShort(incomingValue)));
}
项目:BookReader-master    文件:BookDetailActivity.java   
@Override
protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
    if (mPresenter != null) {
        mPresenter.detachView();
    }
}
项目:VBrowser-Android    文件:MainActivity.java   
@Override
protected void onStop() {
    stopRefreshGoBackButtonStateThread();
    if (mainWebView != null) {
        mainWebView.pauseTimers();
        mainWebView.onHide();
    }
    if(videoSniffer!=null) {
        videoSniffer.stopSniffer();
    }
    EventBus.getDefault().unregister(this);
    super.onStop();
}