Receiving data from Bluetooth on Android - java

I have write some code for receiving data from Bluetooth module (HC-05), I want to read string '#900~' from Arduino, but I get nothing in response. I have made a connection with module, but nothing more. I need only reading on Android. It is probably easy task but I cannot get across :/. What am I doing wrong? it Below is my code:
package nichten.pneumobil;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainApplication extends AppCompatActivity {
boolean doubleBackToExitPressedOnce = false;
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
static BluetoothSocket mmSocket;
static BluetoothDevice mmDevice;
static OutputStream mmOutputStream;
static InputStream mmInputStream;
private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
private String BTdevice = "POJAZD1";
private boolean polaczenie = false;
Handler bluetoothIn;
final int handlerState = 0;
private ConnectedThread mConnectedThread;
private StringBuilder recDataString = new StringBuilder();
private Button btnModuleConnect;
private TextView txtModuleConnect;
private TextView txtTest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_application);
btnModuleConnect = (Button) findViewById(R.id.btnModuleConnect);
txtModuleConnect = (TextView) findViewById(R.id.txtModuleConnect);
txtTest = (TextView) findViewById(R.id.txtTest);
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
btnModuleConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (connectWithModule())
txtModuleConnect.setText("Connection status: Connected");
else
txtModuleConnect.setText("Connection status: Module not found");
} catch(IOException e){
e.printStackTrace();
}
}
});
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
recDataString.append(readMessage);
int endOfLineIndex = recDataString.indexOf("~");
if (endOfLineIndex > 0) {
String dataInPrint = recDataString.substring(0, endOfLineIndex);
int dataLength = dataInPrint.length();
if (recDataString.charAt(0) == '#')
{
txtTest.setText(recDataString);
}
recDataString.delete(0, recDataString.length());
dataInPrint = " ";
}
}
}
};
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
disconnectWithModule();
mBluetoothAdapter.disable();
finish();
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
public boolean connectWithModule() throws IOException {
if(polaczenie){
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
mmDevice = null;
mmSocket = null;
mBluetoothAdapter = null;
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if(device.getName().equals(BTdevice)){
mmDevice = device;
break;
}
}
}
if (mmDevice != null) {
try {
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
Toast.makeText(getApplicationContext(), "Połączono!", Toast.LENGTH_SHORT).show();
polaczenie = true;
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
return true;
} catch (Exception e2) {
Toast.makeText(getApplicationContext(),"Nie udało się połaczyć.", Toast.LENGTH_SHORT).show();
mmDevice = null;
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = null;
}
}
else if (mmDevice == null){
Toast.makeText(getApplicationContext(), "Nie ma sparowanych urządzeń.", Toast.LENGTH_SHORT).show();
polaczenie = false;
}
return false;
}
public void disconnectWithModule(){
if (polaczenie) {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class ConnectedThread extends Thread{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
I am a beginner in Android (only 2 days with it :P), but I have no idea what to do. I also include my AndroidManifest, my other Activity, maybe it would help to find out what is wrong:
package nichten.pneumobil;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
btnNextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent nextScreen = new Intent(getApplicationContext(), MainApplication.class);
startActivity(nextScreen);
}
});
}
}
And manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nichten.pneumobil">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainApplication"
android:screenOrientation="landscape">
</activity>
</application>
</manifest>

Related

Manage Bluetooth Communication

Im actually trying to interact with a bluetooth module controlled by a microcontroller PIC.
So i need to build an android app in order to send caracters by bluetooth.
But im kind of lost.
The beginning is quiet clear to me ( enabling bluetooth and connect as client)
But i dont know how to interact with my Bluetooth Service class from my MainActivity.
How to interact with write and read.
I can see that im successfully Connected to my device.
ALEA is the name of the BT module i want to connect to.
Thanks for your help
package com.example.stef.bluetoothencore;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ArrayList<String> NomBT=null;
BluetoothDevice mydevice;
int position_alea=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv=(ListView)findViewById(R.id.listdevice);
CheckBox Aleabox=(CheckBox) findViewById(R.id.checkAlea);
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
NomBT= new ArrayList<String>();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
BluetoothDevice mDevice = device;
arrayListBluetoothDevices.add(device); // On charge la liste de Device
NomBT.add(device.getName().toString());
if(device.getName().toString().equals("ALEA")){
mydevice=device;
Aleabox.setChecked(true);
Aleabox.setText(mydevice.getName().toString());
}
}
}
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, NomBT);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// position_alea=i;
//Toast.makeText(getApplicationContext(), mydevice.getName().toString(), Toast.LENGTH_SHORT).show();
ConnectThread mConnectThread = new ConnectThread(mydevice);
mConnectThread.start();
}
});
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
ConnectedThread mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
mConnectedThread.write("c".getBytes());
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;
while (true) {
try {
bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
for(int i = begin; i < bytes; i++) {
if(buffer[i] == "#".getBytes()[0]) {
mHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
begin = i + 1;
if(i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
break;
}
}
}
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int)msg.arg1;
int end = (int)msg.arg2;
switch(msg.what) {
case 1:
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
break;
}
}
};
}
Up, im still blocked, i am connected to my device but i can't read or write data ...

