I wrote a WiFi-Direct Code connection and created a connection between them, then I created a ServerSocket on the first side and a Socket on the client side and started sending data between them, the first time I start the application it works Successfully, but when I close the Application and start it again it gives me an exception that says "Connection Refused ECONNREFUSED"
here is my code in the Server side:
package com.example.serverwifidirect;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class BroadcastServer extends BroadcastReceiver
{
#SuppressLint("NewApi")
private WifiP2pManager mManager;
private Channel mChannel;
private Server mActivity;
static boolean temp=false;
Socket client=null;
static boolean isRunning = false;
ServerSocket serverSocket = null;
InetSocketAddress inet;
private void closeConnections()
{
try
{
if(client!=null || serverSocket!=null)
{
if(client!=null)
{
if(client.isInputShutdown()|| client.isOutputShutdown())
{
log("x1");
client.close();
}
if(client.isConnected())
{
log("x2");
client.close();
log("x2.1");
//client.bind(null);
log("x2.2");
}
if(client.isBound())
{
log("x3");
client.close();
}
client=null;
}
}
}
catch(Exception e)
{
log("Error :'(");
e.printStackTrace();
}
}
#SuppressLint("NewApi")
public BroadcastServer(WifiP2pManager manager, Channel channel, Server activity)
{
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
try
{
serverSocket = new ServerSocket(8870);
serverSocket.setReuseAddress(true);
}
catch(Exception e)
{
}
}
#SuppressLint("NewApi")
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action))
{
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED)
{}
else
{}
}
else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
mManager.requestPeers(mChannel, new PeerListListener()
{
#Override
public void onPeersAvailable(WifiP2pDeviceList list)
{
}
});
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action))
{
Bundle b = intent.getExtras();
NetworkInfo info = (NetworkInfo)b.get(WifiP2pManager.EXTRA_NETWORK_INFO);
if(info.isFailover())
{
temp=false;
}
else if(info.isConnected())
{
temp=true;
log("c1");
new Thread(new Runnable(){
public void run()
{
try
{
client =serverSocket.accept();
InputStream input=null;
input = client.getInputStream();
log("q3");
while(BroadcastServer.temp)
{
final int n = input.read();
if(n==100)
{
closeConnections();
mManager.cancelConnect(mChannel, new ActionListener() {
#Override
public void onSuccess()
{
log("done");
mManager.removeGroup(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("group removed");
}
#Override
public void onFailure(int reason)
{
log("fail!!!!!");
}
});
}
#Override
public void onFailure(int reason) {
log("fail");
mManager.removeGroup(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("group removed");
}
#Override
public void onFailure(int reason)
{
log("fail!!!!!");
}
});
}
});
}
log("q4");
if(n==-1)
{
log("n = -1");
break;
}
log("n= "+n);
mActivity.runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(mActivity.getBaseContext(), "--"+n, Toast.LENGTH_SHORT).show();
}
});
}
log("After loop");
}
catch(Exception e)
{
}
}
});
mActivity.runOnUiThread(new Runnable(){
public void run()
{
//Toast.makeText(mActivity, "Connected to WiFi-Direct!", Toast.LENGTH_SHORT).show();
}
});
log("c2");
}
else if(info.isConnectedOrConnecting())
{
temp=false;
}
else if(!info.isConnected())
{
temp=false;
try
{
if(client!=null || serverSocket!=null)
{
if(client!=null)
{
if(client.isInputShutdown()|| client.isOutputShutdown())
{
log("x1");
client.close();
}
if(client.isConnected())
{
log("x2");
client.close();
log("x2.1");
//client.bind(null);
log("x2.2");
}
if(client.isBound())
{
log("x3");
client.close();
}
client=null;
}
}
}
catch(Exception e)
{
log("Error :'(");
e.printStackTrace();
}
mManager.clearLocalServices(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("success");
}
#Override
public void onFailure(int reason)
{
}
});
}
}
else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action))
{
log("Device change Action!");
}
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
this code is in the Server side, and the following code is in the Client side:
package com.example.wifidirect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
#SuppressLint("NewApi")
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver
{
static WifiP2pDevice connectedDevice = null;
boolean found=false;
boolean connected = false;
private WifiP2pManager mManager;
private Channel mChannel;
Button find = null;
Activity mActivity = null;
#SuppressLint("NewApi")
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel, WifiDirect activity)
{
super();
this.mManager = manager;
this.mChannel = channel;
mActivity = activity;
find = (Button)mActivity.findViewById(R.id.discover);
}
#SuppressLint("NewApi")
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action))
{
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED)
{
// Wifi Direct is enabled
} else
{
// Wi-Fi Direct is not enabled
}
}
else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
mManager.requestPeers(mChannel, new PeerListListener()
{
#Override
public void onPeersAvailable(WifiP2pDeviceList list)
{
WifiP2pDevice d = null;
if(!found)
{
Log.d("status", "2");
Collection<WifiP2pDevice>li = list.getDeviceList();
ArrayList<WifiP2pDevice> arrayList = new ArrayList<WifiP2pDevice>();
Iterator<WifiP2pDevice>peers = li.iterator();
while(peers.hasNext())
{
WifiP2pDevice device = peers.next();
arrayList.add(device);
}
for(int i=0;i<arrayList.size();i++)
{
log("xxx");
log(arrayList.get(i).deviceName);
if(arrayList.get(i).deviceName.equalsIgnoreCase("Android_144b"))
{
d = arrayList.get(i);
arrayList.clear();
found = true;
break;
}
}
}
if(d!=null)
{
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = d.deviceAddress;
if(!connected)
{
mManager.connect(mChannel, config, new ActionListener()
{
#Override
public void onSuccess()
{
connected = true;
}
#Override
public void onFailure(int reason)
{
connected=false;
mManager.cancelConnect(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
Log.d("status", "success on cancelConnect()");
}
#Override
public void onFailure(int reason)
{
Log.d("status", "Fail on cancelConnect()");
}
});
}
});
}
}
}
});
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action))
{
Bundle b = intent.getExtras();
NetworkInfo info = (NetworkInfo)b.get(WifiP2pManager.EXTRA_NETWORK_INFO);
if(info.isFailover())
{
connected=false;
Log.d("status", "connection failure!");
}
else if(info.isConnected())
{
connected=true;
find.setEnabled(false);
Log.d("status", "connection is Connected!");
}
else if(info.isConnectedOrConnecting())
{
connected=false;
log("Connecting !!!");
}
else if(!info.isConnected())
{
if(connected)
{
//closeConnections();
connected=false;
}
find.setEnabled(true);
mManager.removeGroup(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("Success disconnect");
}
#Override
public void onFailure(int arg0)
{
log("Fail disconnect");
}
});
}
}
else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action))
{}
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
And this is the class Connection
package com.example.wifidirect;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
#SuppressLint("NewApi")
public class Connection
{
boolean found = false;
OutputStream out=null;
Socket socket = null;
boolean connected =false;
WiFiDirectBroadcastReceiver mReceiver=null;
WifiDirect instance=null;
#SuppressLint("NewApi")
Channel mChannel=null;
WifiP2pManager mManager=null;
public void sendMessage(int msg)
{
try
{
out.write(msg);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Connection(WiFiDirectBroadcastReceiver mReceiver,WifiDirect instance,Channel mChannel,WifiP2pManager mManager) throws UnknownHostException, IOException
{
this.instance=instance;
this.mReceiver=mReceiver;
this.mChannel=mChannel;
this.mManager= mManager;
socket = null;
Button send = (Button)instance.findViewById(R.id.send);
send.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try
{
log("z1");
if(socket==null)
{
log("z2");
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
log("z3");
socket= new Socket("192.168.49.1",8870);
socket.setReuseAddress(true);
log("z4");
out = socket.getOutputStream();
connected = true;
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
t.setDaemon(false);
t.start();
}
new Thread(new Runnable()
{
public void run()
{
log("trying to Send !");
while(!connected);
sendMessage(10);
log(" Data sent !");
}
}).start();
}
catch(Exception e)
{
log("exception_1");
e.printStackTrace();
log("exception_2");
log(e.getMessage());
}
}
});
}
public void closeConnections()
{
try
{
if(out!=null)
{
out.close();
out=null;
}
if(socket!=null)
{
socket.shutdownInput();
socket.shutdownOutput();
if(socket.isInputShutdown()|| socket.isOutputShutdown())
{
socket.close();
}
if(!socket.isClosed())socket.close();
}
if(socket.isConnected())
{
socket.close();
}
socket=null;
}
catch(Exception e)
{
Log.d("status", "error :( ");
e.printStackTrace();
}
}
public void connect()
{
mManager.discoverPeers(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
Log.d("status", "1");
}
#Override
public void onFailure(int reason)
{
mManager.cancelConnect(mChannel, new ActionListener() {
#Override
public void onSuccess()
{
Log.d("status", "success cancel connect");
connect();
}
#Override
public void onFailure(int reason)
{
Log.d("status", "failed cancel connect");
}
});
}
});
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
finally this is my main Activity class
package com.example.wifidirect;
import java.io.IOException;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class WifiDirect extends Activity
{
WifiP2pManager mManager;
Channel mChannel;
WiFiDirectBroadcastReceiver mReceiver;
PeerListListener listener = null;
IntentFilter mIntentFilter;
String host;
Connection con=null;
PeerListListener myPeerListListener;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.wifi_direct);
StrictMode.enableDefaults();
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
try {
con = new Connection(mReceiver,this,mChannel,mManager);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final Button discover = (Button)findViewById(R.id.discover);
discover.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
con.connect();
}
});
}
#Override
protected void onResume()
{
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
}
#SuppressLint("NewApi")
#Override
protected void onDestroy()
{
super.onDestroy();
con.sendMessage(100);
unregisterReceiver(mReceiver);
}
#SuppressLint("NewApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
String action = data.getAction();
if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
if (mManager != null)
{
mManager.requestPeers(mChannel, myPeerListListener);
}
}
}
void log(String s)
{
Log.d("status ", s);
}
}
Just in case someone run into similar issue, I was having similar problem of seeing connection refused messages sometimes and fixed this by allowing client thread,to sleep for a second to prevent race conditions. The idea is that once two devices are connected, the ConnectionListener gets fired. After that, both server\client will launch server thread or client thread based on the role. A group owner will issue a server thread and group member will launch a client thread. Sometimes, the client thread will launch before the server thread and those fail to find a server to connect to. So, I added a one-second-sleep for the client to ensure that server thread gets registered first. Now, I don't see the problem happening. Here is my code:
private WifiP2pManager.ConnectionInfoListener connectionListener
= new WifiP2pManager.ConnectionInfoListener(){
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
// TODO Auto-generated method stub
Log.i(TAG, "onConnectionInfoAvailable");
//String groupOwnerAddress = info.groupOwnerAddress.getHostAddress();
if (info.groupFormed && info.isGroupOwner) {
// Do whatever tasks are specific to the group owner.
// One common case is creating a server thread and accepting
// incoming connections.
Log.i(TAG, "Connected as group owner...");
WifiDirectServerThread wifiDirectServerThread = new WifiDirectServerThread(context);
wifiDirectServerThread.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case,
// you'll want to create a client thread that connects to the group
// owner.
Log.i(TAG, "Connected as group member...");
Log.i(TAG, "Sleep before launching client thread to avoid race conditions...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WifiDirectClientDataThread wifiDirectClientThread = new WifiDirectClientDataThread(info.groupOwnerAddress.getHostAddress(), PORT, context);
wifiDirectClientThread.start();
}
}
};
Related
how can i keep the socket active on the service, when i close the app it disconnected, from node, i call it from the main activity, with startService(new Intent(this, sys_service.class)); the socket its fine while the app its active
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
public class sys_service extends Service {
Socket mSocket;
TelephonyManager manager;
JSONObject chat_response;
private Handler mHandler = new Handler();
String msg_over;
{
try {
mSocket = IO.socket("http://xxxx:8001");
} catch (URISyntaxException e) {
Toast.makeText(this, "refused", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Toast.makeText(this,"Service Active :)", Toast.LENGTH_LONG ).show();
run_app();
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service stop :)", Toast.LENGTH_LONG ).show();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent){
run_app();
return null;
}
public Socket getSocket() {
return mSocket;
}
public void run_app() {
mSocket.connect();
manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
final JSONObject uidJson = new JSONObject();
String real = manager.getDeviceId();
try {
uidJson.put("uid", real);
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.on("connect", new Emitter.Listener() {
public void call(Object... args) {
mSocket.emit("uid", uidJson);
}
});
mSocket.on("chat", new Emitter.Listener() {
public void call(Object... args) {
String chat_msg = args[0].toString();
try {
chat_response = new JSONObject(chat_msg);
} catch (JSONException e) {
e.printStackTrace();
}
msg_over = chat_response.optString("msg");
final JSONObject chat = new JSONObject();
try {
chat.put("msg", "all fine");
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("test", msg_over);
//Toast.makeText(StartActivity.this, msg, Toast.LENGTH_SHORT).show(); Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
Log.d("chat", msg_over);
}
});
}
}
I am trying to connect the Bluetooth device (BT headphone) programmatically with my android app. The issue I am facing is in for first couple of attempts it fails to connect the device and says "Pairing Rejected". then after it connects successfully.
Here's my code:
package rockwellcollins.bluetooth_pairing_siu;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
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.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
public ServerSocket serverSocket;
public BluetoothA2dp btA2dp;
BluetoothAdapter mBluetoothAdapter;
private BluetoothSocket mSocket = null;
private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public InetAddress serverAddr,serverAddrConnected;
public Socket socket,socketConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.getProfileProxy(this, new BluetoothProfile.ServiceListener() {
#Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
Log.i("oncreate","Bluetooth Service connected.\n");
btA2dp = (BluetoothA2dp) proxy;
}
#Override
public void onServiceDisconnected(int profile) {
Log.i("oncreate", "Bluetooth Service disconnected.\n");
}
}, BluetoothProfile.A2DP);
Log.i("oncreate", "going to start thread.\n");
Thread fst = new Thread(new ServerThread());
fst.start();
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
public class ServerThread implements Runnable
{
String[] strLine;
#Override
public void run() {
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
serverSocket = new ServerSocket(4500);
while(true) {
Log.i("inrun","in run method");
Socket client = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = in.readLine();
strLine = line.split(";");
Log.i("ServerThread", "Line is: " + strLine[1]);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(strLine[1]);
if(strLine[0].contains("connect")) {
pairDevice(device);
}
else if(strLine[0].contains("unpair"))
{
Log.i("run","Going to unpair device");
unpairDevice(device, strLine[2]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void pairDevice(BluetoothDevice device) {
try {
if(device.getBondState() == BluetoothDevice.BOND_NONE) {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
Log.d("pairdevice", String.valueOf(device.getBondState()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class FinalThread implements Runnable{
String strMsg = "";
public FinalThread(String msg)
{
strMsg = msg;
}
#Override
public void run() {
try {
serverAddr = InetAddress.getByName("10.240.8.23");
socket = new Socket(serverAddr,5500);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(strMsg);
out.flush();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void unpairDevice(BluetoothDevice device, String seatInfo) {
try {
if(device.getBondState() == BluetoothDevice.BOND_BONDED) {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
}
Thread sThread = new Thread(new ConnectThread(seatInfo));
sThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public class ConnectThread implements Runnable{
String strSeat = "";
public ConnectThread(String seat){
strSeat = seat;
}
#Override
public void run() {
try {
Log.i("ConnectThread","Going to connect");
serverAddr = InetAddress.getByName("10.240.8.23");
socket = new Socket(serverAddr,5500);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println("startpairconnect;" + strSeat);
out.flush();
socket.close();
Log.i("ConnectThread","Send message back for connect");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice deviceBT = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
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) {
ShowToast("Paired");
connectA2dp(deviceBT);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
ShowToast("Unpaired");
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDING){
ShowToast("Pairing rejected, trying again");
pairDevice(deviceBT);
}
}
}
};
private void connectA2dp(final BluetoothDevice btdevice) {
Method connect;
String strMessage = "";
try {
connect = BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class);
//Log.i("connecta2dp","get connect method " + connect);
} catch (NoSuchMethodException ex) {
Log.e("connectA2dp", "Unable to find connect(BluetoothDevice) method in BluetoothA2dp proxy.");
return;
}
connect.setAccessible(true);
try {
//Log.i("connecta2dp","before invoke" );
connect.invoke(btA2dp, btdevice);
if(btdevice.getBondState() == BluetoothDevice.BOND_BONDED)
strMessage = "success;" + btdevice.getAddress();
else
strMessage = "failure";
Thread fThread = new Thread(new FinalThread(strMessage));
fThread.start();
//Log.i("connecta2dp", "after invoke");
} catch (InvocationTargetException ex) {
Log.e("connectA2dp", "Unable to invoke connect(BluetoothDevice) method on proxy. " + ex.toString());
} catch (IllegalAccessException ex) {
Log.e("connectA2dp", "Illegal Access! " + ex.toString());
}
}
#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);
}
public void ShowToast(String message)
{
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Little explanation of the scenario which rejects the pairing for couple of times class will start a thread on it's onCreate method.Now this thread will continuously monitor the port for a incoming message and once it gets the message it'll extract the mac address of the headphones from it. Once it get the mac address it'll try to connect it programmatically where it fails for couple of attempts and then connects it successfully.
Thanks
This weekend, I decided to work with arduino. Currently I am facing a difficulty in connecting my phone to Arduino. I have successfully passed the address of the module to ledControl.java. I am using AsyncTask to carry out the operation for connecting to arduino. Can anyone pls guide me.
NOTE: m unable to connect with any of the devices having bluetooth.
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;
import java.io.IOException;
import java.util.UUID;
/**
* Created by milind on 09/01/16.
*/
public class ledControl extends Activity {
Button btnOn, btnOff, btnDis;
SeekBar brightness;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.led_control);
//receive the address of the bluetooth device
Intent newint = getIntent();
address = newint.getStringExtra("address");
Log.wtf("ledControl Address:", address); // Log value received.
//view of the ledControl layout
//call the widgtes
btnOn = (Button) findViewById(R.id.on);
btnOff = (Button) findViewById(R.id.off);
//btnDis = (Button)findViewById(R.id.button4);
//brightness = (SeekBar)findViewById(R.id.seekBar);
new ConnectBT().execute(address);
btnOn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
btnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("1".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("2".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private class ConnectBT extends AsyncTask<String, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
Log.i("ledControl","Device Connecting");
//progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(String... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
Log.wtf("ledControl","AsyncTask Called");
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
Log.wtf("AsyncTask:",address);
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(devices[0]);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
Log.i("ledControl:","Connected to Device.");
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again."); // This toast is produced everytime.
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
//progress.dismiss();
}
}
private void msg(final String s)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
});
}
}
In the end, I get this Toast message. "Connection Failed. Is it a SPP Bluetooth? Try again."
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)
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.