Android Open Source - GroveColourSensorAndroidApp Main Activity






From Project

Back to project page GroveColourSensorAndroidApp.

License

The source code is released under:

Copyright (c) 2014, Rohit Grover All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: *...

If you think the Android project GroveColourSensorAndroidApp 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.example.coloursensorapp;
import java.util.List;
import java.util.Vector;
/*w  w  w  . j a  va 2 s.  co  m*/
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {

  private BleWrapper mBleWrapper = null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
      getFragmentManager().beginTransaction()
          .add(R.id.container, new PlaceholderFragment()).commit();
    }

    mBleWrapper = new BleWrapper(this, new BleWrapperUiCallbacks.Null() {
      @Override
      public void uiDeviceFound(final BluetoothDevice device, int rssi, byte[] record) {
        if (device.getAddress().equals("EC:08:A1:6E:CF:1C")) {
          mBleWrapper.stopScanning();

          boolean status;
          status = mBleWrapper.connect(device.getAddress().toString());
          if (status == false) {
            Log.i("DEBUG", "uiDeviceFound: conenction problem");
            return;
          }
        }
      }

      @Override
      public void uiDeviceConnected(final BluetoothGatt gatt, final BluetoothDevice device) {
        Log.i("DEBUG", "uiDeviceConnected: connected successfully!");
      }

      @Override
      public void uiAvailableServices(final BluetoothGatt gatt,
                            final BluetoothDevice device,
                            final List<BluetoothGattService> services) {
        for (BluetoothGattService service : services) {
          String serviceName = BleNamesResolver.resolveUuid(service.getUuid().toString());
          Log.i("DEBUG", serviceName);

          if (service.getUuid().equals(BleDefinedUUIDs.Service.COLOR_SENSOR)) {
            mBleWrapper.getCharacteristicsForService(service);
          }
        }
      }

      private Vector<BluetoothGattCharacteristic> charsForNotification;

      @Override
      public void uiCharacteristicForService(final BluetoothGatt gatt,
                                         final BluetoothDevice device,
                                         final BluetoothGattService service,
                                         final List<BluetoothGattCharacteristic> chars) {
        charsForNotification = new Vector<BluetoothGattCharacteristic>();
        for (BluetoothGattCharacteristic characteristic : chars) {
//          Log.i("DEBUG", "discovered char " + BleNamesResolver.resolveUuid(characteristic.getUuid().toString()));
          charsForNotification.add(characteristic);
        }

        if (charsForNotification.size() > 0) {
          mBleWrapper.setNotificationForCharacteristic(charsForNotification.get(0), true);
          charsForNotification.remove(0);
        }
      }

      @Override
      public void uiOnDescriptorWrite (BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        if (charsForNotification.size() > 0) {
          mBleWrapper.setNotificationForCharacteristic(charsForNotification.get(0), true);
          charsForNotification.remove(0);
        }
      }

      @Override
      public void uiGotNotification(final BluetoothGatt gatt,
                                final BluetoothDevice device,
                                final BluetoothGattService service,
                                final BluetoothGattCharacteristic characteristic) {
        int id;
        if (characteristic.getUuid().equals(BleDefinedUUIDs.Characteristic.COLOR_SENSOR_RED)) {
          id = R.id.redValue;
        } else if (characteristic.getUuid().equals(BleDefinedUUIDs.Characteristic.COLOR_SENSOR_GREEN)) {
          id = R.id.greenValue;
        } else if (characteristic.getUuid().equals(BleDefinedUUIDs.Characteristic.COLOR_SENSOR_BLUE)) {
          id = R.id.blueValue;
        } else if (characteristic.getUuid().equals(BleDefinedUUIDs.Characteristic.COLOR_SENSOR_AMBIENCE)) {
          id = R.id.clearValue;
        } else {
          return;
        }

        final String newValue = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0).toString();
        final TextView textView = (TextView) findViewById(id);

        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            textView.setText(newValue);
            }
        });
      }
    });

    if (mBleWrapper.checkBleHardwareAvailable() == false) {
      Toast.makeText(this, "No BLE-compatible hardware detected", Toast.LENGTH_SHORT).show();
      finish();
    }
  }

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

    // check for Bluetooth enabled on each resume
    if (mBleWrapper.isBtEnabled() == false) {
      // Bluetooth is not enabled. Request to user to turn it on.
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivity(enableBtIntent);
      finish();
    }

    if (!mBleWrapper.initialize()) {
      Log.e("DEBUG", "onResume: failed to initialize BleWrapper");
      return;
    }
    Log.i("DEBUG", "initialized BleWrapper");

    mBleWrapper.startScanning();
  }

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

    if (mBleWrapper == null) {
      return;
    }

    mBleWrapper.diconnect();
    mBleWrapper.close();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    switch(id) {
    case R.id.action_settings:
      return true;
    case R.id.action_scan:
      if (mBleWrapper != null) {
        mBleWrapper.startScanning();
      }
      return true;
    case R.id.action_stop:
      if (mBleWrapper != null) {
        mBleWrapper.stopScanning();
      }
      return true;
    default:
      return super.onOptionsItemSelected(item);
    }
  }

  /**
   * A placeholder fragment containing a simple view.
   */
  public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
      View rootView = inflater.inflate(R.layout.fragment_main, container,
          false);
      return rootView;
    }
  }
}




Java Source Code List

com.example.coloursensorapp.BleDefinedUUIDs.java
com.example.coloursensorapp.BleNamesResolver.java
com.example.coloursensorapp.BleWrapperUiCallbacks.java
com.example.coloursensorapp.BleWrapper.java
com.example.coloursensorapp.MainActivity.java