I can't send the data through Bluetooth

I wrote the application in Android Studio which has to send 1 on Arduino Pro Mini. Data is sent but doesn't reach Arduino. I checked Arduino through Bluetooth Terminal and everything was OK so the problem is in code. What is wrong?
package com.example.niko.motoco;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
BluetoothAdapter btAdapter = null ;
BluetoothDevice btDevice = null;
BluetoothSocket btSocket = null;
final String LOG_TAG = "myLogs";
Button btConnect, btSend;
public TextView checkText;
private static final int REQUEST_ENABLE_BT = 1;
private static final int CONNECTEDdevice = 2;
Boolean connection = false;
private static String MAC = null;
UUID my_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
private ConnectedThread MyThread = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
checkText = (TextView) findViewById(R.id.checkText);
btConnect = (Button)findViewById(R.id.btConnect);
btSend = (Button)findViewById(R.id.btSend);
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null) {
Toast.makeText(getApplicationContext(),"Device does not support Bluetooth",Toast.LENGTH_LONG).show();
} else if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
btConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (connection) {
// disconnect
try {
btSocket.close();
connection = false;
btConnect.setText("Connect");
Toast.makeText(getApplicationContext(),"Bluetooht is disconnected:",Toast.LENGTH_LONG).show();
} catch (IOException error) {
Toast.makeText(getApplicationContext(),"Error;" + error,Toast.LENGTH_LONG).show();
}
} else {
// connect
Intent ListDevices = new Intent(MainActivity.this, ListDevices.class);
startActivityForResult(ListDevices,CONNECTEDdevice);
}
}
});
btSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MyThread.write((byte) 1);
Toast.makeText(getApplicationContext(),"Sending 1",Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_ENABLE_BT:
if(resultCode == Activity.RESULT_OK) {
Toast.makeText(getApplicationContext(),"bluetooth is activated",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"bluetooth is not activated",Toast.LENGTH_LONG).show();
finish();
}
break;
case CONNECTEDdevice :
if (resultCode == Activity.RESULT_OK) {
MAC = data.getExtras().getString(ListDevices.MACaddress);
btDevice = btAdapter.getRemoteDevice(MAC);
try {
btSocket = btDevice.createRfcommSocketToServiceRecord(my_UUID);
btSocket.connect();
connection = true;
btConnect.setText("Disconnect");
Toast.makeText(getApplicationContext(),"MAC of connected device:" + MAC,Toast.LENGTH_LONG).show();
MyThread = new ConnectedThread(btSocket);
//MyThread.start();
} catch (IOException error) {
connection = false;
Toast.makeText(getApplicationContext(),"Error:" + error,Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(getApplicationContext(),"didn't get MAC",Toast.LENGTH_LONG).show();
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket btSocket2;
private final OutputStream OutStream;
public ConnectedThread(BluetoothSocket socket) {
btSocket2 = socket;
OutputStream tmpOut = null;
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
OutStream = tmpOut;
}
public void write(byte bytes) {
try {
OutStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
btSocket2.close();
} catch (IOException e) { }
}
}
}
What's wrong ? At least those 2 pieces of code are wrong :
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
And later:
try {
OutStream.write(bytes);
} catch (IOException e) { }
When something goes wrong you catch the exception silently and loose all chances to identify the root cause.
Change the code to something like this :
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.(TAG, "Fail to get socket output stream" ,e);
}
And later :
try {
OutStream.write(bytes);
} catch (IOException e) {
Log.(TAG, "Fail to write on socket output stream" ,e);
}
Then re-run your code and look at the logcat. You will probably see the cause of your problems.

What can I do by getBluetoothService() called with no BluetoothManagerCallback ?

hi I want to write a Android java application that can connect with a bluetooth device but I get the error:
W/BluetoothAdapter﹕ getBluetoothService() called with no BluetoothManagerCallback
I use a Nexus 5 device with android version 4.4.4
here is my code:
package com.example.tarasov.bluetoothexample;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MyActivity extends Activity implements OnItemClickListener {
/*
* Deklaration
* */
ArrayAdapter<String> listAdapter;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> deviceArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "debugging";
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.i(tag, "in handler");
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
// DO something
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
init(); //Initialisierung der Komponenten
if(btAdapter==null)
{
Toast.makeText(getApplicationContext(), "Kein Bluetooth aktiviert", Toast.LENGTH_SHORT).show();
finish();
}
else
{
if (!btAdapter.isEnabled()){
turnOnBT();
}
getPairedDevices();
startDiscovery();
}
}
private void startDiscovery() {
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void turnOnBT() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent,1);
}
private void getPairedDevices() {
deviceArray = btAdapter.getBondedDevices();
if (deviceArray.size()>0){
for (BluetoothDevice device:deviceArray){
pairedDevices.add(device.getName());
}
}
}
private void init(){
listView = (ListView)findViewById(R.id.listView); //bindet ListView
listView.setOnItemClickListener(this);
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devices = new ArrayList<BluetoothDevice>();
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String s = "";
for (int a=0;a< pairedDevices.size();a++){
if (device.getName().equals(pairedDevices.get(a))){
s = "(Verbunden)";
break;
}
}
listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
}
else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}
else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if (btAdapter.getState()==btAdapter.STATE_OFF){
turnOnBT();
}
}
}
};
registerReceiver(receiver,filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver,filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver,filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver,filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth muss erst aktiviert werden", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if (listAdapter.getItem(arg2).contains("Verbunden")){
BluetoothDevice selectedDevice = devices.get(arg2);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
Log.i(tag, "in click listener");
}
else
{
Toast.makeText(getApplicationContext(), "Gerät ist nicht verbunden", Toast.LENGTH_SHORT).show();
}
}
/*
* Hilfsklassen
* */
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
Log.i(tag, "construct");
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.i(tag, "get socket failed");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
btAdapter.cancelDiscovery();
Log.i(tag, "connect - run");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(tag, "connect - succeeded");
} catch (IOException connectException) { Log.i(tag, "connect failed");
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}

