Can anyone tell me how to connect a mobile and a printer via bluetooth to print a text file in android?
That is,if i click the print button from the android application,the printer has to print that corresponding file.As per my knowledge i have searched for it in Google, but i couldn't find any good samples to do it.Has anyone have at-least one sample android program to do this, it will be better to clear my chaos.
Suggestions please.
Thanks for your precious time!..
Bluetooth Printer Android Example
Create a new android project BlueToothPrinterApp in your editor.
Step 1:
Create main activity like below
com.example.BlueToothPrinterApp / BlueToothPrinterApp.java
package com.example.BlueToothPrinterApp;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import java.io.OutputStream;
import android.bluetooth.BluetoothSocket;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BlueToothPrinterApp extends Activity {
/** Called when the activity is first created. */
EditText message;
Button printbtn;
byte FONT_TYPE;
private static BluetoothSocket btsocket;
private static OutputStream btoutputstream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
message = (EditText) findViewById(R.id.message);
printbtn = (Button) findViewById(R.id.printButton);
printbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
connect();
}
});
}
protected void connect() {
if (btsocket == null) {
Intent BTIntent = new Intent(getApplicationContext(), BTDeviceList.class);
this.startActivityForResult(BTIntent, BTDeviceList.REQUEST_CONNECT_BT);
} else {
OutputStream opstream = null;
try {
opstream = btsocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
btoutputstream = opstream;
print_bt();
}
}
private void print_bt() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
btoutputstream = btsocket.getOutputStream();
byte[] printformat = {
0x1B,
0× 21,
FONT_TYPE
};
btoutputstream.write(printformat);
String msg = message.getText().toString();
btoutputstream.write(msg.getBytes());
btoutputstream.write(0x0D);
btoutputstream.write(0x0D);
btoutputstream.write(0x0D);
btoutputstream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (btsocket != null) {
btoutputstream.close();
btsocket.close();
btsocket = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
btsocket = BTDeviceList.getSocket();
if (btsocket != null) {
print_bt();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step 2:
com.example.BlueToothPrinterApp / BTDeviceList.java
package com.example.BlueToothPrinterApp;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
import android.app.ListActivity;
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.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class BTDeviceList extends ListActivity {
static public final int REQUEST_CONNECT_BT = 0× 2300;
static private final int REQUEST_ENABLE_BT = 0× 1000;
static private BluetoothAdapter mBluetoothAdapter = null;
static private ArrayAdapter < String > mArrayAdapter = null;
static private ArrayAdapter < BluetoothDevice > btDevices = null;
private static final UUID SPP_UUID = UUID
.fromString(“8 ce255c0 - 200 a - 11e0 - ac64 - 0800200 c9a66″);
// UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
static private BluetoothSocket mbtSocket = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(“Bluetooth Devices”);
try {
if (initDevicesList() != 0) {
this.finish();
return;
}
} catch (Exception ex) {
this.finish();
return;
}
IntentFilter btIntentFilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(mBTReceiver, btIntentFilter);
}
public static BluetoothSocket getSocket() {
return mbtSocket;
}
private void flushData() {
try {
if (mbtSocket != null) {
mbtSocket.close();
mbtSocket = null;
}
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
if (btDevices != null) {
btDevices.clear();
btDevices = null;
}
if (mArrayAdapter != null) {
mArrayAdapter.clear();
mArrayAdapter.notifyDataSetChanged();
mArrayAdapter.notifyDataSetInvalidated();
mArrayAdapter = null;
}
finalize();
} catch (Exception ex) {} catch (Throwable e) {}
}
private int initDevicesList() {
flushData();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), “Bluetooth not supported!!”, Toast.LENGTH_LONG).show();
return -1;
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mArrayAdapter = new ArrayAdapter < String > (getApplicationContext(),
android.R.layout.simple_list_item_1);
setListAdapter(mArrayAdapter);
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
try {
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} catch (Exception ex) {
return -2;
}
Toast.makeText(getApplicationContext(), “Getting all available Bluetooth Devices”, Toast.LENGTH_SHORT)
.show();
return 0;
}
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent intent) {
super.onActivityResult(reqCode, resultCode, intent);
switch (reqCode) {
case REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK) {
Set < BluetoothDevice > btDeviceList = mBluetoothAdapter
.getBondedDevices();
try {
if (btDeviceList.size() > 0) {
for (BluetoothDevice device: btDeviceList) {
if (btDeviceList.contains(device) == false) {
btDevices.add(device);
mArrayAdapter.add(device.getName() + “\n” +
device.getAddress());
mArrayAdapter.notifyDataSetInvalidated();
}
}
}
} catch (Exception ex) {}
}
break;
}
mBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mBTReceiver = 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);
try {
if (btDevices == null) {
btDevices = new ArrayAdapter < BluetoothDevice > (
getApplicationContext(), android.R.id.text1);
}
if (btDevices.getPosition(device) < 0) {
btDevices.add(device);
mArrayAdapter.add(device.getName() + “\n” +
device.getAddress() + “\n”);
mArrayAdapter.notifyDataSetInvalidated();
}
} catch (Exception ex) {
// ex.fillInStackTrace();
}
}
}
};
#Override
protected void onListItemClick(ListView l, View v, final int position,
long id) {
super.onListItemClick(l, v, position, id);
if (mBluetoothAdapter == null) {
return;
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
Toast.makeText(
getApplicationContext(), “Connecting to” + btDevices.getItem(position).getName() + “, ”
+btDevices.getItem(position).getAddress(),
Toast.LENGTH_SHORT).show();
Thread connectThread = new Thread(new Runnable() {
#Override
public void run() {
try {
boolean gotuuid = btDevices.getItem(position)
.fetchUuidsWithSdp();
UUID uuid = btDevices.getItem(position).getUuids()[0]
.getUuid();
mbtSocket = btDevices.getItem(position)
.createRfcommSocketToServiceRecord(uuid);
mbtSocket.connect();
} catch (IOException ex) {
runOnUiThread(socketErrorRunnable);
try {
mbtSocket.close();
} catch (IOException e) {
// e.printStackTrace();
}
mbtSocket = null;
return;
} finally {
runOnUiThread(new Runnable() {
#Override
public void run() {
finish();
}
});
}
}
});
connectThread.start();
}
private Runnable socketErrorRunnable = new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), “Cannot establish connection”, Toast.LENGTH_SHORT).show();
mBluetoothAdapter.startDiscovery();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, Menu.FIRST, Menu.NONE, “Refresh Scanning”);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case Menu.FIRST:
initDevicesList();
break;
}
return true;
}
}
Step 3:
Edit your main.xml file and paste below code.
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<TextView
android:id="#+id/msgtextlbl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter Your Message : "/>
<EditText
android:id="#+id/message"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_below="#+id/msgtextlbl"
android:text=""/>
<Button
android:id="#+id/printButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/message"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dip"
android:text="Print"/>
</RelativeLayout>
Step 4:
Now edit your AndroidManifest.xml
Add bluetooth permission and admin permission.
AndroidManifest.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest
xmlns:android=”http://schemas.android.com/apk/res/android
package=”com.example.BlueToothPrinterApp”
android:versionCode=”1″
android:versionName=”1.0″>
<uses-sdk android:minSdkVersion=”14″ />
<uses-permission android:name=”android.permission.BLUETOOTH”></uses-permission>
<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”></uses-permission>
<application
android:label=”#string/app_name”
android:icon=”#drawable/ic_launcher”>
<activity
android:name=”BlueToothPrinterApp”
android:label=”#string/app_name”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<activity android:name=”BTDeviceList”></activity>
</application>
</manifest>
Compile and run this application. Enter message and press print button.
You will see list of bluetooth devices. Select bluettoth printer.
Check print on your bluetooth printer.
here is the CODE Reference...
You can use this awesome lib, you can connect to any printer and print easily,
https://github.com/mazenrashed/Printooth
you can download it by:
implementation 'com.github.mazenrashed:Printooth:${LAST_VERSION}'
and use it like:
var printables = ArrayList<Printable>()
var printable = Printable.PrintableBuilder()
.setText("Hello World")
printables.add(printable)
BluetoothPrinter.printer().print(printables)
Related
I have been trying to send data from arduino to an Android application via Bluetooth Module HC-05 and i couldn't get any readings from the arduino to be displayed in the application
The arduino code is :
void setup() {
Serial.begin(9600);
}
void loop()
{
char c;
if(Serial.available())
{
c = Serial.read();
Serial.print(c);
}
}
The Android code is:
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.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
// private final String DEVICE_NAME="MyBTBee";
private final String DEVICE_ADDRESS="30:14:12:18:01:38";
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");//Serial Port Service ID
private BluetoothDevice 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);
startButton = (Button) findViewById(R.id.buttonStart);
sendButton = (Button) findViewById(R.id.buttonSend);
clearButton = (Button) findViewById(R.id.buttonClear);
stopButton = (Button) findViewById(R.id.buttonStop);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
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();
if(bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
}
else
{
for (BluetoothDevice iterator : bondedDevices)
{
if(iterator.getAddress().equals(DEVICE_ADDRESS))
{
device=iterator;
found=true;
break;
}
}
}
return found;
}
public boolean BTconnect()
{
boolean connected=true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
connected=false;
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
return connected;
}
public void onClickStart(View view) {
if(BTinit())
{
if(BTconnect())
{
setUiEnabled(true);
deviceConnected=true;
beginListenForData();
textView.append("\nConnection Opened!\n");
}
}
}
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;
}
}
}
});
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("");
}
}
The first issue I see right now is in your Arduino code:
You're never sending the message over Bluetooth as you're using the same Serial for input and output. If you're using an Arduino Mega using Serial1 would fixe this (Using TX1 and RX1). If you're not using a Mega you should consider to use the SerialSoftware library which allows you to create a new custom Serial.
It would be nice to see your Arduino setup to see how you wired it up.
Hope that helps you, feel free to ask any question.
package com.ubitech.tokencallingsystem;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
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.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class BluetoothActivity extends Activity{
private final static UUID uuid = UUID.fromString("38bf8160-61ce-11e5-a837-0800200c9a66");
private BluetoothAdapter bluetoothAdapter;
private ToggleButton toggleBtn;
private Button scanBtn;
private ListView listView;
#SuppressWarnings("rawtypes")
private ArrayAdapter adapter;
private static final int ENABLE_BT_REQUEST_CODE = 1;
#SuppressWarnings("rawtypes")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_activity);
toggleBtn = (ToggleButton) findViewById(R.id.toggleButton);
scanBtn = (Button) findViewById(R.id.scan);
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) listView.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17);
Toast.makeText(getApplicationContext(), itemValue+"="+MAC, Toast.LENGTH_SHORT).show();
BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
AcceptThread th = new AcceptThread();
th.start();
System.out.println("In itemonclick listner");
}
});
}
public void onToggleClicked(View view){
//adapter.clear();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), "Oops! Bluetooth not supported.", Toast.LENGTH_SHORT).show();
} else {
if(toggleBtn.isChecked()){
scanDevices(view);
} else{
Toast.makeText(getApplicationContext(), "Turning off bluetooth..", Toast.LENGTH_SHORT).show();
adapter.clear();
bluetoothAdapter.disable();
}
}
}
public void scanDevices(View view){
adapter.clear();
if(!bluetoothAdapter.isEnabled()){
Toast.makeText(getApplicationContext(), "Turning on bluetooth..", Toast.LENGTH_SHORT).show();
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetoothIntent, ENABLE_BT_REQUEST_CODE);
discoverDevices();
}else{
/* Toast.makeText(getApplicationContext(), "Bluetooth has already been enabled." +
"\n" + "Scanning for available nearby bluetooth devices..",
Toast.LENGTH_SHORT).show();*/
discoverDevices();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ENABLE_BT_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// Toast.makeText(getApplicationContext(), "Bluetooth is now enabled.", Toast.LENGTH_SHORT).show();
discoverDevices();
} else {
// Toast.makeText(getApplicationContext(), "Bluetooth is not enabled.",Toast.LENGTH_SHORT).show();
toggleBtn.setChecked(false);
}
}
}
protected void discoverDevices(){
if (bluetoothAdapter.startDiscovery()) {
Toast.makeText(getApplicationContext(), "Scanning for available nearby bluetooth devices..", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Scanning failed to start.", Toast.LENGTH_SHORT).show();
}
}
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
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());
}
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
Toast.makeText(getApplicationContext(), "Paired.", Toast.LENGTH_SHORT).show();
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
Toast.makeText(getApplicationContext(), "UnPaired.", Toast.LENGTH_SHORT).show();
}
}
}
};
#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);
}
private class ConnectingThread extends Thread {
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 {
System.out.println("1");
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
System.out.println("2");
} catch (IOException e) {
System.out.println("In catch exception connecting bt device");
e.printStackTrace();
}
System.out.println("3");
bluetoothSocket = temp;
}
public void run() {
// Cancel discovery as it will slow down the connection
System.out.println("4");
bluetoothAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
System.out.println("5");
if(bluetoothSocket!=null){
bluetoothSocket.connect();
}
/*InputStream inputStream = bluetoothSocket.getInputStream();
OutputStream outputStream = bluetoothSocket.getOutputStream();
outputStream.write(new byte[] { (byte) 0xa0, 0, 7, 16, 0, 4, 0 });*/
Log.e("","Connected");
} catch (IOException connectException) {
System.out.println("In connection exception thread");
connectException.printStackTrace();
try {
System.out.println("6");
bluetoothSocket.close();
System.out.println("7");
} catch (IOException closeException) {
System.out.println("in connection close exception");
closeException.printStackTrace();
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (bluetoothSocket != null) {
try {
Log.d("TCS", ">>Client Close");
bluetoothSocket.close();
finish();
return ;
} catch (IOException e) {
Log.e("EF-BTBee", "", e);
}
}
}
// Code to manage the connection in a separate thread
// manageBluetoothConnection(bluetoothSocket);
}
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("tcs", uuid);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(socket);
try {
mmServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
}
This is my activity file. from where i am trying to connect another android device. But when trying to connect nothing happens. Just getting a warning getBluetoothService() called with no BluetoothManagerCallback.
I am implementing a simple app that sends and receives data between two devices via bluetooth.
I am following the android developer's blog's bluetoothchat example, but my application seems unable to read from the inputstream of a socket.
Writing to the socket is fine. The app does not throw an error nor update the textview as it is supposed to. Any help would be appreciated. Thank you!
Main activity.java(where list of devices are shown and selected) - probably not the errored file:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.*;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends ActionBarActivity {
private final static int REQUEST_ENABLE_BT = 22;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME = "Bluetooth!";
ListView listView;
ArrayList<BluetoothDevice> deviceList;
ArrayAdapter<String> arrayAdapter;
ScanReciever reciever;
BluetoothAdapter bluetooth_adapter;
Button onButton;
Button scanButton;
Button alreadyButton;
AcceptThread acceptThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
deviceList = new ArrayList<>();
//arrayAdapter = new ArrayAdapter<>(this, R.xml.table_item, android.R.id.text1, deviceList);
arrayAdapter = new ArrayAdapter<String>(this, R.layout.table_item);
// Set up Buttons
onButton = (Button) findViewById(R.id.onButton);
scanButton = (Button) findViewById(R.id.scanButton);
onButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
askAdapterOn();
}
});
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanForDevices();
}
});
// Set up listview
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
callButtons(deviceList.get(position));
}
});
// Bluetooth setup.
bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
// If device is incapable of using bluetooth:
if (bluetooth_adapter == null) {
onButton.setEnabled(false);
scanButton.setEnabled(false);
}
else if (!bluetooth_adapter.isEnabled()) { // If bluetooth is off:
//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
onButton.setEnabled(true);
scanButton.setEnabled(false);
}
else { // Bluetooth is on and ready:
onButton.setEnabled(false);
scanButton.setEnabled(true);
alreadyButton = (Button) findViewById(R.id.alreadyButton);
alreadyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Collect current devices into a set.
Set<BluetoothDevice> pairedDevices = bluetooth_adapter.getBondedDevices();
// Pass the index of the paired device
if (pairedDevices.size() > 0) {
callButtons(pairedDevices.iterator().next()); // First element in set.
} else {
System.out.println("No paired Device!");
}
}
});
acceptThread = new AcceptThread();
acceptThread.start();
}
}
private class ScanReciever extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
System.out.println("Started");
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
System.out.println("finished");
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("FOUND: " + device.getName());
deviceList.add(device);
arrayAdapter.add(device.getName()+" - Click to pair");
arrayAdapter.notifyDataSetChanged();
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
System.out.println("Connected~!!!!!!!!!!!!!!");
callButtons(deviceList.get(deviceList.size()-1));
}
}
};
protected void askAdapterOn() {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
protected void scanForDevices() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
reciever = new ScanReciever();
registerReceiver(reciever, filter);
bluetooth_adapter.startDiscovery();
}
protected void callButtons(BluetoothDevice bd) {
bluetooth_adapter.cancelDiscovery();
Intent toButton = new Intent(getApplicationContext(), buttons.class);
toButton.putExtra("selected",bd);
startActivity(toButton);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK){
if (bluetooth_adapter.isEnabled()){
onButton.setEnabled(false);
scanButton.setEnabled(true);
}
else {
onButton.setEnabled(true);
scanButton.setEnabled(false);
}
}
}
}
#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);
}
#Override
public void onDestroy() {
unregisterReceiver(reciever);
super.onDestroy();
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetooth_adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
System.out.println("READY TO ACCEPT");
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(socket);
try {
mmServerSocket.close();
} catch (IOException e) { }
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
}
Buttons.java(where the app will initiate a connection and maintain communication) - probably the file with the error:
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.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
public class buttons extends Activity {
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
BluetoothDevice selected;
BluetoothAdapter bluetoothAdapter;
TextView tv;
Button button1;
Button button2;
Button button3;
Button unpairB;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
ConnectThread connectThread;
ConnectedThread connectedThread;
BluetoothSocket mmSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buttons);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
selected = getIntent().getExtras().getParcelable("selected");
pair(selected);
connectedThread = null;
try {
connectedThread = new ConnectedThread(mmSocket);
connectedThread.start();
System.out.println("ConnectedThread started!");
} catch (Exception e) {
Log.e("unpair()", e.getMessage());
}
// Set up Buttons
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
unpairB = (Button) findViewById(R.id.unpairButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(2);
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(3);
}
});
unpairB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
unpair(selected);
finish();
}
});
// Set up textview
tv = (TextView) findViewById(R.id.textView);
tv.setText("connected to: " + selected.getName());
}
protected void buttonPressed(int i) {
connectedThread.write(i);
tv.setText(Integer.toString(i));
}
private void pair(BluetoothDevice device) {
connectThread = new ConnectThread(device);
connectThread.start();
}
private void unpair(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e("unpair()", e.getMessage());
}
}
private class ConnectThread extends Thread {
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;
// 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);
System.out.println("Socket was created in ConnectThread");
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
// bluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// 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)
//manageConnectedSocket(mmSocket);
}
/** 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 bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ConnectedThread(BluetoothSocket socket) {
this.bluetoothSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
System.out.println("Connected to " + socket.getRemoteDevice().getName());
try {
tmpIn = bluetoothSocket.getInputStream();
tmpOut = bluetoothSocket.getOutputStream();
} catch (IOException e) {
}
inputStream = tmpIn;
outputStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
if (inputStream == null) System.out.println("Inputstream is null");
else System.out.println("Inputstream is safe");
if (outputStream == null) System.out.println("outstream is null");
else System.out.println("Outputstream is safe");
while (true) {
try {
System.out.println("Blocking?");
bytes = inputStream.read(buffer);
System.out.println("NO");
handler.obtainMessage(MESSAGE_READ, bytes, -1,
buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void write(int i) {
try {
byte[] buffer = new byte[1024];
buffer[0] = (byte) i;
outputStream.write(buffer);
outputStream.flush();
handler.obtainMessage(MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
System.out.println("Write SUCCESS!!!!!!!!!!!!!!");
} catch (IOException e) {
System.out.println("write ERRORRRRRRRRRRRRRRRRR");
}
}
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
}
}
}
private final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WRITE:
System.out.println("Write was broadcasted");
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(Integer.toString(writeBuf[0]));
///tv.setText(writeMessage);
break;
case MESSAGE_READ:
System.out.println("Read was broadcasted");
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(Integer.toString(readBuf[0]));
tv.setText(readMessage);
break;
}
}
};
}
I am trying to save an array list into a xml file in the internal storage using Xmlserializer. The app scans for BLE and when a Stop button is pressed it should save some parameters from the list of BLE that it has detected. It runs perfect and when I pressed the stop button it stops the scan and displays in the mobile screen a toast message that the xml file has been created successfully. However, when I seach for the xml file, it doesn´t appear anywhere as if it hasn´t been created. I don´t know the reason of this problem. Here is the code I have implemented:
package com.example.newblescan;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.xmlpull.v1.XmlSerializer;
import com.example.newblescan.R;
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.example.newblescan.adapter.BleDevicesAdapter;
/**
* Activity for scanning and displaying available Bluetooth LE devices.
*/
public class DeviceScanActivity extends ListActivity {
private static final int REQUEST_ENABLE_BT = 1;
private static final long SCAN_PERIOD = 100;
private BleDevicesAdapter leDeviceListAdapter;
private BluetoothAdapter bluetoothAdapter;
private Scanner scanner;
private Save save;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setTitle(R.string.title_devices);
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (bluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.gatt_scan, menu);
if (scanner == null || !scanner.isScanning()) {
menu.findItem(R.id.menu_stop).setVisible(false);
menu.findItem(R.id.menu_scan).setVisible(true);
menu.findItem(R.id.menu_refresh).setActionView(null);
} else {
menu.findItem(R.id.menu_stop).setVisible(true);
menu.findItem(R.id.menu_scan).setVisible(false);
menu.findItem(R.id.menu_refresh).setActionView(
R.layout.actionbar_indeterminate_progress);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_scan:
leDeviceListAdapter.clear();
if (scanner == null) {
scanner = new Scanner(bluetoothAdapter, mLeScanCallback);
scanner.startScanning();
invalidateOptionsMenu();
}
break;
case R.id.menu_stop:
if (scanner != null) {
save = new Save(leDeviceListAdapter);
scanner.stopScanning();
try {
save.savedata();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scanner = null;
invalidateOptionsMenu();
}
break;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!bluetoothAdapter.isEnabled()) {
final Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
return;
}
init();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_CANCELED) {
finish();
} else {
init();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onPause() {
super.onPause();
if (scanner != null) {
scanner.stopScanning();
scanner = null;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = leDeviceListAdapter.getDevice(position);
if (device == null)
return;
//final Intent intent = new Intent(this, DeviceServicesActivity.class);
//intent.putExtra(DeviceServicesActivity.EXTRAS_DEVICE_NAME, device.getName());
//intent.putExtra(DeviceServicesActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
//startActivity(intent);
}
private void init() {
if (leDeviceListAdapter == null) {
leDeviceListAdapter = new BleDevicesAdapter(getBaseContext());
setListAdapter(leDeviceListAdapter);
}
if (scanner == null) {
scanner = new Scanner(bluetoothAdapter, mLeScanCallback);
scanner.startScanning();
}
invalidateOptionsMenu();
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
leDeviceListAdapter.addDevice(device, rssi);
leDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
private static class Scanner extends Thread {
private final BluetoothAdapter bluetoothAdapter;
private final BluetoothAdapter.LeScanCallback mLeScanCallback;
private volatile boolean isScanning = false;
Scanner(BluetoothAdapter adapter, BluetoothAdapter.LeScanCallback callback) {
bluetoothAdapter = adapter;
mLeScanCallback = callback;
}
public boolean isScanning() {
return isScanning;
}
public void startScanning() {
synchronized (this) {
isScanning = true;
start();
}
}
public void stopScanning() {
synchronized (this) {
isScanning = false;
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
#Override
public void run() {
try {
while (true) {
synchronized (this) {
if (!isScanning)
break;
bluetoothAdapter.startLeScan(mLeScanCallback);
}
sleep(SCAN_PERIOD);
synchronized (this) {
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
} catch (InterruptedException ignore) {
} finally {
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
}
public class Save {
/**
*
*/
private BleDevicesAdapter leDeviceListAdapter;
Save(BleDevicesAdapter BLEList) {
leDeviceListAdapter = BLEList;
}
public void savedata() throws FileNotFoundException{
String filename = "Dragon.txt";
//String date = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());
FileOutputStream fos = null;
int size = leDeviceListAdapter.getCount();
//Bundle extras = getIntent().getExtras();
//long timestamp = extras.getLong("currentTime");
try {
fos= openFileOutput(filename, Context.MODE_PRIVATE);
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(fos, "UTF-8");
serializer.startDocument(null, Boolean.valueOf(true));
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag("", "root");
//serializer.startTag("", "timestamp");
//serializer.text(date);
//serializer.endTag("", "timestamp");
for(int j = 0 ; j < size ; j++)
{
BluetoothDevice devices = leDeviceListAdapter.getDevice(j);
//Integer signal = leDeviceListAdapter.getRSSI(j);
serializer.startTag("", "name");
serializer.text(devices.getName());
serializer.endTag("", "name");
serializer.startTag("", "address");
serializer.text(devices.getAddress());
serializer.endTag("", "address");
//serializer.startTag(null, "rssi");
//serializer.setProperty(null, signal);
//serializer.endTag(null, "rssi");
}
//ObjectOutputStream out = new ObjectOutputStream(fos);
//out.write((int) timestamp);
//out.writeObject(leDeviceListAdapter);
//out.close();
serializer.endDocument();
serializer.flush();
fos.close();
Toast.makeText(DeviceScanActivity.this, R.string.list_saved, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
In the class Save, I implement the method savedata to save the list into a xml file.
Does anyone know what is the problem? Pleasee help!!!!
openFileOutput puts it in the /data/data/your_packagename/files directory. This directory can only be read by root and by your app- you will not be able to find the file in any other program without rooting your device. You will not be able to find it in a file explorer unless you have root access. If you want to be able to see the file, you need to write it somewhere world accessible, such as the sd card.
I am trying to connect to a paired bluetooth device (baracoda d-fly bar code reader). I tried the program GetBlueDemo from market and this manages to read from its socket.
I wrote my own proof of concept, but i just keep getting an excpetion when i try to connect to the device.
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): Could not connect to socket
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): java.io.IOException: socket failed to connect
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:255)
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): at org.me.barcodetest.MainActivity$ConnectRunnable.run(MainActivity.java:211)
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): at java.lang.Thread.run(Thread.java:1102)
Any suggestions on what i am doing wrong?
package org.me.barcodetest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 2;
private BluetoothAdapter bluetoothAdapter;
private UUID applicationUUID = java.util.UUID.randomUUID();
private static final String logTag = "BluetoothTest";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Log.d(logTag, "Could not get bluetooth adapter");
return;
}
searchForDevices();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
if (requestCode == RESULT_OK) {
Log.d("BluetoothTest", "bluetooth enabled");
searchForDevices();
} else {
Log.d("BluetoothTest", "Could not enable bluetooth device");
}
}
}
public void lineReadFromBluetoothDevice(String line) {
Log.d(logTag, "Mottok: " + line);
}
private void searchForDevices() {
if (bluetoothAdapter.isEnabled()) {
Set<BluetoothDevice> devicesAvailable = bluetoothAdapter.getBondedDevices();
if (devicesAvailable.isEmpty()) {
informUserNoDevicesPaired();
} else {
askUserToPickDeviceToUse(devicesAvailable);
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
private void askUserToPickDeviceToUse(Set<BluetoothDevice> devicesAvailable) {
final ListView view = new ListView(this);
view.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<BluetoothDevice> adapter =
new ArrayAdapter(this, R.layout.devicesavailabletextview, devicesAvailable.toArray(new BluetoothDevice[devicesAvailable.size()])) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getView(position, convertView, parent);
BluetoothDevice bluetoothDevice = (BluetoothDevice) getItem(position);
view.setText(bluetoothDevice.getName() + " : " + bluetoothDevice.getAddress());
return view;
}
};
view.setAdapter(adapter);
view.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
pairToDevice((BluetoothDevice) view.getItemAtPosition(position));
}
});
Dialog dialog = new Dialog(this);
dialog.setContentView(view);
dialog.setCancelable(true);
dialog.show();
}
private void informUserNoDevicesPaired() {
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setMessage("Ingen \"Paired\" enheter");
dialogBuilder.setPositiveButton("Søk", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
});
dialogBuilder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
finish();
}
});
dialogBuilder.show();
}
private void showError(String message) {
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setMessage("Det oppstod en feil i programmet:\n\n" + message);
dialogBuilder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
finish();
}
});
dialogBuilder.show();
}
private void pairToDevice(BluetoothDevice bluetoothDevice) {
openSocket(bluetoothDevice);
}
private void openSocket(BluetoothDevice bluetoothDevice) {
try {
final ProgressDialog dialog = new ProgressDialog(this);
final ConnectRunnable connector = new ConnectRunnable(bluetoothDevice, dialog);
dialog.show(this, "Kobler til", "Koblier til " + bluetoothDevice.getName() + " : " + bluetoothDevice.getAddress(),
true, true,
new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
connector.cancel();
}
});
new Thread(connector).start();
} catch (IOException ex) {
Log.d(logTag, "Could not open bluetooth socket", ex);
showError("Kunne ikke åpne socket grunnet feil: " + ex.getMessage());
}
}
private void closeSocket(BluetoothSocket openSocket) {
try {
openSocket.close();
} catch (IOException ex) {
Log.d(logTag, "Could not close exisiting socket", ex);
}
}
private void startListeningForInput(BluetoothSocket socket) {
new Thread(new InputReader(socket)).start();
}
private void dismissDialog(final Dialog dialog) {
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
private class ConnectRunnable implements Runnable {
private final ProgressDialog dialog;
private final BluetoothSocket socket;
public ConnectRunnable(BluetoothDevice device, ProgressDialog dialog) throws IOException {
socket = device.createRfcommSocketToServiceRecord(applicationUUID);
this.dialog = dialog;
}
public void run() {
try {
bluetoothAdapter.cancelDiscovery();
socket.connect();
} catch (IOException connectException) {
Log.d(logTag, "Could not connect to socket", connectException);
closeSocket(socket);
return;
}
startListeningForInput(socket);
dismissDialog(dialog);
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
Log.d(logTag, "Canceled connection", e);
}
}
}
private class InputReader implements Runnable {
private final BluetoothSocket socket;
public InputReader(BluetoothSocket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
final InputStream input = socket.getInputStream();
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
lineReadFromBluetoothDevice(line);
}
} catch (IOException ex) {
showError("Mistet forbindelsen: " + ex.getMessage());
}
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
devicesavailabletextview:
<?xml version="1.0" encoding="UTF-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
The problem was my uuid, i figured this was just an uuid for android to know where it came from, but it had to be "00001101-0000-1000-8000-00805F9B34FB"
The barcode scanner uses the SPP protocol - so your have to use the SPP UUID to connect to it.