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.
Related
I am trying to send an image file through android using a server socket. I have used AsyncTask class on the client side and created a TransferFile class to send the file. I am getting a NO SUCH FILE OR DIRECTORY exception while creating the file on client's side. The code is attached below.
Permissions.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
TransferFile class.
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
public class TransferFile extends IntentService{
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.apposite.wifip2p.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public TransferFile(){
super("TransferFile");
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
Toast.makeText(this, "Client Socket Intent Handled.", Toast.LENGTH_SHORT).show();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
Toast.makeText(context, "inside ACTION_SEND_FILE.", Toast.LENGTH_SHORT).show();
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Toast.makeText(context, "Client Socket Connected: "+socket.isConnected(), Toast.LENGTH_SHORT).show();
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
}
catch (FileNotFoundException e) {
}
MainActivity.copyFile(is, stream);
} catch (IOException e) {
Toast.makeText(context, "File can't be copied to client.", Toast.LENGTH_SHORT).show();
} finally {
if(socket.isConnected()){
try {
socket.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
}
}
MainActivity class
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener{
WifiP2pManager wifi;
private WifiP2pInfo info;
ListView listViewPeer;
WifiP2pManager.Channel channel;
IntentFilter intentFilter = new IntentFilter();
Button discover, send;
List<WifiP2pDevice> peersList;
List<String> peersNameList;
BroadcastReceiver receiver = null;
ProgressDialog progressDialog = null;
boolean isConnected = false;
protected static final int CHOOSE_FILE_RESULT_CODE = 20;
Intent serviceIntent;
boolean isHost = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
listViewPeer = (ListView) findViewById(R.id.ListViewPeer);
discover = (Button) findViewById(R.id.btnDiscover);
send = (Button) findViewById(R.id.btnGallery);
wifi = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = wifi.initialize(this, getMainLooper(), null);
receiver = new WifiP2pBroadcastReceiver(wifi, channel, this);
peersList = new ArrayList<>();
peersNameList = new ArrayList<>();
discover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
progressDialog = ProgressDialog.show(MainActivity.this, "Press back to cancel", "finding peers", false,
true, new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if(peersList.size()==0)
Toast.makeText(MainActivity.this, "Peer Not Found.", Toast.LENGTH_SHORT).show();
}
});
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 15000);
wifi.discoverPeers(channel, new WifiP2pManager.ActionListener(){
#Override
public void onSuccess() {
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Peer Discovery failed.", Toast.LENGTH_SHORT).show();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
}
});
refreshList();
listViewPeer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!isConnected)
connect(position);
else
disconnect();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
}
});
if(!isConnected)
send.setVisibility(View.GONE);
else
send.setVisibility(View.VISIBLE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
Uri uri = data.getData();
serviceIntent = new Intent(this, TransferFile.class);
serviceIntent.setAction(TransferFile.ACTION_SEND_FILE);
serviceIntent.putExtra(TransferFile.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(TransferFile.EXTRAS_GROUP_OWNER_ADDRESS, info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(TransferFile.EXTRAS_GROUP_OWNER_PORT, 8988);
this.startService(serviceIntent);
Toast.makeText(this, "TransferFile should start.", Toast.LENGTH_SHORT).show();
}
public void connect(int position) {
final WifiP2pDevice device = peersList.get(position);
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
wifi.connect(channel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Connect failed. Retry.", Toast.LENGTH_SHORT).show();
}
});
}
public void disconnect() {
send.setVisibility(View.GONE);
wifi.removeGroup(channel, new WifiP2pManager.ActionListener() {
#Override
public void onFailure(int reasonCode) {
Toast.makeText(MainActivity.this, "Device disconnecting failed.", Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess() {
}
});
}
#Override
public void onResume() {
super.onResume();
registerReceiver(receiver, intentFilter);
send.setVisibility(View.GONE);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onDestroy() {
super.onStop();
if(isHost)
stopService(serviceIntent);
}
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
peersList.clear();
peersList.addAll(peers.getDeviceList());
refreshList();
}
public void refreshList(){
peersNameList.clear();
if(peersList.size()!=0){
for(int i=0;i<peersList.size();i++){
peersNameList.add(i, peersList.get(i).deviceName);
}
}
else
send.setVisibility(View.GONE);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, peersNameList);
listViewPeer.setAdapter(arrayAdapter);
}
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
this.info = info;
if(!isConnected){
Toast.makeText(MainActivity.this, "Device Connected.", Toast.LENGTH_SHORT).show();
isConnected = true;
if (info.groupFormed && info.isGroupOwner) {
isHost = false;
new FileServerAsyncTask(this).execute();
}
else if(info.groupFormed)
send.setVisibility(View.VISIBLE);
else
Toast.makeText(MainActivity.this, "Nothing matters", Toast.LENGTH_SHORT).show();
}
}
public void reset(){
if(isConnected){
Toast.makeText(MainActivity.this, "Device Disconnected.", Toast.LENGTH_SHORT).show();
isConnected = false;
send.setVisibility(View.GONE);
}
}
public class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
Context context;
FileServerAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Socket client = serverSocket.accept();
final File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
// Here
// is
// the
// ERROR
f.createNewFile();
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, "inside post execute." + result, Toast.LENGTH_SHORT).show();
if (result != null) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
#Override
protected void onPreExecute() {
Toast.makeText(context, "Opening a server socket", Toast.LENGTH_SHORT).show();
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
return false;
}
return true;
}
}
And this is my FileServerAsycTask class
public class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
Context context;
FileServerAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Socket client = serverSocket.accept();
final File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
// Here
// is
// the
// ERROR
f.createNewFile();
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, "inside post execute." + result, Toast.LENGTH_SHORT).show();
if (result != null) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
#Override
protected void onPreExecute() {
Toast.makeText(context, "Opening a server socket", Toast.LENGTH_SHORT).show();
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
return false;
}
return true;
}
When on the client side, I try to create a new file using f.createNewFile(), it gives me an error "No such file or directory".
W/System.err: java.io.IOException: open failed: ENOENT (No such file or directory)
W/System.err: at java.io.File.createNewFile(File.java:939)
W/System.err: at com.apposite.wifip2p.MainActivity$FileServerAsyncTask.doInBackground(MainActivity.java:360)
W/System.err: at com.apposite.wifip2p.MainActivity$FileServerAsyncTask.doInBackground(MainActivity.java:310)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err: at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.Posix.open(Native Method)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
W/System.err: at java.io.File.createNewFile(File.java:932)
W/System.err: ... 8 more
The file's name is...
/storage/emulated/0/com.apposite.wifip2pwifip2pshared-1489935211585.jpg
Please help me how to resolve it!
When creating your Intent to pass the Uri over to the service:
Put in in the data facet of the Intent (setData(), not putExtra()), and
Call addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) on the Intent before calling startService()
Your activity has access to this content; without these changes, your service will not have access to the content.
Also, if your targetSdkVersion is 23 or higher, and you are running on Android 6.0+, you need to handle runtime permissions.
hi guys i am trying to send string from one phone to anther .
1) from one phone(client) i am clicking the paired listview to connect with the anther device(ConnectThread).
2) the second phone which is the server alerts that he has been connected with the device in step 1(AcceptThread).
3) after he get connected he start a new managerconnection thread and send along a string(in AcceptThread after connecting is sucessfull it starts a new managerConnection thread .
4) the other phone(after been connected to server it starts a new managerConnecting thread) should get the bytes from function read and put in the log how much bytes he read it seems its not getting any bytes at all can someone tell me what should i changed in my code?
package com.example.barhom.waves;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class BlueToothServerActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private static final String TAG = "buckysmessage";
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private TextView serverStatus;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private AcceptThread mSecureAcceptThread;
private manageConnectedSocket manager ;
// Unique UUID for this application
private static final UUID MY_UUID =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME_SECURE = "waves";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_server);
serverStatus = (TextView) findViewById(R.id.serverStatus);
// 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 {
text = (TextView) findViewById(R.id.text);
onBtn = (Button)findViewById(R.id.turnOn);
onBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),"Listview clicked" ,
Toast.LENGTH_LONG).show();
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
}
}
#Override
protected void onResume() {
super.onResume();
// setting the device to listen for connections(bluetooth)
AcceptThread mSecureAcceptThread= new AcceptThread();
mSecureAcceptThread.start();
}
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) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
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
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
myBluetoothAdapter.cancelDiscovery();
}
else {
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() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
private boolean running = true;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
serverStatus.setText("Server Status: Listing for connection");
Log.d(TAG, "SERVER IS LISING FOR CONNECTIONS");
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = myBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID);
} catch (IOException e) {running = false; }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (running) {
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)
manager=new manageConnectedSocket(socket);
manager.start();
try {
mmServerSocket.close();
Log.d(TAG, "SERVER IS CONNECTED");
String blahblah="asdasds";
manager.write(blahblah.getBytes());
break;
}catch (IOException e) {
break;
}
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
private class manageConnectedSocket extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public manageConnectedSocket(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 = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
} 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);
Log.d(TAG,"WROTE A STRING TO ANTHER PHONE");
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
and the code for the client(the second phone):
package com.example.barhom.waves;
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.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
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.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class BlueToothClientActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
private static final String TAG = "buckysmessage";
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private TextView serverStatus;
private ConnectThread mConnectThread;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private manageConnectedSocket manager ;
// Unique UUID for this application
private static final UUID MY_UUID =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME_SECURE = "waves";
private BluetoothDevice device;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_client);
serverStatus = (TextView) findViewById(R.id.serverStatus);
// 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 {
text = (TextView) findViewById(R.id.text);
onBtn = (Button)findViewById(R.id.turnOn);
onBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Toast.makeText(getApplicationContext(),"adress is"+address,
Toast.LENGTH_LONG).show();
device = myBluetoothAdapter.getRemoteDevice(address);
ConnectThread mConnectThread=new ConnectThread(device );
mConnectThread.start();
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
}
}
#Override
protected void onResume() {
super.onResume();
}
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) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
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
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
myBluetoothAdapter.cancelDiscovery();
}
else {
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() {
// TODO Auto-generated method stub
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;
// 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) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
myBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
manager=new manageConnectedSocket(mmSocket);
manager.start();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
// manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class manageConnectedSocket extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public manageConnectedSocket(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 = new byte[1024]; // buffer store for the stream
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
int read = -1;
final byte[] bytes = new byte[2048];
for (; (read = mmInStream.read(bytes)) > -1;) {
final int count = read;
Log.d(TAG,"String size is"+count);
}
} 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) { }
}
}
}
any help will be great!
thanks.
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.
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 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();
}
}
};