public static void startDownload(
      Context context, Magazine magazine, boolean isTemp, String tempUrlKey) {
    String fileUrl = magazine.getItemUrl();
    String filePath = magazine.getItemPath();
    if (magazine.isSample()) {
      fileUrl = magazine.getSamplePdfUrl();
      filePath = magazine.getSamplePdfPath();
    } else if (isTemp) {
      fileUrl = tempUrlKey;
    }
    Log.d(
        TAG,
        "isSample: " + magazine.isSample() + "\nfileUrl: " + fileUrl + "\nfilePath: " + filePath);
    EasyTracker.getTracker().sendView("Downloading/" + FilenameUtils.getBaseName(filePath));
    DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileUrl));
    request
        .setVisibleInDownloadsUi(false)
        .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
        .setDescription(magazine.getSubtitle())
        .setTitle(magazine.getTitle() + (magazine.isSample() ? " Sample" : ""))
        .setDestinationInExternalFilesDir(context, null, FilenameUtils.getName(filePath));
    // TODO should use cache directory?
    magazine.setDownloadManagerId(dm.enqueue(request));

    MagazineManager magazineManager = new MagazineManager(context);
    magazineManager.removeDownloadedMagazine(context, magazine);
    magazineManager.addMagazine(magazine, Magazine.TABLE_DOWNLOADED_MAGAZINES, true);
    magazine.clearMagazineDir();
    EventBus.getDefault().post(new LoadPlistEvent());
  }
Exemple #2
0
 @Override
 protected void onDestroy() {
   realmDBManager.close();
   if (EventBus.getDefault().isRegistered(this)) EventBus.getDefault().unregister(this);
   Runtime.getRuntime().gc();
   super.onDestroy();
 }
 @Override
 public void onCreate(@Nullable Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   if (!EventBus.getDefault().isRegistered(this)) {
     EventBus.getDefault().register(this);
   }
 }
Exemple #4
0
 @Override
 public void onDestroy() {
   if (event != null) {
     EventBus.getDefault().post(event);
   }
   EventBus.getDefault().unregister(this);
 }
  private void selectAllImages() {

    if (mSelectedAlbum == null) {
      mSelectedAlbum =
          EventBus.getDefault().getStickyEvent(Events.OnClickAlbumEvent.class).albumEntry;
    }

    if (sCheckedImages.size() < mPickOptions.limit || mPickOptions.limit == NO_LIMIT) {

      for (final ImageEntry imageEntry : mSelectedAlbum.imageList) {

        if (mPickOptions.limit != NO_LIMIT && sCheckedImages.size() + 1 > mPickOptions.limit) {
          // Hit the limit
          Toast.makeText(this, R.string.you_cant_check_more_images, Toast.LENGTH_SHORT).show();
          break;
        }

        if (!imageEntry.isPicked) {
          // To avoid repeated images
          sCheckedImages.add(imageEntry);
          imageEntry.isPicked = true;
        }
      }
    }
    EventBus.getDefault().post(new Events.OnUpdateImagesThumbnailEvent());
    updateFab();

    if (shouldShowDeselectAll()) {
      showDeselectAll();
    }
  }
  /**
   * called when visibility of current fragment is (potentially) altered by * * drawer being
   * shown/hidden * * whether buffer is shown in the pager (see MainPagerAdapter) * * availability
   * of buffer & activity * * lifecycle
   */
  public void maybeChangeVisibilityState() {
    if (DEBUG_VISIBILITY) logger.debug("maybeChangeVisibilityState()");
    if (activity == null || buffer == null) return;

    // see if visibility has changed. if it hasn't, do nothing
    boolean obscured = activity.isPagerNoticeablyObscured();
    boolean watched = started && pagerVisible && !obscured;

    if (buffer.isWatched == watched) return;

    // visibility has changed.
    if (watched) {
      highlights = buffer.highlights;
      privates = (buffer.type == Buffer.PRIVATE) ? buffer.unreads : 0;
    }
    buffer.setWatched(watched);
    scrollToHotLineIfNeeded();

    // move the read marker in weechat (if preferences dictate)
    if (!watched && P.hotlistSync) {
      EventBus.getDefault()
          .post(new SendMessageEvent("input " + buffer.fullName + " /buffer set hotlist -1"));
      EventBus.getDefault()
          .post(
              new SendMessageEvent(
                  "input " + buffer.fullName + " /input set_unread_current_buffer"));
    }
  }