Receive a string via RFCOMM in android

I am trying to recieve a string via RFCOMM in android
I am a newbie to android and please help me
I can send data
but receiving fails
Here is my code
Please help me
package com.example.btspp;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Scanner;
import java.util.UUID;
import java.util.regex.Pattern;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Buttons extends Activity {
private BluetoothAdapter btAdaptor;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private InputStream inStream = null;
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
public String addressToConnect;
public static StringBuilder readStr;
TextView tv;
int aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buttons);
tv = (TextView) findViewById(R.id.textView1);
addressToConnect = getIntent().getStringExtra("addressToConnect");
connectToDevice(addressToConnect);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
sendData("H");
// Toast.makeText(getBaseContext(), addressToConnect,
// Toast.LENGTH_SHORT).show();
}
});
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
try {
// final BT bt = new BT();
outStream.write(msgBuffer);
//readData();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(),
"Not Sent BT Data : " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}
/*private void readData(){
String instring = "";
try {
inStream = btSocket.getInputStream();
} catch (Exception e) {
// TODO: handle exception
}
Scanner scan = new Scanner(new InputStreamReader(inStream));
scan.useDelimiter(Pattern.compile("[\\r\\n]+"));
instring = scan.next();
scan = null;
Toast.makeText(getApplicationContext(),
"Got Data : " + instring, Toast.LENGTH_SHORT)
.show();
//return instring;
}*/
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];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = inStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
inStream.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()
{
tv.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
private void connectToDevice(String address) {
btAdaptor = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdaptor.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
outStream = btSocket.getOutputStream();
inStream = btSocket.getInputStream();
beginListenForData();
tv.setText("Bluetooth Opened");
//listenForMessages(btSocket, readStr);
// beginListenForData();
} catch (IOException e) {
// errorExit("Fatal Error",
// "In onResume() and socket create failed: " + e.getMessage() +
// ".");
Toast.makeText(getApplicationContext(),
"Not Connected : " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_buttons, menu);
return true;
}
}
I am a newbie to android and please help me
I can send data
but receiving fails
Here is my code
Please help me
Isn't 13 "\r" the usual delimiter and not 10?

Error Message "Bluetooth is not available." Honestly unsure of the cause

