Printing with android - android

I want to print the text file from my application in android 8 through Bluetooth or WiFi. Please suggest me the solution.

this is a sample
package com.example.untitled2;
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.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MyActivity extends Activity {
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(MyActivity.this, "no device", Toast.LENGTH_LONG).show();
}
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
Set<BluetoothDevice> bluetoothDevices = mBluetoothAdapter.getBondedDevices();
if (bluetoothDevices.size() == 0)
return;
OutputStream mmOutStream;
BluetoothDevice device = bluetoothDevices.iterator().next();
try {
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
mmOutStream = socket.getOutputStream();
/*String textPrint = ""+(char) 27 + (char)116 + (char) 27;*/
String textPrint = "this is example text"+(char)10;
mmOutStream.flush();
mmOutStream.write(textPrint.getBytes());
mmOutStream.flush();
for (int i = 0; i < 10; i++) {
mmOutStream.write(textPrint.getBytes());
}
mmOutStream.flush();
//mmOutStream.wait();
mmOutStream.close();
socket.close();
} catch (IOException e) {
Toast.makeText(MyActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}

Here is my code [found online & modified as per my reqt] to connect to a Blue-tooth printer, works perfectly... tried n tested. :-)
package com.nvsoft.s2pay.mmsl.bluetoothprinter;
import android.app.Activity;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
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 com.nvsoft.s2pay.sms.DynaCCSmsServiceConstants;
import com.nvsoft.s2pay.util.StringUtil;
import java.util.HashSet;
import org.json.me.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//This class is meant for wrapping the Bluetooth connecting interface provided by android devices.......
//Basically is a state machine, and the communications will happen in a separate thread so as not to obstruct the main UI
public class BTWrapperActivity extends Activity {
public static final int REQUEST_CONNECT_BT = 0x2300;//8960
public static final int REQUEST_ENABLE_BT = 0x1000;//4096
public static final String DEVICES_DISCOVERED = "DD";
public static final String EXTRA_DEVICE_ADDRESS = DynaCCSmsServiceConstants.PRINTER_MAC_ADDRESS;
private static final String ERROR = "ecode";
private static final String ERROR_MSG = "emsg";
public static int ERROR_CODE = 0;
int request;
static private BluetoothAdapter mBluetoothAdapter = null;
static private Set<BluetoothDevice> btDevices = null;
String deviceNames = null;
JSONObject jobj = new JSONObject();
Intent parentIntent = null;
BluetoothDevice selectedDevice = null;
static private BluetoothSocket mbtSocket = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
deviceNames = bundle.getString(EXTRA_DEVICE_ADDRESS);
parentIntent = getIntent();
request = bundle.getInt(BluetoothFilePrinter.REQUEST_CODE);
try {
if (request != DynaCCSmsServiceConstants.EXIT_ACTIVITY_REQUEST){
if (initDevicesList() != 0) {
this.finish();
return;
}
}
} catch (Exception ex) {
getIntent().putExtra(ERROR, 701);
getIntent().putExtra(ERROR_MSG, ex.getMessage());
finish();
return;
}
// Register the Broadcast receiver for handling new BT device discovery
//IntentFilter btIntentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//this.registerReceiver(mBTReceiver, new IntentFilter(DynaCCSmsServiceConstants.ACTION_EXIT_ACTIVITY));
this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED));
this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
this.registerReceiver(mBTReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
this.registerReceiver(mBTReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
if (request == DynaCCSmsServiceConstants.EXIT_ACTIVITY_REQUEST) {
unregisterReceiver(mBTReceiver);
this.finish();
}
}
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 (deviceNames!=null) {
deviceNames = null;
}
finalize();
} catch(Exception ex){
getIntent().putExtra(ERROR, 702);
getIntent().putExtra(ERROR_MSG, ex.getMessage());
} catch (Throwable e) {
getIntent().putExtra(ERROR, 702);
getIntent().putExtra(ERROR_MSG, e.getMessage());
}
}
// This method will Connect to our SPP Bluetooth Device after discovering and pairing if required
// Do not forget to add the permission for Bluetooth to use this method
// Also this method is very tightly coupled with the above method, for getting the status of bt connection
private int initDevicesList() {
// Flush any Pending Data to rediscover devices
if (request == DynaCCSmsServiceConstants.DISCOVER_REQUEST) {
flushData();
}
// Get the Bluetooth Adaptor of the device
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
return -1;
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// ENABLE BLUETOOTH on DEVICE if not ALREADY TURNED ON
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
try {
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} catch (Exception ex) {
return -2;
}
return 0;
} // End getDeviceList
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent intent) {
super.onActivityResult(reqCode, resultCode, intent);
if (intent == null) {
intent = getIntent();
}
switch (reqCode) {
case REQUEST_ENABLE_BT:
if (request == DynaCCSmsServiceConstants.DISCOVER_REQUEST) {
if (resultCode == RESULT_OK) {
// Start getting the paired devices list
Set<BluetoothDevice> btDeviceList = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
try {
if (btDeviceList.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : btDeviceList) {
jobj.put(device.getName(), device.getAddress());
if (btDeviceList.contains(device) == false) {
btDevices.add(device); // Add the device to the device list
jobj.put(device.getName(), device.getAddress());
}
}
if (jobj != null) {
intent.putExtra(DEVICES_DISCOVERED, jobj.toString());
}
setResult(Activity.RESULT_OK, intent);
finish();
} else {
mBluetoothAdapter.startDiscovery();
}
} catch (Exception ex) {
getIntent().putExtra(ERROR, 704);
getIntent().putExtra(ERROR_MSG, ex.getMessage());
setResult(Activity.RESULT_CANCELED, intent);
}
} else {
getIntent().putExtra(ERROR, 704);
getIntent().putExtra(ERROR_MSG, "Permission to enable Bluetooth on the device was denied. Please enable Bluetooth and retry.");
setResult(Activity.RESULT_CANCELED, intent);
finish();
}
}//end of discovery
else if (request == DynaCCSmsServiceConstants.CONNECT_REQUEST || request == DynaCCSmsServiceConstants.PRINT_REQUEST) {
if (resultCode == RESULT_OK) {
if (deviceNames!=null) {
connect(deviceNames);
}else{
getIntent().putExtra(ERROR, 704);
getIntent().putExtra(ERROR_MSG, "Could not find any printer.");
setResult(Activity.RESULT_CANCELED, intent);
finish();
}
}else{
getIntent().putExtra(ERROR, 704);
getIntent().putExtra(ERROR_MSG, "Permission to enable Bluetooth on the device was denied. Please enable Bluetooth and retry.");
setResult(Activity.RESULT_CANCELED, intent);
finish();
}
}
break;
case REQUEST_CONNECT_BT:
if (resultCode == Activity.RESULT_OK) {
setResult(Activity.RESULT_OK, intent);
} else {
setResult(Activity.RESULT_CANCELED, intent);
}
finish();
break;
}
}
private final BroadcastReceiver mBTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Get the BluetoothDevice object from the Intent
BluetoothDevice device ;
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
// No paired device found
if (btDevices == null) {
btDevices = new HashSet<BluetoothDevice>();
btDevices.add(device);
jobj.put(device.getName(), device.getAddress());
} else {
if (!btDevices.contains(device)) {
btDevices.add(device);
jobj.put(device.getName(), device.getAddress());
}
}
intent.putExtra(DEVICES_DISCOVERED, jobj.toString());
} catch (Exception ex) {
getIntent().putExtra(ERROR, 705);
getIntent().putExtra(ERROR_MSG, ex.getMessage());
}
} else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
intent.putExtra("IS_CONNECTED", true);
} else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
//#ifndef REMOVE_DEBUG
logger.debug("BTWrapperActivity - ", " Device is about to disconnect");
//#endif
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//#ifndef REMOVE_DEBUG
logger.debug("BTWrapperActivity - ", "Device has disconnected");
//#endif
intent.putExtra("IS_CONNECTED", false);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//#ifndef REMOVE_DEBUG
logger.debug("BTWrapperActivity - ", "DISCOVERY FINISSHED");
//#endif
if (request == DynaCCSmsServiceConstants.DISCOVER_REQUEST) {
intent.putExtra(DEVICES_DISCOVERED, jobj.toString());
sendDiscoveryResult(intent);
}
}else if(Intent.ACTION_SCREEN_ON.equals(action)){
//#ifndef REMOVE_DEBUG
logger.debug("BTWrapperActivity - ", "SCREEN ON");
//#endif
}else if(Intent.ACTION_SCREEN_OFF.equals(action)){
//#ifndef REMOVE_DEBUG
logger.debug("BTWrapperActivity - ", "SCREEN OFF");
//#endif
}
}
};
private void connect(final String deviceAddress) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
return;
} else {
selectedDevice = mBluetoothAdapter.getRemoteDevice(deviceAddress);
}
// Cancel the dicovery if still going on
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
if (mbtSocket != null) {
try {
mbtSocket.close();
} catch (IOException ex) {
getIntent().putExtra(ERROR, 706);
getIntent().putExtra(ERROR_MSG, ex.getMessage());
setResult(Activity.RESULT_CANCELED, getIntent());
finish();
}
mbtSocket = null;
}
// Try to connect with the selected device,
// made the thread different as the connecting proceedure might break down the system
Thread connectThread = new Thread(new Runnable() {
#Override
public void run() {
Intent intent = getIntent();
String errMsg = "";
try {
try {
Method m = selectedDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[]{int.class});
try {
mbtSocket = (BluetoothSocket) m.invoke(selectedDevice, 1);
} catch (IllegalArgumentException e) {
errMsg = e.getMessage();
getIntent().putExtra(ERROR, 707);
getIntent().putExtra(ERROR_MSG, errMsg);
} catch (IllegalAccessException e) {
errMsg = e.getMessage();
getIntent().putExtra(ERROR, 708);
getIntent().putExtra(ERROR_MSG, errMsg);
} catch (InvocationTargetException e) {
errMsg = e.getMessage();
getIntent().putExtra(ERROR, 709);
getIntent().putExtra(ERROR_MSG, errMsg);
}finally{
if (!StringUtil.isEmpty(errMsg) && intent.getExtras().getInt(ERROR)>0) {
setResult(Activity.RESULT_CANCELED, getIntent());
finish();
}
}
} catch (SecurityException e) {
errMsg = e.getMessage();
getIntent().putExtra(ERROR, 710);
getIntent().putExtra(ERROR_MSG, errMsg);
setResult(Activity.RESULT_CANCELED, getIntent());
finish();
} catch (NoSuchMethodException e) {
errMsg = e.getMessage();
getIntent().putExtra(ERROR, 711);
getIntent().putExtra(ERROR_MSG, errMsg);
setResult(Activity.RESULT_CANCELED, getIntent());
finish();
}
//mbtSocket =
selectedDevice.createRfcommSocketToServiceRecord(SPP_UUID);
ERROR_CODE = intent.getExtras().getInt(ERROR);
//#ifndef REMOVE_DEBUG
logger.debug("ERROR = ", ERROR_CODE);
//#endif
if (ERROR_CODE == 0) {
mbtSocket.connect();
//#ifndef REMOVE_DEBUG
logger.debug("##BTWrapperActivity - ", "Connected to selectedDevice = " + (String) intent.getExtras().get(EXTRA_DEVICE_ADDRESS));
//#endif
intent.putExtra("IS_CONNECTED", true);
setResult(Activity.RESULT_OK, intent);
} else {
intent.putExtra(ERROR, ERROR_CODE);
intent.putExtra(ERROR_MSG,errMsg);
setResult(Activity.RESULT_CANCELED, intent);
finish();
}
} catch (IOException ex) {
getIntent().putExtra(ERROR, 712);
getIntent().putExtra(ERROR_MSG, "Unable to Connect to the Printer. Please verify the printer settings and try again.");
getIntent().putExtra("IS_CONNECTED", false);
ex.printStackTrace();
setResult(Activity.RESULT_CANCELED, intent);
finish();
}finally{
finish();
}
}
});
connectThread.start();
}
private Runnable socketErrorRunnable = new Runnable() {
#Override
public void run() {
getIntent().putExtra(ERROR, 714);
getIntent().putExtra(ERROR_MSG,"Cannot establish connection");
mBluetoothAdapter.startDiscovery();
}
};
protected void onStop() {
unregisterReceiver(mBTReceiver);
super.onStop();
}
private void sendDiscoveryResult(Intent mIntent){
mIntent.putExtra(DEVICES_DISCOVERED, jobj.toString());
setResult(Activity.RESULT_OK, mIntent);
finish();
}
private String getDisplayMessage(){
String message = "Please Wait!!";
switch(request) {
case DynaCCSmsServiceConstants.DISCOVER_REQUEST :
message = "Discovery in progress!!";
break;
case DynaCCSmsServiceConstants.CONNECT_REQUEST:
message = "Connecting...Please Wait!!";
break;
case DynaCCSmsServiceConstants.PRINT_REQUEST:
message = "Printing in progress!!";
break;
}
return message;
}} // End of class definition

