how to write 8 bit using outStream.write(msgBuffer); - android

outStream.write(msgBuffer);
It writes only first bit. how to write 8 bit out of it.If we are sending 00000001 means it writes only 0. But we want to write whole 8 bit how to achieve it.
public class MainActivity extends ActionBarActivity {
private ToggleButton power, simulation, reset, pause, replay, diagnose,
abs, emergency;
private static final String TAG = "bluetooth1";
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:12:02:28:75:34";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
power = (ToggleButton) findViewById(R.id.toggleButton1);
simulation = (ToggleButton) findViewById(R.id.simulation_tb);
reset = (ToggleButton) findViewById(R.id.reset_bt);
pause = (ToggleButton) findViewById(R.id.pause_bt);
replay = (ToggleButton) findViewById(R.id.replay_bt);
diagnose = (ToggleButton) findViewById(R.id.diagnose_bt);
abs = (ToggleButton) findViewById(R.id.abs_bt);
emergency = (ToggleButton) findViewById(R.id.emergency_bt);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
power.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (power.isChecked()) {
String str = "1";
int i = Integer.parseInt(str);
String binarystr = Integer.toBinaryString(i);
char[] buffer = new char[binarystr.length()];
binarystr.getChars(0, binarystr.length(), buffer, 0);
System.out.println("char array:: "
+ Arrays.toString(buffer));
byte[] binaryFormat = getbyteFromString(buffer);
for (byte b : binaryFormat) {
sendData(Integer.toBinaryString(b & 255 | 256)
.substring(1));
}
Toast.makeText(getApplicationContext(), "LED ON",
Toast.LENGTH_LONG).show();
} else {
sendData("0");
Toast.makeText(getApplicationContext(), "LED OFF",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.const_closeApp))
.setPositiveButton(getString(R.string.const_yes),
dialogClickListener)
.setNegativeButton(getString(R.string.const_no),
dialogClickListener).show();
}
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(new
// BTStateChangedBroadcastReceiver());
System.exit(0);
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
break;
}
}
};
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned
// on
// Emulator doesn't support Bluetooth and will return null
if (btAdapter == null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException {
if (Build.VERSION.SDK_INT >= 10) {
try {
final Method m = device.getClass().getMethod(
"createInsecureRfcommSocketToServiceRecord",
new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#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;
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
Log.d(TAG, "...This is the value byte: " + msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString()
+ " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
private void errorExit(String title, String message) {
Toast.makeText(getBaseContext(), title + " - " + message,
Toast.LENGTH_LONG).show();
finish();
}
#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);
}
public static byte[] getbyteFromString(char[] binarystr) {
int length = binarystr.length / 8;
if (binarystr.length % 8 > 0)
length++;
int iterationCount = length;
byte[] binaryFormat = new byte[iterationCount];
int iter = iterationCount - 1;
for (int i = binarystr.length - 1; i >= 0;) {
byte byt = 0x0;
for (int j = 0; j < 8; j++) {
if (i < 0)
break;
int b = binarystr[i] - 48;
byt = (byte) (byt + (b << j));
i--;
}
binaryFormat[iter] = byt;
iter--;
}
return binaryFormat;
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: "
+ e1.getMessage() + ".");
}
/*
* try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); }
* catch (IOException e) { errorExit("Fatal Error",
* "In onResume() and socket create failed: " + e.getMessage() + "."); }
*/
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error",
"In onResume() and unable to close socket during connection failure"
+ e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit(
"Fatal Error",
"In onResume() and output stream creation failed:"
+ e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit(
"Fatal Error",
"In onPause() and failed to flush output stream: "
+ e.getMessage() + ".");
} catch (NullPointerException e) {
e.printStackTrace();
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket."
+ e2.getMessage() + ".");
}
}
}

It looks like your code is not complete. Anyway, I suggest to use the DataInputStream / DataOutputStream of Android. Just wrap your streams into them. They provide methods for writing any kind of primitive datatype up to String with arbitrary encoding. All you need to do is use the writeString(...) method and use the read String method on the other side. This way you don't need to convert the String in order to write it into you stream and you don't need to care about how to reconstruct it from the stream.
If you only want to write Strings you can use the BufferedWriter which allows you to only write Strings to an stream, you can use it like this to stick it onto a 'OutputStream'
OutputStreamWriter osw = new OutputStreamWriter(outStream);
BufferedWriter writer = new BufferedWriter(osw);

Related

After a while from running perfectly, the app crash

So I was working on an arduino project that send char via bluetooth to my app. The app receive the data. If the char is "1" it plays a voice clip called "the"
else if its "2" plays voice clip called "its_me".
The app run just fine for a while like for 2 or 3 min and then it crashes. This is the logcat:
en02-05 21:12:56.060 7715-7715/bluetooth.arduino.ndroid.bluetooth3 E/AndroidRuntime: FATAL EXCEPTION: main
Process: bluetooth.arduino.ndroid.bluetooth3, PID: 7715
android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.Resources.getValue(Resources.java:1551)
at android.content.res.Resources.openRawResourceFd(Resources.java:1503)
at android.media.MediaPlayer.create(MediaPlayer.java:947)
at android.media.MediaPlayer.create(MediaPlayer.java:930)
at bluetooth.arduino.ndroid.bluetooth3.MainActivity.malek(MainActivity.java:223)
at bluetooth.arduino.ndroid.bluetooth3.MainActivity$2.handleMessage(MainActivity.java:74)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5763)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
and this is the java code:
public class MainActivity extends AppCompatActivity {
private MediaPlayer TheSound;
private static final String TAG = "bluetooth2";
TextView txtArduino;
Handler h;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "98:D3:31:F9:4C:52";
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer TheSound) {
releaseMediaPlayer();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtArduino = (TextView) findViewById(R.id.txtArduino); // for display the received data from the Arduino
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
Toast.makeText(getBaseContext(), "the connection has set up ", Toast.LENGTH_LONG).show();
malek(sbprint);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
}
;
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if (Build.VERSION.SDK_INT >= 10) {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[]{UUID.class});
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if (btAdapter == null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message) {
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket 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 = new byte[256]; // 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
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
}
// determent the voice clip and update TextView
public void malek (String sbprint){
releaseMediaPlayer();
TheSound = MediaPlayer.create(this,mmalek(sbprint));
TheSound.start();
// I created a global var for when TheSound is finished , releas the resources
TheSound.setOnCompletionListener(mCompletionListener);
}
// determent which voice clip to play
public int mmalek (String theX ){
txtArduino.setText(theX); // update TextView
if(theX.equals("1")){
Toast.makeText(getBaseContext(), " hello", Toast.LENGTH_LONG).show();
return R.raw.the;}
if(theX.equals("2")){
Toast.makeText(getBaseContext(), " it's me", Toast.LENGTH_LONG).show();
return R.raw.its_me;
}
return 0;}
/**
* Clean up the media player by releasing its resources.
*/
private void releaseMediaPlayer() {
// If the media player is not null, then it may be currently playing a sound.
if (TheSound != null) {
// Regardless of the current state of the media player, release its resources
// because we no longer need it.
TheSound.release();
// Set the media player back to null. For our code, we've decided that
// setting the media player to null is an easy way to tell that the media player
// is not configured to play an audio file at the moment.
TheSound = null;
}
}
}

