Reading a Bluetooth data stream from an Arduino with Android - android

The Situation
I'm trying to write an application that does one very simple task: when an NFC tag is detected with the appropriate AAR and URI it launches the application, uses data in the tag to connect to a specified Bluetooth radio (specified by the NFC tag) and waits to accept a data stream, which it converts to a string and displays on the screen.
When I run the application currently it simply exits immediately with three runtime exceptions. I would like it to wait passively instead of closing, and I do not understand the runtime exceptions.
The Exceptions
Unable to resume activity; NullPointerException
ParseTag(); exception line 127
onResume(); exception line 83
The Code
public class BlueNF extends Activity {
private BluetoothDevice mBluetoothDevice = null;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket mBluetoothSocket = null;
private NfcAdapter mNfcAdapter = null;
private NdefMessage dashTag = null;
private static final int REQUEST_ENABLE_BT = 3;
private static final UUID SerialPortServiceClass_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private InputStream iStream = null;
public static String iValue = null;
public final static String EXTRA_MESSAGE = "com.yogafarts.hackpsuproject.BlueNF.iValue";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set the content view
setContentView(R.layout.activity_blue_nf);
//Check for NFC
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
//Check for Bluetooth
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#Override
public void onStart() {
super.onStart();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
public void onResume() {
super.onResume();
//IntentFilter ndefTag = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
//Get the current intent
Intent dashTagIntent = getIntent();
//Read extra intent data into tag object (Really just reading the NdefMessage into the dashTag object
dashTag = dashTagIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
//Create a byte array of bluetooth hardware ID using ParseTag
byte[] mBluetoothInfo = ParseTag(dashTag);
//Create a bluetooth adapter object
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mBluetoothInfo);//Should be 0013EF00061A
try {
mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(SerialPortServiceClass_UUID);
}
catch ( IOException e ) {
Log.e( "Bluetooth Socket", "Bluetooth not available, or insufficient permissions" );
}
//Cancel discovery because it's resource intensive (if it's active)
mBluetoothAdapter.cancelDiscovery();
//Connect to the device
try {
mBluetoothSocket.connect();
iStream = mBluetoothSocket.getInputStream();
//System.out.println(iStream);
//OutputStream oStream = mBluetoothSocket.getOutputStream();
}
catch ( IOException e ) {
try { mBluetoothSocket.close();
}
catch ( IOException e2 ) {
Log.e( "Bluetooth Socket", "IO Exception" );
}
}
iValue = iStream.toString();
viewMessage();
}
public byte[] ParseTag(NdefMessage ndef) {
NdefRecord[] mNdef = ndef.getRecords();
return mNdef[2].getPayload();
}
public void viewMessage() {
Intent intent = new Intent(this, DisplayMessage.class);
//TextView text = (TextView) findViewById(R.id.tv);
String message = iValue;//text.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.blue_n, menu);
return true;
}
}
And the activity that displays the text after the stream is read...
public class DisplayMessage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
TextView text = (TextView) findViewById(R.id.tv);
text.setText(com.yogafarts.hackpsuproject.BlueNF.iValue);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.display_message, menu);
return true;
}
}

Related

Bluetooth Connection