Related

Connecting 2 bluetooth devices

I'm trying to make an application that is using bluetooth.It's very simple but I'm stuck at connecting devices.
So far I've made 2 listviews, one is displaying paired devices and the other found devices.I dont understand how sockets work and how to make the device server or a client.
Can someone please explain me that or at least tell me what to do with the code I already made(copied).
I've gone through all the tutorials I could find and I still dont understand it.The bluetooth chat example is very confusing, I'm a beginner in android programming and didn't really study much java.
This is the code:
public class ConnectThread extends Thread{
BluetoothDevice device;
private BluetoothSocket socket;
ConnectThread(){
connect(device, MY_UUID);
}
public boolean connect(BluetoothDevice bTDevice, UUID mUUID) {
BluetoothSocket temp = null;
try {
temp = bTDevice.createRfcommSocketToServiceRecord(mUUID);
} catch (IOException e) {
Log.d("CONNECTTHREAD","Could not create RFCOMM socket:" + e.toString());
return false;
}
try {
socket.connect();
} catch(IOException e) {
Log.d("CONNECTTHREAD","Could not connect: " + e.toString());
try {
socket.close();
} catch(IOException close) {
Log.d("CONNECTTHREAD", "Could not close connection:" + e.toString());
return false;
}
}
return true;
}
public boolean cancel() {
try {
socket.close();
} catch(IOException e) {
Log.d("CONNECTTHREAD","Could not close connection:" + e.toString());
return false;
}
return true;
}
}
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.listenUsingRfcommWithServiceRecord(NAME, MY_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)
try {
mmServerSocket.close();
} catch (IOException e) {
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 the xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:baselineAligned="false">
<ListView
android:layout_width="170dp"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:background="#drawable/lviewbg"
android:id="#+id/paired_devies">
</ListView>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="fill_horizontal"
android:background="#drawable/lviewbg"
android:id="#+id/new_devices">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<Button
android:id="#+id/discover"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#aa0000ff"
android:text="#string/disc"
style="?android:attr/buttonBarButtonStyle"
/>
<Button
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#aa0000ff"
android:text="#string/discoverable"
android:onClick="makeDiscoverable"
style="?android:attr/buttonBarButtonStyle"
/>
</LinearLayout>
</LinearLayout>
This is rest of the code if you need it:
package com.example.user.broj;
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.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
public class BluetoothDevices extends AppCompatActivity{
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;
BluetoothDevice device;
static int REQUEST_ENABLE_BT = 1;
static int DISCOVERABLE_BT_REQUEST_CODE = 1;
static int DISCOVERABLE_DURATION = 120;
public static String EXTRA_DEVICE_ADDRESS = "device_address";
private BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
//This is used for connecting devices
static final String NAME = "BluetoothGame";
static final UUID MY_UUID = UUID.fromString("ae19c8fa-9b60-11e5-8994-feff819cdc9f");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
Button scanButton = (Button) findViewById(R.id.discover);
scanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
doDiscovery();
view.setClickable(false);
}
});
//enabling bluetooth
if(!bluetooth.isEnabled()){
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(btIntent, REQUEST_ENABLE_BT);
}
//arrayadapters for paired and new devices list views
mPairedDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.device_name);
//listview for paired devices
ListView deviceList = (ListView) findViewById(R.id.paired_devies);
deviceList.setAdapter(mPairedDevicesArrayAdapter);
deviceList.setOnItemClickListener(mDeviceClickListener);
//listview for new devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
bluetooth = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
if (pairedDevices.size() > 0) {
//findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
//button onClick for making the device discoverable
public void makeDiscoverable(View view) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DISCOVERABLE_BT_REQUEST_CODE){
if (resultCode == DISCOVERABLE_DURATION){
Toast.makeText(getApplicationContext(), "Your device is now discoverable by other devices for " +
DISCOVERABLE_DURATION + " seconds",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Fail to enable discoverability on your device.",
Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (bluetooth != null) {
bluetooth.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
private void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
// findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (bluetooth.isDiscovering()) {
bluetooth.cancelDiscovery();
}
// Request discover from BluetoothAdapter
bluetooth.startDiscovery();
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
bluetooth.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Button scanButton = (Button) findViewById(R.id.discover);
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
scanButton.setClickable(true);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
Async class for connection via Bluetoothsocket
UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
InputStream is1;
OutputStream os1;
BluetoothAdapter bluetoothAdapter = null;
BluetoothSocket socket = null;
class UserInterface extends Thread {
BluetoothDevice bdDevice;
public UserInterface() {
bdDevice = your pair device;
}
#Override
public void run() {
Looper.prepare();
try {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
if (socket != null && socket.isConnected()) {
is1.close();
os1.close();
socket.close();
}
try {
socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (Exception e) {
Log.e("", "Error creating socket");
}
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
try {
socket.connect();
Log.e("", "Connected Rfcomm");
} catch (IOException e) {
Log.e("", e.getMessage());
try {
Log.e("", "trying fallback...");
socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
socket.connect();
Log.e("", "Connected serial UDID");
} catch (Exception e2) {
Log.e("", "Couldn't establish Bluetooth connection!");
}
}
if (socket.isConnected()) {
// dismiss Progress Dialog
os1 = socket.getOutputStream();
is1 = socket.getInputStream();
Log.i("TAG", "Socket Connected");
//code after socket connect
} else {
// dismiss Progress Dialog
showProgressDialogToast("Please restart bluetooth Device");
closeSocket();
Log.i("TAG", "Socket Disconnected");
}
Log.i("Log", "Removed" + bdDevice.getName());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("Log", "Under Catch of thread");
e.printStackTrace();
// dismiss Progress Dialog
}
}
}
use Thread class like this
UserInterface userInterface = new UserInterface();
userInterface.start();
Basically refer the tutorial given by android developers on their site.
In every connectivity there should be one server and one client. The server will just run the accept thread and the client will run the connect thread. Once the accept thread started, you need to connect from the client side with the proper device name.

I am building a bluetooth app for communating another bluetooth device. I am able to scan and get list of available devices

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.

Arduino Android Bluetooth Serial Communication

I have an Arduino Bluetooth shield HC-05. I paired the Bluetooth shield first with Android device and tried to send data to Arduino via Bluetooth shield. Android app sends data to the shield. But Arduino not receiving the command more than (4 to 13) times I think my app not holding the connection properly with the Bluetooth shield, I am not sure about the problem. I tried with the same Arduino code with some other Android application. It was working well. So problem is in my code only. I am using log to monitor the flow of code. The data is sending from the Android device and the Bluetooth is live and still paired. I think Bluetooth shield was not receiving or it was receiving and not passing the data to Arduino. I am troubling for couple of weeks.
Thanks in Advance !!
My code goes here...
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static String address = "98:D3:31:30:25:DC";//old: 20:14:12:03:12:42, 98:D3:31:30:25:DC
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private InputStream inStream = null;
Handler handler = new Handler();
byte delimiter = 10;
boolean stopWorker = false;
int readBufferPosition = 0;
byte[] readBuffer = new byte[1024];
//
//Bluetooth sender ends
//
//
private final BroadcastReceiver commandAction = new BroadcastReceiver() {
#Override
public void onReceive(Context context2, Intent intent2) {
String com = intent2.getStringExtra("key");
commandAction(com);
Toast.makeText(context2, "commandAction:"+com, Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
commandAction("up");
}
});
GCMRegistrar.checkDevice( this );
GCMRegistrar.checkManifest( this );
final String regId = GCMRegistrar.getRegistrationId( this );
if( regId.equals( "" ) ) {
GCMRegistrar.register( this, "501396392354" );
Toast.makeText(this," 501396392354", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this,regId, Toast.LENGTH_SHORT).show();
Log.v( TAG2, "Already registered" );
Log.v(TAG2, "Registration id is: " + regId );
}
startService(new Intent(MainActivity.this, LocationService.class));
CheckBt();
Connect();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.e("Jon", device.toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public Object onRetainNonConfigurationInstance() {
if (mAccessory != null) {
return mAccessory;
} else {
return super.onRetainNonConfigurationInstance();
}
}
#Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("in.robot.gcm.commandaction");
registerReceiver(commandAction, intentFilter);
if (mInputStream != null && mOutputStream != null) {
return;
}
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(commandAction);
closeAccessory();
}
#Override
public void onDestroy() {
unregisterReceiver(mUsbReceiver);
stopService(new Intent(MainActivity.this, LocationService.class));
try {
btSocket.close();
} catch (IOException e) {
}
super.onDestroy();
}
private void openAccessory(UsbAccessory accessory) {
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Log.d(TAG, "accessory opened");
} else {
Log.d(TAG, "accessory open fail");
}
}
private void closeAccessory() {
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
} catch (IOException e) {
} finally {
mFileDescriptor = null;
mAccessory = null;
}
}
public void commandAction(String command){
byte[] buffer = new byte[1];
MediaPlayer mp;
Toast.makeText(this,"in cmd action",Toast.LENGTH_SHORT).show();
if("up".equals(command)){
buffer[0]=(byte)0;
Log.v(TAG ,"up heay");
writeData("1");
Toast.makeText(this,"UP",Toast.LENGTH_SHORT).show();
}
else if("down".equals(command)) {
buffer[0]=(byte)1;
Log.v(TAG ,"down heay");
writeData("2");
}
else if("left".equals(command)){
buffer[0]=(byte)2;
writeData("3");
}
else if("right".equals(command)){
buffer[0]=(byte)3;
writeData("4");
}
else if("break".equals(command)){
buffer[0]=(byte)4;
writeData("0");
}
else if("camera left".equals(command)){
buffer[0]=(byte)5;
//writeData("0");
}
else if("camera right".equals(command)){
buffer[0]=(byte)6;
//writeData("0");
}
else if ("jigsaw1".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw1);
mp.start();
}
else if("jigsaw2".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw2);
mp.start();
}
else if("horn".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.horn);
mp.start();
}
else if("start".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.start);
mp.start();
}
else if("ghosts".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.ghosts);
mp.start();
}
else if("flash on".equals(command)){
if((this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) && !(isLighOn)){
cam = Camera.open();
Parameters params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
cam.setParameters(params);
cam.startPreview();
isLighOn=true;
Log.v("camera","flash on");
}
else{Log.v("camera","flash not exsisted");}
}
else if("flash off".equals(command)){
if(isLighOn){
cam.stopPreview();
cam.release();
isLighOn=false;
Log.v("camera","flash off");
} }
else if("location on".equals(command)){
startService(new Intent(MainActivity.this, LocationService.class));
}
else if("location off".equals(command)){
stopService(new Intent(MainActivity.this, LocationService.class));
}
else if("speed min".equals(command)){
buffer[0]=(byte)7;
}
else if("speed min".equals(command)){
buffer[0]=(byte)8;
}
else if("speed max".equals(command)){
buffer[0]=(byte)9;
}
else{
Log.v(TAG ,"no command recieved");}
if (mOutputStream != null) {
try {
mOutputStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "write failed", e);
}
}
}
//
//
//
//
private void CheckBt() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), "Bluetooth Disabled !",
Toast.LENGTH_SHORT).show();
}
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),
"Bluetooth null !", Toast.LENGTH_SHORT)
.show();
}
}
public void Connect() {
Log.d(TAG, address);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.d(TAG, "Connecting to ... " + device);
Toast.makeText(this, "Connecting to...", Toast.LENGTH_SHORT).show();
mBluetoothAdapter.cancelDiscovery();
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
Log.d(TAG, "Connection made.");
Toast.makeText(this, "Connection made Successful..", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "Unable to end the connection");
Toast.makeText(this, "Unable to end the connection", Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "Socket creation failed");
Toast.makeText(this, "connection creation failed", Toast.LENGTH_SHORT).show();
}
//beginListenForData();
}
private void writeData(String data) {
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "Bug BEFORE Sending stuff", e);
}
String message = data;
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
Toast.makeText(this, "Data Send Successful..", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.d(TAG, "Bug while sending stuff", e);
Toast.makeText(this, "Data Send Error..", Toast.LENGTH_SHORT).show();
}
}
}

