@Override
 public void onWindowFocusChanged(boolean hasFocus) {
   Log.v(TAG, "focus : " + hasFocus);
   if (hasFocus) {
     new Handler()
         .post(
             new Runnable() {
               @Override
               public void run() {
                 discreteSeekBar.showFloater(250);
               }
             });
   } else {
     discreteSeekBar.hideFloater(250);
   }
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    try {
      android.support.v7.app.ActionBar actionBar = getSupportActionBar();
      if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(false);
      }
    } catch (NullPointerException e) {
      e.printStackTrace();
    }

    Intent intent = getIntent();
    gagTitle = intent.getStringExtra(GAG_TITLE);
    gagURL = intent.getStringExtra(GAG_URL);
    file_ext = getIntent().getStringExtra(FILE_EXT);

    setContentView(R.layout.activity_display_recieved_image);
    bp = new BitmapProcessor(this, DisplayReceivedImage.this);

    final FloatingActionMenu fam = (FloatingActionMenu) findViewById(R.id.fam);
    FloatingActionButton save = (FloatingActionButton) findViewById(R.id.save);
    FloatingActionButton share = (FloatingActionButton) findViewById(R.id.share);
    FloatingActionButton changeTitle = (FloatingActionButton) findViewById(R.id.changeTitle);
    final FloatingActionButton changeSize = (FloatingActionButton) findViewById(R.id.changeSize);
    final TouchImageView mImageView = (TouchImageView) findViewById(R.id.imageViewPhoto);

    DiscreteSeekBar seekbar = (DiscreteSeekBar) findViewById(R.id.seekBar);
    final RelativeLayout sbc = (RelativeLayout) findViewById(R.id.seekBarContainer);
    sbc.setVisibility(View.INVISIBLE);

    changeSize.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            sbc.setVisibility(View.VISIBLE);
            changeSize.setEnabled(false);
          }
        });

    seekbar.setOnProgressChangeListener(
        new DiscreteSeekBar.OnProgressChangeListener() {
          @Override
          public void onProgressChanged(DiscreteSeekBar seekBar, int value, boolean fromUser) {
            customPercent = value;
          }

          @Override
          public void onStartTrackingTouch(DiscreteSeekBar seekBar) {
            Toast.makeText(
                    context,
                    "Changes will take effect after releasing seek bar.",
                    Toast.LENGTH_SHORT)
                .show();
          }

          @Override
          public void onStopTrackingTouch(DiscreteSeekBar seekBar) {
            fam.close(true);
            bp.cache(file_ext, mImageView, true, true);
          }
        });

    changeTitle.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            new MaterialDialog.Builder(context)
                .title("Change Title Text")
                .theme(Theme.DARK)
                .cancelable(false)
                .inputType(InputType.TYPE_CLASS_TEXT)
                .alwaysCallInputCallback()
                .negativeText("Cancel")
                .input(
                    "Title",
                    gagTitle,
                    new MaterialDialog.InputCallback() {
                      @Override
                      public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                        if (input.length() == 0) {
                          dialog.getActionButton(DialogAction.POSITIVE).setEnabled(false);
                          newGagTitle = "";
                        } else {
                          dialog.getActionButton(DialogAction.POSITIVE).setEnabled(true);
                          newGagTitle = input.toString();
                        }
                      }
                    })
                .onPositive(
                    new MaterialDialog.SingleButtonCallback() {
                      @Override
                      public void onClick(
                          @NonNull MaterialDialog materialDialog,
                          @NonNull DialogAction dialogAction) {
                        if (!newGagTitle.equals("")) gagTitle = newGagTitle;
                        bp.cache(
                            file_ext, mImageView, !(customPercent == 5), !newGagTitle.equals(""));
                      }
                    })
                .show();
          }
        });

    save.setOnClickListener(this);
    share.setOnClickListener(this);

    photoURI =
        Uri.parse(
            getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/downloads/GAG" + file_ext);

    bp.cache(file_ext, mImageView, false, true);
  }
  private void setAdvertisingInteval() {

    adInterval = discreteSeekBar.getProgress() * 5;

    Log.v(TAG, "setting AD interval to " + adInterval + "ms");

    runOnUiThread(
        new Runnable() {

          @Override
          public void run() {

            if (btDevice != null && !btDevice.getDeviceAddress().equals("")) {

              final String deviceAddress = btDevice.getDeviceAddress();

              if (mService.isScanning()) {

                scanMenuItem.setIcon(R.drawable.ic_bluetooth);
                mService.stopScan();
              }

              if (!mService.getConnectionList().containsKey(deviceAddress)
                  || !mService.getConnectionList().get(deviceAddress).isConnected()) {

                dialog =
                    ProgressDialog.show(
                        RFdroidActivity.this,
                        "",
                        getResources().getString(R.string.connection_to_rfdroid),
                        true);
                mService.connect(deviceAddress);

              } else {

                if (!mService.getConnectionList().get(deviceAddress).isConnected()) {
                  mService.connect(deviceAddress);
                } else {

                  if (mService.getConnectionList().get(deviceAddress).getDevice()
                      instanceof IRfduinoDevice) {

                    IRfduinoDevice device =
                        (IRfduinoDevice)
                            mService.getConnectionList().get(deviceAddress).getDevice();

                    device.setAdvertisingInterval(
                        adInterval,
                        new IPushListener() {
                          @Override
                          public void onPushFailure() {
                            Log.v(TAG, "onPushFailure");
                            mService.disconnect(deviceAddress);
                            refreshViewOnError();
                          }

                          @Override
                          public void onPushSuccess() {
                            Log.v(TAG, "onPushSuccess");
                            mService.disconnect(deviceAddress);
                            refreshViewOnSucccess();
                          }
                        });
                  }
                }
              }
            }
          }
        });
  }
        @Override
        public void onReceive(Context context, Intent intent) {

          final String action = intent.getAction();

          if (BluetoothEvents.BT_EVENT_SCAN_START.equals(action)) {
            Log.v(TAG, "Scan has started");
          } else if (BluetoothEvents.BT_EVENT_SCAN_END.equals(action)) {
            Log.v(TAG, "Scan has ended");
          } else if (BluetoothEvents.BT_EVENT_DEVICE_DISCOVERED.equals(action)) {
            Log.v(TAG, "New device has been discovered");

            BluetoothObject btDeviceTmp = BluetoothObject.parseArrayList(intent);

            if (btDeviceTmp != null
                && btDeviceTmp.getAdvertizingInterval() != -1
                && discreteSeekBar != null
                && intervalTv != null
                && globalReceptionRateTv != null) {

              btDevice = btDeviceTmp;

              if (deviceFoundDialog != null) deviceFoundDialog.dismiss();

              adInterval = btDevice.getAdvertizingInterval();
              discreteSeekBar.setProgress(btDevice.getAdvertizingInterval() / 5);
              intervalTv.setText(
                  getResources().getString(R.string.interval)
                      + " - "
                      + btDevice.getAdvertizingInterval()
                      + "ms");
              globalReceptionRateTv.setText("0%");
            }

          } else if (BluetoothEvents.BT_EVENT_DEVICE_DISCONNECTED.equals(action)) {

            Log.v(TAG, "Device disconnected");

            BluetoothObject btDevice = BluetoothObject.parseArrayList(intent);

            if (btDevice != null) {
              closeDialog();
            }

          } else if (BluetoothEvents.BT_EVENT_DEVICE_CONNECTED.equals(action)) {

            Log.v(TAG, "device connected");

            BluetoothObject btDevice = BluetoothObject.parseArrayList(intent);

            if (btDevice != null && !btDevice.getDeviceAddress().equals("")) {

              final String deviceAddress = btDevice.getDeviceAddress();

              if (mService.getConnectionList().get(deviceAddress).getDevice()
                  instanceof IRfduinoDevice) {

                IRfduinoDevice device =
                    (IRfduinoDevice) mService.getConnectionList().get(deviceAddress).getDevice();

                device.setAdvertisingInterval(
                    adInterval,
                    new IPushListener() {
                      @Override
                      public void onPushFailure() {
                        Log.v(TAG, "onPushFailure");
                        mService.disconnect(deviceAddress);
                        refreshViewOnError();
                      }

                      @Override
                      public void onPushSuccess() {
                        Log.v(TAG, "onPushSuccess");
                        mService.disconnect(deviceAddress);
                        refreshViewOnSucccess();
                      }
                    });
              }
            }
          }
        }
  protected void onCreate(Bundle savedInstanceState) {

    setLayout(R.layout.activity_rfdroid);
    super.onCreate(savedInstanceState);

    registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

    UiModeManager uiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE);

    deviceFoundDialog =
        ProgressDialog.show(
            RFdroidActivity.this,
            "",
            getResources().getString(R.string.toast_looking_for_rfdroid),
            true);
    deviceFoundDialog.setCancelable(false);
    deviceFoundDialog.setOnKeyListener(
        new DialogInterface.OnKeyListener() {
          @Override
          public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
              dialog.dismiss();
              onBackPressed();
              return true;
            }
            return false;
          }
        });

    final ScrollView view = (ScrollView) findViewById(R.id.scrollview);
    view.getViewTreeObserver()
        .addOnScrollChangedListener(
            new ViewTreeObserver.OnScrollChangedListener() {
              @Override
              public void onScrollChanged() {
                if (!openingDrawer) {
                  if (view.getScrollX() == 0 && view.getScrollY() == 0) {
                    discreteSeekBar.showFloater(250);
                  } else {
                    discreteSeekBar.hideFloater(1);
                  }
                }
              }
            });

    sharedpreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
    int dataChartTypeVal =
        sharedpreferences.getInt("dataChartType", DataChartType.RECEPTION_RATE.ordinal());

    if (dataChartTypeVal == DataChartType.PACKET_NUMBER.ordinal()) {
      dataChartType = DataChartType.PACKET_NUMBER;
    }

    tablelayout = (TableLayout) findViewById(R.id.tablelayout);

    altTableRow(2);

    mChart = (BarChart) findViewById(R.id.chart1);

    mChart.setDrawBarShadow(false);
    mChart.setDrawValueAboveBar(true);

    mChart.setDescription("");

    // if more than 60 entries are displayed in the chart, no values will be
    // drawn
    mChart.setMaxVisibleValueCount(60);

    // scaling can now only be done on x- and y-axis separately
    mChart.setPinchZoom(false);

    mChart.setDrawGridBackground(false);
    mChart.setDescriptionColor(Color.parseColor("#000000"));

    XAxis xAxis = mChart.getXAxis();
    xAxis.setDrawGridLines(false);
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setSpaceBetweenLabels(0);

    YAxisValueFormatter custom = new DataAxisFormatter("%");

    YAxis leftAxis = mChart.getAxisLeft();
    leftAxis.setValueFormatter(custom);
    leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);

    YAxis rightAxis = mChart.getAxisRight();
    rightAxis.setValueFormatter(custom);
    rightAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);

    leftAxis.setDrawGridLines(true);
    rightAxis.setDrawGridLines(false);

    mChart.animateY(1000);

    mChart.getLegend().setEnabled(true);

    mChart.setVisibility(View.GONE);

    discreteSeekBar = (DiscreteSeekBar) findViewById(R.id.discrete1);
    discreteSeekBar.keepShowingPopup(true);

    discreteSeekBar.setNumericTransformer(
        new DiscreteSeekBar.NumericTransformer() {
          @Override
          public int transform(int value) {
            return value * 5;
          }
        });

    discreteSeekBar.setOnFocusChangeListener(
        new View.OnFocusChangeListener() {
          @Override
          public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
              discreteSeekBar.showFloater(250);
            }
          }
        });

    discreteSeekBar.setOnProgressChangeListener(
        new DiscreteSeekBar.OnProgressChangeListener() {

          @Override
          public void onProgressChanged(DiscreteSeekBar seekBar, int value, boolean fromUser) {}

          @Override
          public void onStartTrackingTouch(DiscreteSeekBar seekBar) {}

          @Override
          public void onStopTrackingTouch(DiscreteSeekBar seekBar) {
            setAdvertisingInteval();
          }
        });

    if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) {

      discreteSeekBar.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              setAdvertisingInteval();
            }
          });
    }

    intervalTv = (TextView) findViewById(R.id.interval_head);
    globalReceptionRateTv = (TextView) findViewById(R.id.global_reception_rate);
    lastPacketReceivedTv = (TextView) findViewById(R.id.last_packet_received_value);
    samplingTimeTv = (TextView) findViewById(R.id.sampling_time_value);
    totalPacketReceiveTv = (TextView) findViewById(R.id.total_packet_received_value);
    averagePacketReceivedTv = (TextView) findViewById(R.id.average_packet_received_value);

    initTv();

    if (mBluetoothAdapter.isEnabled()) {
      Intent intent = new Intent(this, BtAnalyzerService.class);
      mBound = bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
    }
  }