I've looked at quite a lot of topics on this in different forums and none seem to help me.
I recently bought an Elegoo car kit, which is compatible with the Arduino IDE, and it comes with different types of code and what not. they even have their own Android app.
My problem is I want to create my own android Bluetooth application that connects/pairs with the module and can control the car remotely. I have my application up and running, it can scan for nearby devices and the HC-08 module appears in the list but I am not able to connect. when I try to connect it says it can't communicate with HC-08. I am pretty sure the problem lies in the android end as the elegoo Bluetooth app connects no problem at all with the Bluetooth module if there is any code on the elegoo board or not. The bluetooth module is a HC-08.
Can someone help me with this ?
Also I am following this youtube tutorial so the credit goes to him for the code.
https://www.youtube.com/watch?v=YJ0JQXcNNTA
Here is the main activity code:
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener{
private static final String TAG = "MainActivity";
BluetoothAdapter mBluetoothAdapter;
Button btnEnableDisable_Discoverable;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch(state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
/**
* Broadcast Receiver for changes made to bluetooth states such as:
* 1) Discoverability mode on/off or expire.
*/
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG, "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG, "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
/**
* Broadcast Receiver for listing devices that are not yet paired
* -Executed by btnDiscover() method.
*/
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
if (action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
/**
* Broadcast Receiver that detects bond state changes (Pairing status changes)
*/
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
}
}
}
};
#Override
protected void onDestroy() {
Log.d(TAG, "onDestroy: called.");
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
//mBluetoothAdapter.cancelDiscovery();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnONOFF = (Button) findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
//Broadcasts when bond state changes (ie:pairing)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(MainActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
}
public void enableDisableBT(){
if(mBluetoothAdapter == null){
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if(!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable(View view) {
Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void btnDiscover(View view) {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if(!mBluetoothAdapter.isDiscovering()){
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
/**
* This method is required for all devices running API23+
* Android must programmatically check the permissions for bluetooth. Putting the proper permissions
* in the manifest is not enough.
*
* NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
}
}
}
/// Here is also my DeviceListAdapter code:
public class DeviceListAdapter extends ArrayAdapter<BluetoothDevice> {
private LayoutInflater mLayoutInflater;
private ArrayList<BluetoothDevice> mDevices;
private int mViewResourceId;
public DeviceListAdapter(Context context, int tvResourceId, ArrayList<BluetoothDevice> devices){
super(context, tvResourceId,devices);
this.mDevices = devices;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = tvResourceId;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflater.inflate(mViewResourceId, null);
BluetoothDevice device = mDevices.get(position);
if (device != null) {
TextView deviceName = (TextView) convertView.findViewById(R.id.tvDeviceName);
TextView deviceAdress = (TextView) convertView.findViewById(R.id.tvDeviceAddress);
if (deviceName != null) {
deviceName.setText(device.getName());
}
if (deviceAdress != null) {
deviceAdress.setText(device.getAddress());
}
}
return convertView;
}
}
Some of the tutorials on Bluetooth are pretty old! I just got Arduino-Android Bluetooth communication working last week so this should work for you! First in your manifest file add these permissions:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then use this in your main.
public class MainActivity extends AppCompatActivity {
private final String DEVICE_ADDRESS="benamekhoda"; //I actually used Device Name instead of address
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Serial Port Service UUID
private BluetoothDevice device; //Our Bluetooth Device
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
Button startButton, sendButton,clearButton,stopButton;
TextView textView;
EditText editText;
boolean deviceConnected=false;
Thread thread;
byte buffer[];
int bufferPosition;
boolean stopThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.edittext);
textView = (TextView) findViewById(R.id.textview);
startButton = (Button) findViewById(R.id.buttonStart);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(BTinit())
{
if(BTconnect())
{
setUiEnabled(true);
deviceConnected=true;
beginListenForData();
textView.append("\nConnection Opened!\n");
}
else{
Toast.makeText(getApplicationContext(),"BTconnect false",Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getApplicationContext(),"BTinit false",Toast.LENGTH_SHORT).show();
}
}
});
sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String string = editText.getText().toString();
string.concat("\n");
try {
outputStream.write(string.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
textView.append("\nSent Data:"+string+"\n");
}
});
clearButton = (Button) findViewById(R.id.buttonClear);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onClickClear(view);
}
});
stopButton = (Button) findViewById(R.id.buttonStop);
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onClickSend(view);
}
});
setUiEnabled(false);
}
public void setUiEnabled(boolean bool)
{
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public boolean BTinit()
{
boolean found=false;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices(); //Something like ArrayList but no duplicate is allowed and data is unordered
if(bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
}
else
{
for (BluetoothDevice iterator : bondedDevices)
{
if(iterator.getName().equals(DEVICE_ADDRESS))
{
device=iterator;
Toast.makeText(getApplicationContext(),"found the device",Toast.LENGTH_SHORT).show();
found=true;
break;
}
}
}
return found;
}
public boolean BTconnect()
{
boolean connected=true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw1",Toast.LENGTH_SHORT).show();
connected=false;
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw2",Toast.LENGTH_SHORT).show();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw3",Toast.LENGTH_SHORT).show();
}
}
return connected;
}
void beginListenForData()
{
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];
Thread thread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopThread)
{
try
{
int byteCount = inputStream.available();
if(byteCount > 0)
{
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
final String string=new String(rawBytes,"UTF-8");
handler.post(new Runnable() {
public void run()
{
textView.append(string);
}
});
}
}
catch (IOException ex)
{
stopThread = true;
Toast.makeText(getApplicationContext(),"throw4",Toast.LENGTH_SHORT).show();
}
}
}
});
thread.start();
}
public void onClickSend(View view) {
String string = editText.getText().toString();
string.concat("\n");
try {
outputStream.write(string.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
textView.append("\nSent Data:"+string+"\n");
}
public void onClickStop(View view) throws IOException {
stopThread = true;
outputStream.close();
inputStream.close();
socket.close();
setUiEnabled(false);
deviceConnected=false;
textView.append("\nConnection Closed!\n");
}
public void onClickClear(View view) {
textView.setText("");
}
}
I got it from this awesome tutorial by Hariharan Mathavan from All About Circuits.

How to read two BLE characteristics of two services at the same interface page?

I am trying to manage my temperature service and LED service of my BLE device at the same Android interface. However, whenever I try to turn the LED on, the app dies, and I don't know how to fix this (I am not good at either Java or BLE).
I have all of the UUIDs of the characteristics and services I need. I am trying to create two BluetoothGattCharacteristic
private BluetoothGattCharacteristic characteristic;
private BluetoothGattCharacteristic characteristicCTRL2;
It works fine when I call the temperature characteristic and get the temperature measurement. However, the app dies whenever I try to turn the LED on /call the LED characteristic.
10-30 08:48:33.026 1033-1033/com.example.android.bluetoothlegatt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.bluetoothlegatt, PID: 1033
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothGattCharacteristic.setValue(byte[])' on a null object reference
at com.example.android.bluetoothlegatt.AutoConnectActivity.turnLEDon(AutoConnectActivity.java:71)
at com.example.android.bluetoothlegatt.AutoConnectActivity$6.onClick(AutoConnectActivity.java:264)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19754)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5219)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The following code is how I transfer all characteristics & services together.
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
if ( gattCharacteristic.getUuid().equals(UUID.fromString(SampleGattAttributes.CTRL_2))){ //CTRL_2 is the UUID of my LED characteristic
Log.e(TAG, "GattCharacteristics= " + gattCharacteristic.getUuid());
Intent intent = new Intent(DeviceControlActivity.this, AutoConnectActivity.class);
intent.putExtra("character_id", "F000AA01-0451-4000-B000-000000000000"); //UUID of my temperature characteristic
intent.putExtra("service_id", "F000AA00-0451-4000-B000-000000000000");//UUID of my temperature service
intent.putExtra("address", mDeviceAddress);
intent.putExtra("ctrl2_character_id", gattCharacteristic.getUuid().toString()); //UUID of my LED characteristics
intent.putExtra("ctrl2_service_id", gattCharacteristic.getService().getUuid().toString());//UUID of my LED service
startActivity(intent);
}
The part I fail is the function that I try to turn LED on.
public boolean turnLEDon()
{
byte[] value = {(byte)1};
characteristicCTRL2.setValue(value);//This is the line I failed
boolean status = mBluetoothLeService.mBluetoothGatt.writeCharacteristic(characteristicCTRL2);
return status;
};
The following is my complete code of trying to manipulate two characteristics at the same interface.
package com.example.android.bluetoothlegatt;
public class AutoConnectActivity extends Activity {
private BluetoothGattCharacteristic characteristic;
private BluetoothGattCharacteristic characteristicCTRL2;
private String address;
private UUID serviceId;
private UUID charId;
private UUID ctrl2ServiceId;
private UUID ctrl2CharId;
private TextView debugText;
private Button startBtn;
private Button stopBtn;
private Button ctrlStartBtn;
private Button ctrlStopBtn;
private Timer timer = new Timer();
private boolean started = false;
private ArrayAdapter<String> adapter;
private String Entry;
private File file;
private boolean check= true;
private BluetoothLeService mBluetoothLeService;
public boolean turnLEDon()
{
byte[] value = {(byte)1};
characteristicCTRL2.setValue(value);//This is the line I failed
boolean status = mBluetoothLeService.mBluetoothGatt.writeCharacteristic(characteristicCTRL2);
return status;
};
public boolean turnLEDoff()
{
byte[] value = {(byte)0};
characteristicCTRL2.setValue(value);
boolean status = mBluetoothLeService.mBluetoothGatt.writeCharacteristic(characteristicCTRL2);
return !status;
};
private TimerTask timerTask = new TimerTask() {
#Override
public void run() {
mBluetoothLeService.connect(address);
}
};
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
mBluetoothLeService.connect(address);
List<BluetoothGattService> list = mBluetoothLeService.getSupportedGattServices();
for(BluetoothGattService s : list){
if(s.getUuid().compareTo(serviceId) == 0){
if (check==true) {
characteristic = s.getCharacteristic(charId);
mBluetoothLeService.disconnect();
}
return;
}
if(s.getUuid().compareTo(ctrl2ServiceId) == 0){
if(check==false) {
characteristicCTRL2 = s.getCharacteristic(ctrl2CharId);
}
return;
}
}
mBluetoothLeService.disconnect();
Log.e(TAG, "not find device");
debugText.setText("not find device");
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
debugText.setText(action);
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
// if temperature measurement
if (check==true){
mBluetoothLeService.readCharacteristic(characteristic);}
// if control LED
if(check==false){
mBluetoothLeService.readCharacteristic(characteristicCTRL2);
turnLEDon();
}
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action))
{
if (check==false) {
String CTRL_Status = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
adapter.add("CTRL Status: " + CTRL_Status + " " + new Date(System.currentTimeMillis()));
turnLEDoff();
mBluetoothLeService.disconnect();
}
if(check==true) {
String temperature = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
adapter.add("Temperature: " + temperature + "°C " + new Date(System.currentTimeMillis()));
Entry = address + "," + new Date(System.currentTimeMillis()).toString() + "," + temperature.toString() + "\n";
try {
FileOutputStream out = new FileOutputStream(file, true);
out.write(Entry.getBytes());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mBluetoothLeService.disconnect();
}
}
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autoconnect);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
address = intent.getStringExtra("address");
serviceId = UUID.fromString(intent.getStringExtra("service_id"));
charId = UUID.fromString(intent.getStringExtra("character_id"));
ctrl2ServiceId = UUID.fromString(intent.getStringExtra("ctrl2_service_id"));
Log.e(TAG, " CTRL2 SERVICE: " + ctrl2ServiceId);
ctrl2CharId = UUID.fromString(intent.getStringExtra("ctrl2_character_id"));
Log.e(TAG, " CTRL2 CHARAC: " + ctrl2CharId);
((TextView)findViewById(R.id.address_txt)).setText(address);
((TextView)findViewById(R.id.service_txt)).setText(serviceId.toString());
((TextView)findViewById(R.id.char_txt)).setText(charId.toString());
debugText = (TextView)findViewById(R.id.debug_txt);
startBtn = (Button)findViewById(R.id.start_btn);
stopBtn = (Button)findViewById(R.id.stop_btn);
ctrlStartBtn = (Button)findViewById(R.id.ctrl_start_btn);
ctrlStopBtn = (Button)findViewById(R.id.ctrl_stop_btn);
ListView listView = (ListView)findViewById(R.id.result_list);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(started) return;
started = true;
check=true;
//External Storage
String state;
state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File root = Environment.getExternalStorageDirectory();
File Dir = new File(root.getAbsolutePath() + "/MeasurementDataFile");
if (!Dir.exists()) {
Dir.mkdir();
}
file = new File(Dir, "Temperature.csv");
}
if (check==true){
timer.schedule(timerTask, 0, 1000 * 5); }
}
});
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!started) return;
started = false;
check=true;
timer.cancel();
}
});
ctrlStartBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mBluetoothLeService.connect(address);
check=false;
if(started) return;
started = true;
Toast.makeText (getBaseContext(), "Turn CTRL 1 ON", Toast.LENGTH_SHORT).show();
Log.e(TAG, " On?: " + turnLEDon());
}
});
ctrlStopBtn.setOnClickListener(new View.OnClickListener() {
//mBluetoothLeService.connect(address);
#Override
public void onClick(View v) {
if(!started) return;
started = false;
check=false;
Log.e(TAG, " Off?: " + turnLEDoff());
Toast.makeText (getBaseContext(), "Turn CTRL 1 OFF", Toast.LENGTH_SHORT).show();
}
});
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, DeviceControlActivity.makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(address);
Log.d(TAG, "Connect request result=" + result);
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
}
All BLE calls are asynchronous. This is really pain-in-neck, but we have what we have. So you cannot just write:
{
boolean status = writeCharacteristic(characteristic);
return status;
}
and hope all will be ok. In this case, you obtain a result of the writeCharacteristic instruction only, but not the real write operation result! For the last, you need to register the part of your code as BluetoothGattCallback descendant and read OnCharacteristicWrite event, where you can really know the result of your write operation.
All BLE read-write operations should be done in a strict one-by-one sequence and from main app thread only.
Different devices have different capabilities and productivity, so you can obtain different results - IMHO, this is less strange, than Google's decision to realize BLE stack in this manner :)
Pretty BLE guide for Android can be found here: https://droidcon.de/sites/global.droidcon.cod.newthinking.net/files/media/documents/practical_bluetooth_le_on_android_0.pdf
Edit
The link above is broken but the other one can be found here:
https://speakerdeck.com/erikhellman/practical-bluetooth-low-energy-on-android

App crashed due to looper.prepare() in the beginlistendata() function

public class BluetoothActivity extends Activity {
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Whenever a remote Bluetooth device is found
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
adapter.add(bluetoothDevice.getName() + "\n"
+ bluetoothDevice.getAddress());
}
}
};
//declaration
TextView myLabel;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
volatile boolean stopWorker;
private BluetoothAdapter mBluetoothAdapter;
private ListView listview;
private ArrayAdapter adapter;
private ToggleButton toggleButton;
private static final int REQUEST_ENABLE_BT =0;
private static final int DISCOVERABLE_DURATION = 0;
private static final int DISCOVERABLE_BT_REQUEST_CODE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_main);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
listview = (ListView) findViewById(R.id.listView);
// ListView Item Click Listener
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item value
String itemValue = (String) listview.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "clicked", Toast.LENGTH_LONG).show();
String MAC = itemValue.substring(itemValue.length() - 17);
BluetoothDevice bluetoothDevice = mBluetoothAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
});
adapter = new ArrayAdapter
(this,android.R.layout.simple_list_item_1);
listview.setAdapter(adapter);
//verify bluetooth is supported on the device
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Device does not support Bluetooth
if (mBluetoothAdapter == null) {
}
}//end oncreate
public void onToggle(View view) {
adapter.clear();
if (toggleButton.isChecked()){
//enable bluetooth
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(),"Already on", Toast.LENGTH_LONG).show();
//To discover remote Bluetooth devices
discoverDevices();
// Make local device discoverable by other devices
makeDiscoverable();
}
}//end of 1st if
else{
//turn off bluetooth
mBluetoothAdapter.disable();
adapter.clear();
Toast.makeText(getApplicationContext(),"Turned off" ,Toast.LENGTH_LONG).show();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
// Bluetooth successfully enabled!
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(getApplicationContext(), "Bluetooth is now enabled.",Toast.LENGTH_SHORT).show();
// Make local device discoverable by other devices
makeDiscoverable();
// To discover remote Bluetooth devices
Log.e("calldiscover", "func");
discoverDevices();
Log.e("Discover", "device");
// Start a thread to create a server socket to listen
// for connection request
Log.e("listenthread", "listenthread");
ListeningThread t = new ListeningThread();
Log.e("call", "t.start");
t.start();
Log.e("t.start", "over");
}
else {
// RESULT_CANCELED as user refused
Toast.makeText(getApplicationContext(), "Bluetooth is not enabled.",
Toast.LENGTH_SHORT).show();
// Turn off togglebutton
toggleButton.setChecked(false);
}
}//end of 1st if
}
protected void discoverDevices(){
// To scan for remote Bluetooth devices
if (mBluetoothAdapter.startDiscovery()) {Log.e("disc", "print");
Toast.makeText(getApplicationContext(), "Discovering other bluetooth devices...", Toast.LENGTH_SHORT).show();
}
else {
Log.e("print", "print");
Toast.makeText(getApplicationContext(), "Discovery failed to start.", Toast.LENGTH_SHORT).show();
}
}
protected void makeDiscoverable(){
// Make local device discoverable
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
}
#Override
protected void onResume() {
super.onResume();
// Register the BroadcastReceiver for ACTION_FOUND
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(broadcastReceiver, filter);
}
#Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(broadcastReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ListeningThread extends Thread {
private final BluetoothServerSocket bluetoothServerSocket;
public ListeningThread() {
BluetoothServerSocket temp = null;
try {
temp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(getString(R.string.app_name), uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothServerSocket = temp;
}
public void run() {
BluetoothSocket bluetoothSocket;
// This will block while listening until a BluetoothSocket is returned
// or an exception occurs
while (true) {
try {
Log.e("while", "over");
bluetoothSocket = bluetoothServerSocket.accept();
Log.e("bt", "accept");
} catch (IOException e) {Log.e("error", "catch");
break;
}
// If a connection is accepted
if (bluetoothSocket != null) {
Log.e("connection is accepted", "over");
BluetoothActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(BluetoothActivity.this, "Connected!", Toast.LENGTH_SHORT).show();
}
});
// Manage the connection in a separate thread
try {Log.e("callserver", "close");
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}//end of while
}
// Cancel the listening socket and terminate the thread
public void cancel() {
try {Log.e("cancel", "socket");
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Setting Up a Connecting Client
private class ConnectingThread extends Thread {
OutputStream mmOutputStream;
InputStream mmInputStream;
private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try { Log.e("click6", "click6");
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
Log.e("click7", "click7");
mBluetoothAdapter.cancelDiscovery();
Log.e("click8", "click8");
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
mmOutputStream = bluetoothSocket.getOutputStream();
mmInputStream = bluetoothSocket.getInputStream();
beginListenForData();
Log.e("listendata", "lsitendata");
BluetoothActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(BluetoothActivity.this, "Connected with Device!", Toast.LENGTH_SHORT).show();
}
});
Log.e("click9", "click9");
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
Log.e("click6", "blueclose");
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];//It uses a 1024 bytes long buffer because it doesn't have any way of knowing the length of the input stream.
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
myLabel.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
Hi the app crashed when I try to call beginListenForData(); The error state that Can't create handler inside thread that has not called Looper.prepare()
Does anyone know what wrong? I am new to android. Please help.
Bluetooth.xml below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".BluetoothActivity">
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Turn off Bluetooth"
android:textOff="Turn on Bluetooth"
android:id="#+id/toggleButton"
android:onClick="onToggle"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentStart="true"
android:layout_marginStart="76dp"
android:layout_below="#+id/toggleButton" />
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:"
android:layout_below="#+id/toggleButton"
android:layout_centerHorizontal="true"
android:layout_marginTop="66dp" />
</RelativeLayout>
Try this inside beginListenForData()
Replace
final Handler handler = new Handler();
With this
final Handler handler = new Handler(Looper.getMainLooper());

Android: Get Bluetooth working in other Activiy

i'm trying to connect (over a onclick method of a listview where all available bluetooth devices are listed) to a bluetooth device in my Class Bluetooth. That class starts the intentservice BluetoothService, where i create a BluetoothSocket and connect to the Device.
After the Connection works i would like to go to my MainActivity, while my Connection is on and there I want to send Bluetooth-Messages. But the BluetoothConnection always disconnects ...
BLUETOOTH.JAVA
public class Bluetooth extends ActionBarActivity {
ArrayList arrayList1;
ListView lv;
ArrayAdapter<String> arrayAdapter;
MainActivity ma = new MainActivity();
BroadcastReceiver mReceiver;
static final String TAG = "Bluetooth";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup);
Intent intent = getIntent();
arrayList1=intent.getStringArrayListExtra("values");
lv= (ListView) findViewById(R.id.listView);
getSurroundingDevicesandConnect();
}
#Override
protected void onStart(){
super.onStart();
}
public void getSurroundingDevicesandConnect() {
setContentView(R.layout.popup);
ma.bluetooth.startDiscovery();
if (ma.bluetooth.startDiscovery()) {
System.out.println("discovery started");
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
arrayAdapter.add(device.getName() + "\n" + device.getAddress());
System.out.println("while onreceive" + arrayList1);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.v(TAG, "Entered the Finished ");
ma.bluetooth.cancelDiscovery();
} else {
System.out.println("hoppala da funktioniert was nciht");
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
System.out.println("wurde registriert...");
}
setListView();
}
public void setListView() {
lv = (ListView) findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.select_dialog_item,
arrayList1
);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
String devicehelper = arrayList1.get(position).toString();
String[] device = devicehelper.split("\n");
String deviceName = device[0];
String deviceMAC = device[1];
//TODO: das hier muss in service..
Intent serviceIntent = new Intent();
serviceIntent.setAction("jritter.stamer.bluetoothtest.BluetoothService");
serviceIntent.putExtra("deviceMAC", deviceMAC);
BluetoothService bts = new BluetoothService();
bts.onHandleIntent(serviceIntent);
// boolean connected = connectWithDeviceNow(deviceMAC);
// if (connected) {
// System.out.println("Connected!");
// Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
// } else {
// System.out.println("Connection Failure");
// Toast.makeText(getApplicationContext(), "Connection Failure", Toast.LENGTH_LONG).show();
// }
// //onRestart();
// Toast.makeText(getApplicationContext(), "Mit Gerät " + deviceName + " verbunden", Toast.LENGTH_LONG);
}
});
lv.setAdapter(arrayAdapter);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bluetooth, menu);
return true;
}
public void onDestroy(){
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
BLUETOOTHSERVICE.JAVA
public class BluetoothService extends IntentService {
MainActivity ma = new MainActivity();
BluetoothSocket btSocket = null;
ConnectedThread mConnectedThread;
public BluetoothService() {
super("BluetoothService");
}
#Override
protected void onHandleIntent(Intent intent) {
String MAC = intent.getStringExtra("deviceMAC");
// create device and set the MAC address
BluetoothDevice device = ma.bluetooth.getRemoteDevice(MAC);//mydeviceaddress
System.out.println("devicename: " + device + device.getName());
ma.bluetooth.cancelDiscovery();
try {
btSocket = ma.createBluetoothSocket(device);
} catch (IOException e) {
System.out.println("socket creation failed");
}
// Establish the Bluetooth socket connection.
try {
btSocket.connect();
System.out.println("mit geraet verbunden");
} catch (IOException e) {
System.out.println("geraet nicht in eichweite");
try {
btSocket.close();
} catch (IOException e2) {
System.out.println("Socket closing doesnt work!");
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.setPriority(Thread.MAX_PRIORITY);
mConnectedThread.start();
}
}
MAINACTIVITY.JAVA
public class MainActivity extends ActionBarActivity {
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
static final boolean D = true;
static final int REQUEST_ENABLE_BT = 2;
static final String TAG = "Bluetooth";
// String for MAC address
static String mydeviceaddress;
// SPP UUID service - this should work for most devices
static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
VerticalSeekBar Master, Channel1, Channel2, Channel3, Channel4, Channel5, Channel6, FX1, FX2, FX3, FX4;
CheckBox MuteMaster, Mute1, Mute2, Mute3, Mute4, Mute5, Mute6;
Button connect;
TextView textView;
ArrayList arrayList;
Spinner effects;
List<String> spinnerArray = new ArrayList<String>(Arrays.asList("no effect", "Hall A", "Hall B"));
VerticalSeekBar vsb;
private static long back_pressed;
//BroadcastReceiver mReceiver;
Intent intent;
//BluetoothService btservice;
ConnectedThread mConnectedThread;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeVariables();
deviceSupportBluetooth();//?
turnBluetoothOn();
intent = getIntent();
}
#Override
public synchronized void onResume() {
super.onResume();
if (D) Log.e(TAG, "+ ON RESUME +");
effectsConfig(effects);
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something...
//connect bluetooth activity
sendMessage(v);
}
});
seekbarConfig(Master, "Master");
seekbarConfig(Channel1, "Channel1");
seekbarConfig(Channel2, "Channel2");
seekbarConfig(Channel3, "Channel3");
seekbarConfig(Channel4, "Channel4");
seekbarConfig(Channel5, "Channel5");
seekbarConfig(Channel6, "Channel6");
muteConfig(MuteMaster);
muteConfig(Mute1);
muteConfig(Mute2);
muteConfig(Mute3);
muteConfig(Mute4);
muteConfig(Mute5);
muteConfig(Mute6);
}
//TODO: MCONNECTEDTHREAD
public void sendMessage(View view) {
Intent intent = new Intent(this, Bluetooth.class);
intent.putExtra("values", arrayList);
startActivity(intent);
}
private void initializeVariables() {
Master = (VerticalSeekBar) findViewById(R.id.Seekbar);
Channel1 = (VerticalSeekBar) findViewById(R.id.Seekbar1);
Channel2 = (VerticalSeekBar) findViewById(R.id.seekbar2);
Channel3 = (VerticalSeekBar) findViewById(R.id.seekbar3);
Channel4 = (VerticalSeekBar) findViewById(R.id.seekbar4);
Channel5 = (VerticalSeekBar) findViewById(R.id.seekbar5);
Channel6 = (VerticalSeekBar) findViewById(R.id.seekbar6);
vsb = (VerticalSeekBar) findViewById(R.id.impulse2);
textView = (TextView) findViewById(R.id.textView);
MuteMaster = (CheckBox) findViewById(R.id.muteMaster);
Mute1 = (CheckBox) findViewById(R.id.mute1);
Mute2 = (CheckBox) findViewById(R.id.mute2);
Mute3 = (CheckBox) findViewById(R.id.mute3);
Mute4 = (CheckBox) findViewById(R.id.mute4);
Mute5 = (CheckBox) findViewById(R.id.mute5);
Mute6 = (CheckBox) findViewById(R.id.mute6);
connect = (Button) findViewById(R.id.connect);
effects = (Spinner) findViewById(R.id.spinner2);
arrayList = new ArrayList();
}
//android...
#Override
public void onStart() {
super.onStart();
if (D) Log.e(TAG, "++ ON START ++");
}
#Override
public void onDestroy() {
super.onDestroy();
if (D) Log.e(TAG, "++ ON DESTROY ++");
}
protected void onStop() {
Log.w(TAG, "App stopped");
super.onStop();
}
public void onBackPressed(){
onResume();
if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
#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 true;
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
}
// TODO GUI...
public void effectsConfig(Spinner spinner){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Spinners abc = new Spinners();
abc.setSpinner(spinner);
abc.setmConnectedThread(mConnectedThread);
spinner.setOnItemSelectedListener(abc);
}
public void muteConfig(CheckBox mute){
Checkboxes abc = new Checkboxes();
abc.setmConnectedThread(mConnectedThread);
mute.setOnClickListener(abc);
}
public void seekbarConfig(VerticalSeekBar seekBar, final String fadername) {
Seekbars abc = new Seekbars();
abc.setFadername(fadername);
abc.setmConnectedThread(mConnectedThread);
seekBar.setOnSeekBarChangeListener(abc);
}
// TODO Bluetooth handling...
public BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createInsecureRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
public void deviceSupportBluetooth() {
if (bluetooth == null) {
Toast.makeText(this, "Your Device does not support Bluetooth", Toast.LENGTH_LONG).show();
finish();
return;
}
}
public void turnBluetoothOn() {
if (!bluetooth.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the control session
}
}
}
CONNECTEDTHREAD.JAVA
class ConnectedThread extends Thread {
MainActivity ma = new MainActivity();
private final InputStream mmInStream;
private final OutputStream mmOutStream;
final int handlerState = 0; //used to identify handler message
Handler bluetoothIn;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(ma.getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
ma.finish();
}
}
}
You don't want to use IntentService for this. An IntentService shuts itself down when it has no more work to do. This means that as soon as you return from onHandleIntent() your service will shut down. Just extend Service and move the code you have in onHandleIntent() to onStartCommand(). Make sure that you return START_STICKY from onHandleIntent() and make sure that you have code that stops your Service when you are done with it.
The next problem is that in several classes you do this:
MainActivity ma = new MainActivity();
This is bad. You cannot instantiate Android components using new. Only the Android framework can instantiate Android components (Service, Activity, BroadcastReceiver, ContentProvider), because the framework needs to set up the correct Context. If you need to call methods in an Activity, you will either need to have a reference to the (Android created) Activity, or you need to make the methods static.
Your code is a mess :-( You should manage all the bluetooth stuff in your Service, not distribute the logic partly in the Service and partly in an Activity. Your classes are all interdependent. This is bad design and is causing you problems. You need to create a clear and clean interface between your Service and your Activity.
Look in your logcat to see what nasty exceptions are being thrown. That is most likely the cause of your "bluetooth disconnect"

Bluetooth device name pass to another activity. Connection not connected in another activity

Hi everyone..
I have used android Bluetooth chat application code in my application
I want pass a device name to another activity so i have saved my device name in public static variable when i select device name from list view same as android chat application.
After that i used this device name in another activity .With the help of this device name i Started BluetoothChatservice in second activity same as bluetooth chat standard code example.I didnt used this services in my mainactivity because I want connect device in my second activity
I have used Secure key only.But when i satarted this service sometimes connection connected with my another devices or sometimes not .
When i try for connection from both side connection connected.But first time it is not connect .I have used many things for service start like in onResume or ONStart or OnCreate but i am not success ed. MY english not good so please read carefully.
MY Main Activity Code=======
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private TextView mTitle;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private Button mSearch;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
public static BluetoothAdapter mBluetoothAdapter = null;
private LinearLayout mLin_getView;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
// Set up the custom title
mLin_getView=(LinearLayout) findViewById(R.id.mLin_addView);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#SuppressLint("NewApi")
#Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
//if (mChatService == null)
setupChat();
}
}
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
}
#SuppressLint("NewApi")
private void setupChat() {
Log.d(TAG, "setupChat()");
mSearch = (Button) findViewById(R.id.btn_search);
mSearch.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
initilizeFiled();
/*Intent serverIntent = new Intent(BluetoothChat.this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);*/
}
});
mOutStringBuffer = new StringBuffer("");
}
protected void initilizeFiled() {
// TODO Auto-generated method stub
Button scanButton = (Button) findViewById(R.id.button_scan);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#SuppressLint("NewApi")
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Log.d("Device Address", address);
connectDevice(address, true);
}
};
#SuppressLint("NewApi")
private void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
}
#Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
//if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
// The Handler that gets information back from the BluetoothChatService
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void connectDevice(String Address,boolean secure) {
// Get the device MAC address
String address = Address;
// Get the BLuetoothDevice object
// BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Const.deviceName=device;
Intent ib=new Intent(DashboardActivity.this,RemmoteActivity.class);
startActivity(ib);
}
}
Second Activity=========
private BluetoothAdapter mBluetoothAdapter = null;
private String mConnectedDeviceName = null;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
String TAG="Remmote";
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
ImageView Img_video, Img_camera, Img_song, Img_play, Img_forward,
Img_backward, Img_volume_up, Img_volume_down, Img_splash,
Img_capture, Img_zoom_in, Img_zoom_out;
private BluetoothChatService mChatService=null;
private StringBuffer mOutStringBuffer;
private BluetoothDevice device_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remote_screen);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mChatService=new BluetoothChatService(this,mHandler);
mOutStringBuffer=new StringBuffer("");
mOutStringBuffer=new StringBuffer("");
device_Name=Const.device;
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
initilizeField();
}
public void onStart() {
super.onStart();
Log.print(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), "Bluetooth Device Enabled", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth Device Enabled", Toast.LENGTH_SHORT).show();
}
}
#Override
public synchronized void onResume() {
super.onResume();
Log.print(TAG, "+ ON RESUME +");
mChatService.connect(device_Name, true);
}
#Override
public synchronized void onPause() {
super.onPause();
Log.print(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
Log.print(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null) mChatService.stop();
Log.print(TAG, "--- ON DESTROY ---");
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.mImg_camera:
sendMessage("Camera");
break;
case R.id.mImg_video:
break;
case R.id.mImg_songs:
break;
case R.id.Img_play:
break;
case R.id.Img_forward:
break;
case R.id.Img_backward:
break;
case R.id.Img_volume_up:
break;
default:
break;
}
}
public void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
// mOutEditText.setText(mOutStringBuffer);77
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Const.Camera:
com.example.utils.Log.print("your tab is here====="+1000);
//BluetoothChat.this.sendMessage("Camera");
break;
case MESSAGE_STATE_CHANGE:
Log.print(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "STATE_CONNECTED", Toast.LENGTH_SHORT).show();
break;
case BluetoothChatService.STATE_CONNECTING:
Toast.makeText(getApplicationContext(), "STATE_CONNECTING", Toast.LENGTH_SHORT).show();
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
Toast.makeText(getApplicationContext(), "STATE_NOT_LISTEN", Toast.LENGTH_SHORT).show();
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
Toast.makeText(getApplicationContext(), writeMessage, Toast.LENGTH_SHORT).show();
//mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Toast.makeText(getApplicationContext(), "Read", Toast.LENGTH_SHORT).show();
// captureImage();
// mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
In const Class for public static varible
public static BluetoothDevice device;
BluetoothChatService Code Same as android default program example

Categories

Resources