send and receive data via bluetooth

you can say that i'm new in android development, i need some help to synchronize some data in two devices with my application, i have done all necessary things like searching for available devices and pairing and unpairing ... all what i need now is how to make a connection between the two devices and send and receive data, to explain more, i need to select a device from my listview and connect with it, after that lets say that i have a text field and a textview and a button, when i click on the button i need to send the text in the textfield of the first device to the textview of other device and vise-versa.
here is all my code :
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ArrayList<BluetoothDevice> devices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private String tag = "debugging";
protected static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.i(tag, "in handler");
super.handleMessage(msg);
switch (msg.what) {
case SUCCESS_CONNECT:
// DO something
ConnectedThread connectedThread = new ConnectedThread(
(BluetoothSocket) msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), string, 0).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),
"Your device does not support Bluetooth", Toast.LENGTH_LONG)
.show();
} else {
myListView = (ListView) findViewById(R.id.listView1);
BTArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
devices = new ArrayList<BluetoothDevice>();
myListView.setAdapter(BTArrayAdapter);
text = (TextView) findViewById(R.id.text);
onBtn = (Button) findViewById(R.id.turnOn);
onBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
on(v);
}
});
offBtn = (Button) findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
off(v);
}
});
listBtn = (Button) findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
list(v);
}
});
findBtn = (Button) findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
find(v);
}
});
// create the arrayAdapter that contains the BTDevices, and set it
// to the ListView
myListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (myBluetoothAdapter.isDiscovering()) {
myBluetoothAdapter.cancelDiscovery();
}
BluetoothDevice selectedDevice = devices.get(position);
if (pairedDevices.contains(selectedDevice)) {
if (unpairDevice(selectedDevice))
Toast.makeText(getApplicationContext(),
"Device unpaired", Toast.LENGTH_LONG)
.show();
else
Toast.makeText(getApplicationContext(),
"Problem while unpairing device",
Toast.LENGTH_LONG).show();
} else {
if (pairDevice(selectedDevice)) {
Toast.makeText(getApplicationContext(),
"Device paired", Toast.LENGTH_LONG).show();
ConnectThread connect = new ConnectThread(
selectedDevice);
connect.start();
} else
Toast.makeText(getApplicationContext(),
"Problem while pairing device",
Toast.LENGTH_LONG).show();
}
}
});
}
}
// For Pairing
private boolean pairDevice(BluetoothDevice device) {
try {
Log.d("pairDevice()", "Start Pairing...");
Method m = device.getClass()
.getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
return true;
} catch (Exception e) {
return false;
}
}
// For UnPairing
private boolean unpairDevice(BluetoothDevice device) {
try {
Log.d("unpairDevice()", "Start Un-Pairing...");
Method m = device.getClass()
.getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
return true;
} catch (Exception e) {
return false;
}
}
public void on(View view) {
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Bluetooth turned on",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view) {
BTArrayAdapter.clear();
// get paired devices
// pairedDevices.clear();
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for (BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
Toast.makeText(getApplicationContext(), "Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the
// arrayAdapter
devices.add(device);
BTArrayAdapter.add(device.getName() + "\n"
+ device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
Toast.makeText(getApplicationContext(), "Discovery cancelled",
Toast.LENGTH_SHORT).show();
myBluetoothAdapter.cancelDiscovery();
} else {
Toast.makeText(getApplicationContext(), "Discovering new devices",
Toast.LENGTH_SHORT).show();
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(
BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view) {
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(), "Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(bReceiver);
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
Log.i(tag, "construct");
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server
// code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.i(tag, "get socket failed");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
myBluetoothAdapter.cancelDiscovery();
Log.i(tag, "connect - run");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(tag, "connect - succeeded");
} catch (IOException connectException) {
Log.i(tag, "connect failed");
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) {
}
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
}

How to connect a mobile and a printer via bluetooth in android?

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)

Categories

Resources