I get the error "Bluetooth is not available when running my latest app from either eclipse or the device itself. The device(s) in question are two Galaxy Nexus Phones (Both CDMA/LTE) with bluetooth enabled. One is running AOKP with Android 4.2.1, the other is stock, with Android 4.1.1.
I had believed that my unique solution to others problems with bluetooth which required a hardcoded mac address to possibly be the issue as these devices have no external storage, but rather mount internal storage to /mnt/sdcard. However, I tried hardcoding the mac address instead of reading it from a file, to no avail. The first link is my MainActivity, the second link is my Manifest.xml (I have proper persmissions for bluetooth and for storage (r/w). I will enclose logcat in a third link.
Main Activity:
package com.hyperspacecg.thermolitics;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final String PREFS_NAME = "ThermolyticsPrefsFile";
String Packet = null;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
SeekBar seekbarTemp, seekbarBlower;
TextView valueTemp, valueBlower;
RadioGroup ventilation;
private static int Blower = 0;
private static int Vent = 255;
private static int Temp = 0;
private static int Defrost = 0;
private static int AC = 0;
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
// hardcoded MAC address
private static String address = null;
private BufferedReader buf;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
valueTemp = (TextView) findViewById(R.id.textViewTemp);
seekbarTemp = (SeekBar) findViewById(R.id.seekBarTemp);
valueBlower = (TextView) findViewById(R.id.textViewBlower);
seekbarBlower = (SeekBar) findViewById(R.id.seekBarBlower);
ventilation = (RadioGroup) findViewById(R.id.radioGroup1);
BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available.",
Toast.LENGTH_LONG).show();
finish();
return;
}
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(this,
"Please enable your BT and re-run this program.",
Toast.LENGTH_LONG).show();
finish();
return;
}
int sbar_blower_position = settings.getInt("seekbar_blower_pref", 0);
seekbarBlower.setProgress(sbar_blower_position);
valueBlower.setText("Blower Power: " + sbar_blower_position);
Blower = sbar_blower_position;
int sbar_temp_position = settings.getInt("seekbar_temp_pref", 0);
seekbarTemp.setProgress(sbar_temp_position);
valueTemp.setText("Temperature: " + sbar_temp_position);
Temp = sbar_temp_position;
Vent = ventilation.indexOfChild(findViewById(ventilation.getCheckedRadioButtonId()));
seekbarBlower.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
valueBlower.setText("Blower Power: " + progress);
Blower = progress;
packet(Blower, Temp, Vent, AC, Defrost);
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
seekbarTemp.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
valueTemp.setText("Temperature:" + progress);
Temp = progress;
packet(Blower, Temp, Vent, AC, Defrost);
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
try{
File f = new File(Environment.getExternalStorageDirectory()+"/therm.txt");
FileInputStream fileIS = new FileInputStream(f);
buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
address = readString;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
// When this returns, it will 'know' about the server,
// via it's MAC address.
address = "00:16:68:2B:40:90";
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
mBluetoothAdapter.cancelDiscovery();
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
}
}
// Create a data stream so we can talk to server.
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
}
packet(Blower, Temp, Vent, AC, Defrost);
byte[] msgBuffer = Packet.getBytes();
try {
outStream.write(msgBuffer);
Toast.makeText(this, "BT successfully connected.",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
}
}
public void onClickDefrost(View v) throws IOException
{
if(Defrost == 1)
{
Defrost = 0;
}
else
{
Defrost = 1;
}
packet(Blower, Temp, Vent, AC, Defrost);
byte[] msgBuffer = Packet.getBytes();
try
{
outStream.write(msgBuffer);
}
catch (IOException e)
{
}
}
public void onClickAC(View v) throws IOException
{
if(AC == 1)
{
AC = 0;
}
else
{
AC = 1;
}
packet(Blower, Temp, Vent, AC, Defrost);
byte[] msgBuffer = Packet.getBytes();
try
{
outStream.write(msgBuffer);
}
catch (IOException e)
{
}
}
#Override
public void onPause() {
super.onPause();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("seekbar_blower_pref", Blower);
editor.putInt("seekbar_temp_pref", Temp);
editor.commit();
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
}
}
try {
btSocket.close();
} catch (IOException e2) {
}
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
}
public String packet(int Blower, int Temp, int Vent, int AC,int Defrost) {
Blower = Blower * 4;
Temp = Temp * 4;
Packet = "<HMG:" + Blower + ":" + Temp + ":" + Vent + ":" + AC + ":" + Defrost + ">";
return Packet;
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hyperspacecg.thermolitics"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.hyperspacecg.thermolitics.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat:
02-27 21:59:54.572: D/dalvikvm(8472): Late-enabling CheckJNI
02-27 21:59:54.689: E/Trace(8472): error opening trace file: No such file or directory (2)
02-27 21:59:55.041: D/dalvikvm(8472): GC_CONCURRENT freed 81K, 10% free 2696K/2964K, paused 2ms+6ms, total 115ms
02-27 21:59:55.236: D/dalvikvm(8472): GC_CONCURRENT freed 18K, 7% free 3078K/3308K, paused 12ms+12ms, total 69ms

Categories

Resources