Android Open Source - MovisensGattSensorExample Device Scan Activity






From Project

Back to project page MovisensGattSensorExample.

License

The source code is released under:

GNU General Public License

If you think the Android project MovisensGattSensorExample listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.movisens.gattsensorexample.activities;
//  www . java2s. c o m
import static com.movisens.gattsensorexample.application.App.app;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.movisens.gattsensorexample.R;

/**
 * Activity for scanning and displaying available Bluetooth LE devices.
 */
public class DeviceScanActivity extends ListActivity {
  private LeDeviceListAdapter mLeDeviceListAdapter;
  private BluetoothAdapter mBluetoothAdapter;
  private boolean mScanning;
  private Handler mHandler;

  private static final int REQUEST_ENABLE_BT = 1;
  // Stops scanning after 10 seconds.
  private static final long SCAN_PERIOD = 15000;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(R.string.title_devices);
    mHandler = new Handler();

    // Use this check to determine whether BLE is supported on the device.
    // Then you can
    // selectively disable BLE-related features.
    if (!getPackageManager().hasSystemFeature(
        PackageManager.FEATURE_BLUETOOTH_LE)) {
      Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT)
          .show();
      finish();
    }

    // Initializes a Bluetooth adapter. For API level 18 and above, get a
    // reference to
    // BluetoothAdapter through BluetoothManager.
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    // Checks if Bluetooth is supported on the device.
    if (mBluetoothAdapter == null) {
      Toast.makeText(this, R.string.error_bluetooth_not_supported,
          Toast.LENGTH_SHORT).show();
      finish();
      return;
    }
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    if (!mScanning) {
      menu.findItem(R.id.menu_stop).setVisible(false);
      menu.findItem(R.id.menu_scan).setVisible(true);
      menu.findItem(R.id.menu_refresh).setActionView(null);
    } else {
      menu.findItem(R.id.menu_stop).setVisible(true);
      menu.findItem(R.id.menu_scan).setVisible(false);
      menu.findItem(R.id.menu_refresh).setActionView(
          R.layout.actionbar_indeterminate_progress);
    }
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_scan:
      mLeDeviceListAdapter.clear();
      scanLeDevice(true);
      break;
    case R.id.menu_stop:
      scanLeDevice(false);
      break;
    }
    return true;
  }

  @Override
  protected void onResume() {
    super.onResume();

    // Ensures Bluetooth is enabled on the device. If Bluetooth is not
    // currently enabled,
    // fire an intent to display a dialog asking the user to grant
    // permission to enable it.
    if (!mBluetoothAdapter.isEnabled()) {
      if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(
            BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
      }
    }

    // Initializes list view adapter.
    mLeDeviceListAdapter = new LeDeviceListAdapter();
    setListAdapter(mLeDeviceListAdapter);
    scanLeDevice(true);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // User chose not to enable Bluetooth.
    if (requestCode == REQUEST_ENABLE_BT
        && resultCode == Activity.RESULT_CANCELED) {
      finish();
      return;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  @Override
  protected void onPause() {
    super.onPause();
    scanLeDevice(false);
    mLeDeviceListAdapter.clear();
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    if (device == null)
      return;

    Editor editor = app().getPrefs().edit();
    editor.putString(Preferences.SENSOR_ADDRESS, device.getAddress());
    editor.putString(Preferences.SENSOR_NAME, device.getName());
    editor.commit();

    if (mScanning) {
      mBluetoothAdapter.stopLeScan(mLeScanCallback);
      mScanning = false;
    }

    finish();
  }

  private void scanLeDevice(final boolean enable) {
    if (enable) {
      // Stops scanning after a pre-defined scan period.
      mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
          mScanning = false;
          mBluetoothAdapter.stopLeScan(mLeScanCallback);
          invalidateOptionsMenu();
        }
      }, SCAN_PERIOD);

      mScanning = true;
      mBluetoothAdapter.startLeScan(mLeScanCallback);
    } else {
      mScanning = false;
      mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
    invalidateOptionsMenu();
  }

  // Adapter for holding devices found through scanning.
  private class LeDeviceListAdapter extends BaseAdapter {
    private ArrayList<BluetoothDevice> mLeDevices;
    private HashMap<String, Integer> mRssi;
    private LayoutInflater mInflator;

    public LeDeviceListAdapter() {
      super();
      mLeDevices = new ArrayList<BluetoothDevice>();
      mRssi = new HashMap<String, Integer>();
      mInflator = DeviceScanActivity.this.getLayoutInflater();
    }

    public void addDevice(BluetoothDevice device, int rssi) {
      if (!mLeDevices.contains(device)) {
        mLeDevices.add(device);
      }
      mRssi.put(device.getAddress(), rssi);
    }

    public BluetoothDevice getDevice(int position) {
      return mLeDevices.get(position);
    }

    public void clear() {
      mLeDevices.clear();
    }

    @Override
    public int getCount() {
      return mLeDevices.size();
    }

    @Override
    public Object getItem(int i) {
      return mLeDevices.get(i);
    }

    @Override
    public long getItemId(int i) {
      return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
      ViewHolder viewHolder;
      // General ListView optimization code.
      if (view == null) {
        view = mInflator.inflate(R.layout.listitem_device, null);
        viewHolder = new ViewHolder();
        viewHolder.deviceAddress = (TextView) view
            .findViewById(R.id.device_address);
        viewHolder.deviceName = (TextView) view
            .findViewById(R.id.device_name);
        viewHolder.deviceRssi = (TextView) view
            .findViewById(R.id.device_rssi);
        view.setTag(viewHolder);
      } else {
        viewHolder = (ViewHolder) view.getTag();
      }

      BluetoothDevice device = mLeDevices.get(i);
      Integer rssi = mRssi.get(device.getAddress());
      final String deviceName = device.getName();
      if (deviceName != null && deviceName.length() > 0)
        viewHolder.deviceName.setText(deviceName);
      else
        viewHolder.deviceName.setText(R.string.unknown_device);
      viewHolder.deviceAddress.setText(device.getAddress());
      viewHolder.deviceRssi.setText(getString(R.string.rssi,
          rssi.toString()));

      return view;
    }
  }

  // Device scan callback.
  private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

    @Override
    public void onLeScan(final BluetoothDevice device, final int rssi,
        byte[] scanRecord) {
      runOnUiThread(new Runnable() {
        @Override
        public void run() {
          mLeDeviceListAdapter.addDevice(device, rssi);
          mLeDeviceListAdapter.notifyDataSetChanged();
        }
      });
    }
  };

  static class ViewHolder {
    TextView deviceName;
    TextView deviceAddress;
    TextView deviceRssi;
  }
}




Java Source Code List

com.movisens.gattsensorexample.activities.DeviceScanActivity.java
com.movisens.gattsensorexample.activities.Preferences.java
com.movisens.gattsensorexample.activities.SensorConnected.java
com.movisens.gattsensorexample.activities.SensorDisconnected.java
com.movisens.gattsensorexample.activities.StartActivity.java
com.movisens.gattsensorexample.activities.TimePreference.java
com.movisens.gattsensorexample.application.App.java
com.movisens.gattsensorexample.events.BLEEvent.java
com.movisens.gattsensorexample.events.MeasurementStatus.java
com.movisens.gattsensorexample.events.SensorStatusEvent.java
com.movisens.gattsensorexample.model.CurrentSensorData.java
com.movisens.gattsensorexample.receivers.SystemStateReceiver.java
com.movisens.gattsensorexample.receivers.UpdateAppReceiver.java
com.movisens.gattsensorexample.sensors.MovisensSensor.java
com.movisens.gattsensorexample.services.BluetoothLeService.java
com.movisens.gattsensorexample.services.SamplingService.java
com.movisens.gattsensorexample.utils.BleQueue.java
com.movisens.gattsensorexample.utils.BleUtils.java