Exemple #7
0
  private void onRebroadcastResponse(
      boolean successful, Broadcast result, VolleyError error, RebroadcastState state) {

    if (successful) {

      if (!state.rebroadcast) {
        // Delete the rebroadcast broadcast by user. Must be done before we update the
        // broadcast so that we can retrieve rebroadcastId for the old one.
        // This will not finish this activity, because this activity displays the
        // rebroadcasted broadcast instead of the rebroadcast broadcast itself, and this is
        // the desired behavior since it won't surprise user, and user can have the chance
        // to undo it.
        Broadcast broadcast = mBroadcastAdapter.getBroadcast();
        if (broadcast != null && broadcast.rebroadcastId != null) {
          EventBus.getDefault().post(new BroadcastDeletedEvent(broadcast.rebroadcastId));
        }
      }
      EventBus.getDefault().post(new BroadcastUpdatedEvent(result));
      ToastUtils.show(
          state.rebroadcast
              ? R.string.broadcast_rebroadcast_successful
              : R.string.broadcast_unrebroadcast_successful,
          this);

    } else {

      LogUtils.e(error.toString());
      Broadcast broadcast = mBroadcastAdapter.getBroadcast();
      if (broadcast != null) {
        boolean notified = false;
        if (error instanceof ApiError) {
          // Correct our local state if needed.
          ApiError apiError = (ApiError) error;
          Boolean shouldBeRebroadcasted = null;
          if (apiError.code == Codes.RebroadcastBroadcast.ALREADY_REBROADCASTED) {
            shouldBeRebroadcasted = true;
          } else if (apiError.code == Codes.RebroadcastBroadcast.NOT_REBROADCASTED_YET) {
            shouldBeRebroadcasted = false;
          }
          if (shouldBeRebroadcasted != null) {
            broadcast.fixRebroacasted(shouldBeRebroadcasted);
            EventBus.getDefault().post(new BroadcastUpdatedEvent(broadcast));
            notified = true;
          }
        }
        if (!notified) {
          // Must notify changed to reset pending status so that off-screen
          // items will be invalidated.
          mBroadcastAdapter.notifyBroadcastChanged();
        }
      }
      ToastUtils.show(
          getString(
              state.rebroadcast
                  ? R.string.broadcast_rebroadcast_failed_format
                  : R.string.broadcast_unrebroadcast_failed_format,
              ApiError.getErrorString(error, this)),
          this);
    }
  }
        @Override
        public void run() {

          EventBus.getDefault().post(new HeartRateEvent("Couldn't find anything"));

          mScanning = false;
          mBluetoothAdapter.stopLeScan(mLeScanCallback);

          if (!mConnected) {

            EventBus.getDefault().post(new HeartRateEvent("Not connected, trying again..."));

            mBpm = HeartRateConstants.HEART_RATE_MONITOR_NOT_CONNECTED;
            mCurrentRSSI = 0;

            removeTimers();

            mTimer = new Timer();
            mTimer.schedule(
                new TimerTask() {
                  @Override
                  public void run() {
                    scanLeDevice(true);
                  }
                },
                SCAN_PERIOD);
          }
        }
 @Override
 public void onReceive(Context context, Intent intent) {
   final String action = intent.getAction();
   if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
     final int state =
         intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
     switch (state) {
       case BluetoothAdapter.STATE_ON:
         EventBus.getDefault().post(new HeartRateEvent("Bluetooth turned on"));
         mBpm = HeartRateConstants.HEART_RATE_MONITOR_NOT_CONNECTED;
         EventBus.getDefault().post(new BlueToothLEEvent(mBpm));
         if (mContext != null) {
           mContext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
         }
         scanLeDevice(true);
         break;
       case BluetoothAdapter.STATE_OFF:
         EventBus.getDefault().post(new HeartRateEvent("Bluetooth turned off"));
         stopListening();
         if (mContext != null) {
           try {
             mContext.unregisterReceiver(mGattUpdateReceiver);
           } catch (Exception exp) {
             exp.printStackTrace();
           }
         }
         break;
     }
   }
 }
 public void onLoginSuccess() {
   int loginId = IMLoginManager.instance().getLoginId();
   configurationSp = ConfigurationSp.instance(ctx, loginId);
   if (!EventBus.getDefault().isRegistered(inst)) {
     EventBus.getDefault().register(inst);
   }
 }
 @Override
 protected void onHandleIntent(Intent intent) {
   String url = null;
   String userName = intent.getStringExtra(PROVIDED_USER_NAME);
   String instrumentName = intent.getStringExtra(PROVIDED_INSTRUMENT);
   try {
     url = URLDecoder.decode(getString(R.string.poll_post_url, instrumentName, userName), "UTF-8");
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   if (url == null) return;
   RequestFuture<String> future = RequestFuture.newFuture();
   StringRequest request = new StringRequest(Request.Method.POST, url, future, future);
   Volley.newRequestQueue(getApplicationContext()).add(request);
   try {
     String response = future.get(30, TimeUnit.SECONDS);
     PostPollDto dto = new Gson().fromJson(response, PostPollDto.class);
     if (dto.getStatus().toLowerCase().equalsIgnoreCase("ok")) {
       PreferencesUtil.savePollInstrument(getApplicationContext(), instrumentName);
       PreferencesUtil.saveUserName(getApplicationContext(), userName);
       EventBus.getDefault().post(new PollPostEvent());
     } else {
       EventBus.getDefault().post(new PollPostEvent(dto.getMsg()));
     }
   } catch (InterruptedException | ExecutionException | TimeoutException e) {
     EventBus.getDefault().post(new PollPostEvent(e.getLocalizedMessage()));
   }
 }
 @Override
 public void onResume() {
   if (isStickyAvailable()) {
     EventBus.getDefault().registerSticky(this);
   } else {
     EventBus.getDefault().register(this);
   }
   super.onResume();
 }
Exemple #13
0
  @Override
  public void onCreate() {
    super.onCreate();

    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    gameDatabase = new GameDatabase(this);

    // init game DB
    if (gameDatabase.getViruses().isEmpty()) {
      Virus v = VirusFactory.createMutation(null);
      Log.d(LOG_TAG, "new virus: " + v.getId());
      gameDatabase.addVirus(v);
      EventBus.getDefault().post(new GameEvent(GameEvent.Type.NEW_VIRUS, v.getId(), 0));
    }
    clientId = gameDatabase.getSetting("clientId", null);
    if (clientId == null) {
      clientId = UUID.randomUUID().toString();
      gameDatabase.putSetting("clientId", clientId);
      Log.i(LOG_TAG, "persisted new clientId: " + clientId);
    }

    // MQTT
    mqttClient = new MqttAndroidClient(this, BROKER_URI, clientId);
    mqttClient.setCallback(this);

    // Location
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
      locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER,
          MIN_LOCATION_UPDATE_INTERVAL_MS,
          MIN_LOCATION_UPDATE_DISTANCE_M,
          this);
    else
      locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER,
          MIN_LOCATION_UPDATE_INTERVAL_MS,
          MIN_LOCATION_UPDATE_DISTANCE_M,
          this);

    findBestLastLocation();

    try {
      MqttConnectOptions options = new MqttConnectOptions();
      options.setKeepAliveInterval(0); // no keepalive pings
      mqttClient.connect(options, null, this);
      Log.d(LOG_TAG, "connected to MQTT broker as " + clientId);
    } catch (MqttException e) {
      Log.e(LOG_TAG, "could not connect to MQTT broker at " + BROKER_URI);
    }

    EventBus.getDefault().register(this);
  }
  /** Sign out from wpcom account */
  public static void WordPressComSignOut(Context context) {
    // Keep the analytics tracking at the beginning, before the account data is actual removed.
    AnalyticsTracker.track(Stat.ACCOUNT_LOGOUT);

    removeWpComUserRelatedData(context);

    // broadcast an event: wpcom user signed out
    EventBus.getDefault().post(new UserSignedOutWordPressCom());

    // broadcast an event only if the user is completly signed out
    if (!AccountHelper.isSignedIn()) {
      EventBus.getDefault().post(new UserSignedOutCompletely());
    }
  }
  /** 1. 加载本地信息 2. 请求正规群信息 , 与本地进行对比 3. version groupId 请求 */
  public void onLocalLoginOk() {
    logger.i("group#loadFromDb");

    if (!EventBus.getDefault().isRegistered(inst)) {
      EventBus.getDefault().registerSticky(inst);
    }

    // 加载本地group
    List<GroupEntity> localGroupInfoList = dbInterface.loadAllGroup();
    for (GroupEntity groupInfo : localGroupInfoList) {
      groupMap.put(groupInfo.getPeerId(), groupInfo);
    }

    triggerEvent(new GroupEvent(GroupEvent.Event.GROUP_INFO_OK));
  }
  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mPlaylist = (ArrayList<Long>) getArguments().getSerializable("data");

    new Thread(
            new Runnable() {
              @Override
              public void run() {
                mMusicDataList =
                    MusicInfoLoadUtil.switchAllMusicInfoToSelectedMusicInfo(
                        (HashMap<Long, MusicInfo>) getArguments().getSerializable("map"),
                        mPlaylist);
                mAdapter = new CurrentPlaylistAdapter(getActivity(), mMusicDataList);
              }
            })
        .start();

    mPlayback = new PlayBack();

    EventBus.getDefault().post(new RequestEvent());
    //        Log.d(TAG, "재생목록에서 이벤트가 요청되었습니다.");

  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.monitor_info_fragment, container, false);
    listView = (ListView) view.findViewById(R.id.monitor_list_view);

    // 注册接受消息
    EventBus.getDefault().register(this);

    getLastMonitorInfo();
    // 设置适配器
    monitorInfoAdapter =
        new MonitorInfoAdapter(
            this.getActivity().getApplicationContext(),
            list,
            R.layout.monitor_info_item,
            new String[] {
              "t_m_time", "t_m_temperature", "t_m_humidity",
              "t_m_carbon_dioxide", "t_m_oxygen", "t_m_nitrogen",
              "t_m_ethylene", "t_m_ammonia", "t_m_sulfur_dioxide"
            },
            new int[] {
              R.id.t_m_time, R.id.t_m_temperature, R.id.t_m_humidity,
              R.id.t_m_carbon_dioxide, R.id.t_m_oxygen, R.id.t_m_nitrogen,
              R.id.t_m_ethylene, R.id.t_m_ammonia, R.id.t_m_sulfur_dioxide
            });

    // 设置适配器
    listView.setAdapter(monitorInfoAdapter);
    return view;
  }
 /**
  * This method will be called when a group is posted to the EventBus.
  *
  * @param group The group object sent to the EventBus.
  */
 public void onEvent(Group group) {
   // Unregister this instance. For new push messages the new instance will be registered in
   // onCreate().
   EventBus.getDefault().unregister(this);
   Log.d(TAG, group.toString());
   new GroupDatabaseManager(this).updateGroup(group);
 }
 /**
  * This method will be called when a list of moderators is posted to the EventBus.
  *
  * @param event The bus event containing a list of moderator objects.
  */
 public void onEvent(BusEventModerators event) {
   // Unregister this instance. For new push messages the new instance will be registered in
   // onCreate().
   EventBus.getDefault().unregister(this);
   Log.d(TAG, event.toString());
   ModeratorController.storeModerators(this, event.getModerators(), pushMessage.getId1());
 }
  /**
   * This method will be called when a list of users is posted to the EventBus.
   *
   * @param event The bus event containing a list of user objects.
   */
  public void onEvent(BusEventGroupMembers event) {
    // Unregister this instance. For new push messages the new instance will be registered in
    // onCreate().
    EventBus.getDefault().unregister(this);
    Log.d(TAG, event.toString());
    List<User> users = event.getUsers();

    // Store users in database an add them as group members to the group.
    UserDatabaseManager userDBM = new UserDatabaseManager(this);
    GroupDatabaseManager groupDBM = new GroupDatabaseManager(this);
    for (User u : users) {
      userDBM.storeUser(u);
      // Update users to make name changes visible.
      userDBM.updateUser(u);
      if (u.getActive() != null && u.getActive()) {
        groupDBM.addUserToGroup(pushMessage.getId1(), u.getId());
      } else {
        groupDBM.removeUserFromGroup(pushMessage.getId1(), u.getId());
      }
    }
    NotificationSettings notificationSettings =
        settingsDBM.getGroupNotificationSettings(pushMessage.getId1());
    if (notificationSettings == NotificationSettings.GENERAL) {
      notificationSettings = settingsDBM.getSettings().getNotificationSettings();
    }
    if (notificationSettings.equals(NotificationSettings.ALL)) {
      sendGroupMemberNotification(pushMessage.getId1());
    }
    groupDBM.setGroupNewEvents(pushMessage.getId1(), true);
  }
 @Override
 public void onCreate() {
   super.onCreate();
   EventBus.getDefault().register(this);
   settingsDBM = new SettingsDatabaseManager(this);
   pushMessage = null;
 }
 @Override
 public void createCategory(String newCategoryLabel) {
   mRxCategory
       .getAllCategories()
       .observeOn(AndroidSchedulers.mainThread())
       .subscribe(
           categories -> {
             int totalNumber = categories.size();
             if (!TextUtils.isEmpty(newCategoryLabel)) {
               mRxCategory
                   .saveCategory(newCategoryLabel, 0, totalNumber, true)
                   .observeOn(AndroidSchedulers.mainThread())
                   .subscribe(
                       categories1 -> {
                         boolean success = false;
                         for (Category category : categories1) {
                           if (category.getLabel().equals(newCategoryLabel)) {
                             mAlbumView.changeActivityListMenuCategoryChecked(category);
                             EventBus.getDefault().post(new CategoryCreateEvent());
                             success = true;
                             break;
                           }
                         }
                         if (!success) {
                           mAlbumView.showToast(
                               mContext.getResources().getString(R.string.toast_fail));
                         }
                       });
             } else {
               mAlbumView.showToast(mContext.getResources().getString(R.string.toast_fail));
             }
           });
 }
 @Override
 public void onListItemClick(ListView listView, View view, int position, long id) {
   super.onListItemClick(listView, view, position, id);
   // 发送列表项点击事件,直接使用getItem,这里是DummyItem类型
   Log.d(MainActivity.TAG, "Clicked item:" + position);
   EventBus.getDefault().post(getListView().getItemAtPosition(position));
 }
 @Override
 public void onDetach() {
   super.onDetach();
   //        Log.d(TAG, "CurrentPlaylistFragment is detached");
   // 해제 꼭 해주세요
   EventBus.getDefault().unregister(this);
 }
  public void onEventMainThread(Events.LocationMessageReceived e) {
    // Updates a contact or allocates a new one

    Contact c = App.getContacts().get(e.getTopic());

    if (c == null) {
      Log.v(this.toString(), "Allocating new contact for " + e.getTopic());
      c = new st.alr.mqttitude.model.Contact(e.getTopic());
      updateContact(c);
    }

    c.setLocation(e.getGeocodableLocation());

    App.getContacts().put(e.getTopic(), c);

    //		if (e.getLocationMessage().hasTransition()) {
    //			Notification noti = new Notification.InboxStyle(
    //					new Notification.Builder(this.context)
    //							.setContentTitle("title").setContentText("subject")
    //							.setSmallIcon(R.drawable.ic_notification)).addLine(
    //					"line1").build();
    //
    //		}

    // Fires a new event with the now updated or created contact to which
    // fragments can react
    EventBus.getDefault().post(new Events.ContactUpdated(c));
  }
  @Override
  public void onResp(BaseResp resp) {
    Log.d(TAG, "微信支付回调>>onResp>>" + resp.errCode);

    if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
      if (resp.errCode == 0) {
        //				ToastUtil.show("支付成功");
        EventBus.getDefault().post("pay_success");
      } else {
        //				ToastUtil.show("支付失败,请重试");
        EventBus.getDefault().post("pay_fail");
      }

      finish();
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // register EventBus.
    EventBus.getDefault().register(this);
  }
 /**
  * This method will be called when a channel is posted to the EventBus.
  *
  * @param channel The bus event containing a channel object.
  */
 public void onEvent(Channel channel) {
   // Unregister this instance. For new push messages the new instance will be registered in
   // onCreate().
   EventBus.getDefault().unregister(this);
   Log.d(TAG, "EventBus:" + channel.toString());
   new ChannelDatabaseManager(this).updateChannel(channel);
 }
 @Override
 public void onAttach(Activity activity) {
   super.onAttach(activity);
   //        Log.d(TAG, "CurrentPlaylistFragment is attached");
   // EventBus 등록이 되어서 모든 이벤트를 수신 가능
   EventBus.getDefault().register(this);
 }
 /**
  * This method will be called when conversations are posted to the EventBus.
  *
  * @param event The bus event containing conversation objects.
  */
 public void onEvent(BusEventConversations event) {
   // Unregister this instance. For new push messages the new instance will be registered in
   // onCreate().
   EventBus.getDefault().unregister(this);
   Log.d(TAG, event.toString());
   boolean newConversationsStored =
       GroupController.storeConversations(
           getApplicationContext(), event.getConversations(), pushMessage.getId1());
   if (newConversationsStored
       || (event.getConversations() != null
           && !event.getConversations().isEmpty()
           && pushMessage.getPushType().equals(PushType.CONVERSATION_CHANGED_ALL))) {
     new GroupDatabaseManager(getApplicationContext())
         .setGroupNewEvents(pushMessage.getId1(), true);
     NotificationSettings notificationSettings =
         settingsDBM.getGroupNotificationSettings(pushMessage.getId1());
     if (notificationSettings == NotificationSettings.GENERAL) {
       notificationSettings = settingsDBM.getSettings().getNotificationSettings();
     }
     if (notificationSettings.equals(NotificationSettings.ALL)) {
       sendConversationNotification(pushMessage.getId1());
     } else if (notificationSettings.equals(NotificationSettings.PRIORITY)) {
       if (pushMessage.getPushType().equals(PushType.CONVERSATION_NEW)) {
         sendConversationNotification(pushMessage.getId1());
       }
     }
   }
 }