Retain Bluetooth Connection till the app is Closed

I made an app which connects to bluetooth and sends and receive data in an activity. Now I have updates in the app and has to create another activities which connects to the same bluetooth device and transfer data. So I am planning to connect to bluetooth device in my second activity which has some buttons which calls for another activities. I need to retain the bluetooth connection I made in the second activity throughout the activities that are called from the second activity using buttons till the user press back button from second activity (exiting second activity). Please explain how I should change my code to make this happen. This is my current code which is used for single activity bluetooth connection.
public class ViewBoardStatus extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_board_status);
mOutStringBuffer = new StringBuffer("");
IntentFilter filter = new IntentFilter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
List<String> paireddevicesarray = new ArrayList<>();
int iNoOfPariedDev = pairedDevices.size();
int iDeviceCntr = 0;
DevAddressString = new String[iNoOfPariedDev][2];
for (BluetoothDevice device : pairedDevices)
{
DevAddressString[iDeviceCntr][0] = device.getAddress();
DevAddressString[iDeviceCntr][1] = device.getName();
iDeviceCntr++;
if (iDeviceCntr > iNoOfPariedDev)
break;
}
ArrayList<String> aList = new ArrayList<String>();
aList.add("Select Device");
for (int i = 0; i < iDeviceCntr; i++)
{
aList.add(DevAddressString[i][1]);
}
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, aList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_paireddevices.setAdapter(dataAdapter);
sp_paireddevices.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
// Object item = parentView.getItemAtPosition(position);
Log.e(TAG, "Executing On ITEM SELECTED");
int iLoc = sp_paireddevices.getSelectedItemPosition();
if (iLoc != 0)
{
Toast.makeText(getApplicationContext(), " Connecting to hardware please wait..", Toast.LENGTH_SHORT).show();
iBTDevSelcted = 1;
Log.e(TAG, "Toast message of Connecting");
address = DevAddressString[iLoc - 1][0];
Log.e(TAG, "Calling OnResume Function");
onResume();
}
else
{
Toast.makeText(getApplicationContext(), " Please select Bluetooth Device", Toast.LENGTH_SHORT).show();
}
}
public void onNothingSelected(AdapterView<?> arg0) {// do nothing
}
});
lvParaHeader.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(touchSource == null)
touchSource = v;
if(v == touchSource)
{
lvParaValue.dispatchTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP)
{
clickSource = v;
touchSource = null;
}
}
return false;
}
});
lvParaValue.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(touchSource == null)
touchSource = v;
if(v == touchSource)
{
lvParaHeader.dispatchTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP)
{
clickSource = v;
touchSource = null;
}
}
return false;
}
});
lvParaHeader.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(parent == clickSource) {
// Do something with the ListView was clicked
}
}
});
lvParaValue.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(parent == clickSource) {
// Do something with the ListView was clicked
}
}
});
lvParaHeader.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(view == clickSource)
lvParaValue.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
lvParaValue.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(view == clickSource)
lvParaHeader.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
sp_datatype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Log.e(l,"Starting ON Item Selected");
if (sp_paireddevices.getSelectedItemPosition()>0)
{
if (sp_datatype.getSelectedItemPosition() == 1) {
sGetRequest = sGetElectricalPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 2) {
sGetRequest = sGetGprsPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 3) {
sGetRequest = sGetSystemPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 4) {
sGetRequest = sGetRS485Para;
sendMessage(sGetRequest);
}
}
else
Toast.makeText(getApplicationContext(), " Connect to a Device and Refresh ", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
bt_Refresh.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.e(l,"Refresh Button OnClick");
if (sp_paireddevices.getSelectedItemPosition()>0)
{
if (sp_datatype.getSelectedItemPosition() == 0) {
Toast.makeText(getApplicationContext(), " Select a Parameter to Refresh ", Toast.LENGTH_SHORT).show();
}
if (sp_datatype.getSelectedItemPosition() == 1) {
sGetRequest = sGetElectricalPara;
sendMessage(sGetRequest);
Log.e(l, "Send Message Called");
}
if (sp_datatype.getSelectedItemPosition() == 2) {
sGetRequest = sGetGprsPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 3) {
sGetRequest = sGetSystemPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 4) {
sGetRequest = sGetRS485Para;
sendMessage(sGetRequest);
}
Log.e(l, "Send Message Called");
}
else
Toast.makeText(getApplicationContext(), " Connect to a Device and Refresh ", Toast.LENGTH_SHORT).show();
}
});
h = new Handler()
{
public void handleMessage(android.os.Message msg)
{
Log.e(l, "Starting Handler");
int strlen;
switch (msg.what)
{
case RECIEVE_MESSAGE:
Log.d(l, "data received = " );
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
String strMsg = new String();
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("#");
if (endOfLineIndex > 0)
{ // if end-of-line,
sJsonData = sb.substring(1, endOfLineIndex); // extract string
sb.delete(0, sb.length());
// and clear
try
{
Log.e(l, "Starting Try of Handler");
Log.e(l, "Data Received: "+sJsonData);
strlen = sJsonData.length();
Log.e(l, "String Length Obtained");
JSONObject mainobject = new JSONObject(sJsonData);
Log.e(l, "main object created");
sDataType = mainobject.getString("DATA_TYPE");
Log.e(l, "Data Type Obtained");
//tv_jsonlength.setText(String.valueOf(strlen));
//tv_JsonPara.setText(TempHeader);
iSelectedParaPostion=sp_datatype.getSelectedItemPosition();
if(sDataType.trim().equalsIgnoreCase("PARA"))
{
if(iSelectedParaPostion==1)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//tv_jsonstring.setText(sCurrentJsonData);
jsonparseelectricalpara();
}
}
if(sDataType.trim().equalsIgnoreCase("GPRS"))
{
if(iSelectedParaPostion==2)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//tv_jsonstring.setText(sCurrentJsonData);
jsonparsegprsdata();
}
}
if(sDataType.trim().equalsIgnoreCase("SYSTEM"))
{
if(iSelectedParaPostion==3)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//
// tv_jsonstring.setText(sCurrentJsonData);
jsonparseSystem();
}
}
}
catch (Exception e)
{
Log.e(l, "CATCH OF HANDLER");
}
}
break;
}
}
};
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}//oncreate
private void checkBTState()
{
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(mBluetoothAdapter==null) {
// Log.d(TAG, "error, bluetooth not supported");
} else {
if (mBluetoothAdapter.isEnabled()) {
// Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
tvconnectionstatus.setText("");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message)
{
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
{
if (Build.VERSION.SDK_INT >= 10)
{
try
{
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[]{UUID.class});
Log.e(TAG, "Bluetooth Socket Creation TRY EXECUTED");
return (BluetoothSocket) m.invoke(device, MY_UUID);
}
catch (Exception e2)
{
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
Log.e(TAG, "Bluetooth Socket Creation CATCH EXECUTED");
}
}
Log.e(TAG, "Exiting Socket Creation Method");
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
public void onResume()
{
super.onResume();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Log.e(TAG, "Starting OnResume Method");
if (iBTDevSelcted == 0) {
Toast.makeText(getApplicationContext(), " Please select Bluetooth Device", Toast.LENGTH_SHORT).show();
return;
}
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.e(TAG, "Obtaining REMOTE DEVICE address");
try {
btSocket = createBluetoothSocket(device);
Log.e(TAG, "BT SOCKET Created");
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
mBluetoothAdapter.cancelDiscovery();
Log.e(TAG, "BT Discovery CANCELLED");
try
{
Log.e(TAG, "TRY STATEMENT OF BT CONNECTION CREATION");
btSocket.connect();
String connectedto = "Connected to: " + sp_paireddevices.getSelectedItem().toString();
tvconnectionstatus.setText(connectedto);
}
catch (IOException e)
{
Log.e(TAG, "CATCH STATEMENT OF BLUETOOTH CONNECTION CREATION");
try {
btSocket.close();
Log.e(TAG, "Bluetooth Socket Closed");
tvconnectionstatus.setText("");
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
Log.e(TAG, "Unable to Close bluetooth connection");
}
}
// Create a data stream so we can talk to server.
// Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
Log.e(TAG, "Connection Thread Created");
mConnectedThread.start();
Log.e(TAG, "Connection Thread Started");
}
#Override
public void onPause()
{
super.onPause();
// Log.d(TAG, "...In onPause()...");
if(iBTDevSelcted==1) {
try {
btSocket.close();
tvconnectionstatus.setText("");
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
}
private class ConnectedThread extends Thread
{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket)
{
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try
{
Log.e(TAG, "Trying to get Temp Input/Output Stream");
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
Log.e(TAG, "Input/Output Stream Obtained");
}
catch (IOException e)
{
Log.e(TAG, "I/O Stream CATCH STATEMENT");
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run()
{
Log.e(TAG, "Starting RUN Method");
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true)
{
try {
Log.e(TAG, "TRY of RUN Method Started");
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
Log.e(l,"Run Executed");
Log.e(TAG, "TRY of RUN Method Completed");
} catch (IOException e)
{
Log.e(TAG, "CATCH of RUN Method");
break;
}
}
}
public void write(String s) throws IOException
{
mmOutStream.write(s.getBytes());
tvconnectionstatus.setText(s);
sGetRequest=sReset;
}
}//connectthread
private void sendMessage(String message)
{
ConnectedThread ct;
Log.e(l,"Connected Thread Object Created");
ct = mConnectedThread;
try {
ct.write(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}//class

Bluetooth app doesn't work

I found source for bluetooth between Android and Arduino
and I copied and pasted it.
It doesn't show any error in code.
When I try to run this, it truns off with message
"Fatal Error - In onResume() and an exception occureed during write :
socket closde. Check that the SPP
UUID:00001101-0000-1000-8000-00805f9b34fb exists on server"
What is the problem and what should I do?
Here is source code:
public class MainActivity extends Activity {
private static final String TAG = "bluetooth1";
Button btnOn, btnOff;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:15:FF:F2:19:5F";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
btnOn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendData("1");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendData("0");
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createRFCommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}
This is a bad code, you should not use it - there is a great sample from Google - BluetoothChatService: https://github.com/googlesamples/android-BluetoothChat . See BluuetoothChatService class. Unfortunately, there is problem with it- it uses Handler for communicating with the rest of a app. I change it a bit so it posts messages to another HandlerThread and that thread notifies custom interface set by user (for my Arduino project), for more details see this project: https://github.com/AlexShutov/LEDLights

Socket closed error after one command in bluetooth and voice recognition application

I am developing an application that can connect to a bluetooth module (HC06 in my case). in this app i want to send a command to light up 2 leds on my MSP430 board. I managed to connect to the bluetooth module and say a command ("on" for example). after one command the app has errors and exits.
Note: if i say "on" i want to sent the letter "A", "off" letter "B" and so on.
I seem to have a problem with the socket closing, and that is why i cannot say a second command.
Here is my code:
public class VoiceRecognitionDemo extends Activity
{
private static final int REQUEST_CODE = 1234;
private static final String TAG = "SuperAPPLICATIE";
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your bluetooth devices MAC address
private static final String address = "98:D3:31:30:3C:A5";
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.voice_recog);
Button speakButton = (Button) findViewById(R.id.speakButton);
//wordsList = (ListView) findViewById(R.id.list);
// Disable button if no recognition service is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (activities.size() == 0)
{
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
}
/**
* Handle the action of the button being clicked
*/
public void speakButtonClicked(View v)
{
startVoiceRecognitionActivity();
}
/**
* Fire an intent to start the voice recognition activity.
*/
private void startVoiceRecognitionActivity()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");
startActivityForResult(intent, REQUEST_CODE);
}
public void onResume() {
super.onResume();
Log.d(TAG, "...In onResume - Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting to Remote...");
try {
btSocket.connect();
Log.d(TAG, "...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Creating Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
/**
* Handle the results from the voice recognition activity.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
{
// Populate the wordsList with the String values the recognition engine thought it heard
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
//wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
// matches));
String resulttext = matches.get(0);
// wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
// Integer.parseInt(matches.get(0))));
Toast toast = Toast.makeText(getApplicationContext(), resulttext, Toast.LENGTH_LONG);
toast.show();
String letter;
switch (resulttext.toLowerCase()) {
case "on":
letter = "A";
break;
case "off":
letter = "B";
break;
case "flash":
letter = "F";
break;
default:
letter = "X";
break;
}
sendData(letter.toUpperCase());
}
super.onActivityResult(requestCode, resultCode, data);
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Sending data: " + message + "...");
Log.d(TAG, "...In onResume - Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting to Remote...");
try {
btSocket.connect();
Log.d(TAG, "...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Creating Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getBaseContext(),
title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
finish();
}
}
Sockets don't just close themselves spontaneously. SocketException: Socket closed means that you closed the socket and then continued to use its. It's a bug in your code.
Your code is very poorly structured. All those strings of try/catch blocks. Code that depends on the success of a prior try block should be inside that block. Don't write code like this.

RFCOMM Buletooth Socket creation using api

I need to create RFCOMM Bluetooth socket for send request and get response from server using blutooth. need to creat bluetooth socket in client side for request and response using android bluetooth api.
How can i create this..
I tried like this
public class MainActivity extends Activity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// Insert your server's MAC address
private static String address = "xxxxxxxxxxxxxxxx";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
out = (TextView) findViewById(R.id.out);
// out.append("\n...In onCreate()...");
btAdapter = BluetoothAdapter.getDefaultAdapter();
CheckBTState();
}
#Override
public void onStart() {
super.onStart();
// out.append("\n...In onStart()...");
}
#Override
public void onResume() {
super.onResume();
out.append("\n...In onResume...\n...Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
try {
btSocket.connect();
out.append("\n...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
out.append("\n...Sending message to server...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
String message = "DECapabilities?$format=json";
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 08:ED:B9:48:EE:C0 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
AlertBox("Fatal Error", msg);
}
}
#Override
public void onPause() {
super.onPause();
out.append("\n...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
#Override
public void onStop() {
super.onStop();
out.append("\n...In onStop()...");
}
#Override
public void onDestroy() {
super.onDestroy();
out.append("\n...In onDestroy()...");
}
private void CheckBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
out.append("\n...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
public void AlertBox( String title, String message ){
new AlertDialog.Builder(this)
.setTitle( title )
.setMessage( message + " Press OK to exit." )
.setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
}).show();
}
}
but getting socket closed exception.
I solved this by BluetoothChat code its help me very much.
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/2.1_r2/com/example/android/BluetoothChat/BluetoothChat.java

Categories

Resources