TCP in Android - ObjectOutputStream writeObject failure - java

I'm trying to send an Object from my phone to my PC(Windows) using a TCP socket via WiFi. When I try the same code between two PCs, it works without any error. But when I put the client code to the android device, it fails to send date using writeObject method. But writeUTF command works. It gives the "Software caused connection abort: recv failed" error. Below is the Code. Please help..
Server(in PC):
public class Test {
public static void main(String arg[]) {
ServerSocket serverSocket = null;
Socket socket = null;
ObjectInputStream in = null;
ObjectOutputStream out = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
System.out.println("ip: " + socket.getInetAddress());
Message msg = (Message) in.readObject(); //Message captured from chat client.
System.out.println(msg.type + " message received from " + msg.sender + " Containing " + msg.content);
out.writeObject(new Message("Ack", "Server", "Message Received", "Client"));
out.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Client (in Android Device):
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bb=(Button)findViewById(R.id.button1);
bb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Send().execute();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class Send extends AsyncTask<Void, Void, Void> {
Socket socket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.43.92", 8888); //use the IP address of the server
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
out.writeObject(new Message("Chat", "Server", "Hello World", "Server")); //This method is used to write something to the server.
out.flush();
Message msg = (Message) in.readObject();
System.out.println(msg.type + " message received from " + msg.sender + " Containing " + msg.content);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
//setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//showDialog("Downloaded " + result + " bytes");
}
}
}
Message(in Both Sides):
public class Message implements Serializable{
private static final long serialVersionUID = 1L;
public String type, sender, content, recipient;
public Message(String type, String sender, String content, String recipient){
this.type = type; this.sender = sender; this.content = content; this.recipient = recipient;
}
#Override
public String toString(){
return "{type='"+type+"', sender='"+sender+"', content='"+content+"', recipient='"+recipient+"'}";
}
}

Is the network between the client and server setup properly via your WiFi? Download one of those ping & telnet test apps and use it to test your network connection.
Telnet is a useful TCP debugging app. If you have a server listening on 11.22.33.44 port 1234, you should be able to telnet 11.22.33.44 1234

Maybe, you need to add this functions into Message class:
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
stream.writeObject(type);
stream.writeObject(sender);
stream.writeObject(content);
stream.writeObject(recipient);
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
type = (String) stream.readObject();
sender = (String) stream.readObject();
content = (String) stream.readObject();
recipient = (String) stream.readObject();
}
http://developer.android.com/reference/java/io/Serializable.html

Related

file sent to null (empty) by using socket in android studio

Server side code
public class MainActivity extends AppCompatActivity {
TextView infoIp, infoPort;
static final int SocketServerPORT = 8080;
ServerSocket serverSocket;
ServerSocketThread serverSocketThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoIp = (TextView) findViewById(R.id.infoip);
infoPort = (TextView) findViewById(R.id.infoport);
infoIp.setText(getIpAddress());
serverSocketThread = new ServerSocketThread();
serverSocketThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
public class ServerSocketThread extends Thread {
#Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}});
while (true) {
socket = serverSocket.accept();
FileTxThread fileTxThread = new FileTxThread(socket);
fileTxThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class FileTxThread extends Thread {
Socket socket;
FileTxThread(Socket socket){
this.socket= socket;
}
#Override
public void run() {
File file = new File(
Environment.getExternalStorageDirectory(),
"graphs.txt");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
OutputStream os = socket.getOutputStream();
os.write(bytes, 0, bytes.length);
os.flush();
socket.close();
final String sentMsg = "File sent to: " + socket.getInetAddress();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
sentMsg,
Toast.LENGTH_LONG).show();
}});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Client Side Code :
public class MainActivity extends AppCompatActivity {
EditText editTextAddress;
Button buttonConnect;
TextView textPort;
static final int SocketServerPORT = 8080;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText) findViewById(R.id.address);
textPort = (TextView) findViewById(R.id.port);
textPort.setText("port: " + SocketServerPORT);
buttonConnect = (Button) findViewById(R.id.connect);
buttonConnect.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
ClientRxThread clientRxThread =new ClientRxThread(editTextAddress.getText().toString(),SocketServerPORT);
clientRxThread.start();
}});
}
private class ClientRxThread extends Thread {
String dstAddress;
int dstPort;
ClientRxThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
File file = new File(Environment.getExternalStorageDirectory(),"graphs.txt");
byte[] bytes = new byte[8192];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
bos.close();
socket.close();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
"Finished",
Toast.LENGTH_LONG).show();
}});
} catch (IOException e) {
e.printStackTrace();
final String eMsg = "Something wrong: " + e.getMessage();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eMsg,
Toast.LENGTH_LONG).show();
}});
} finally {
if(socket != null){
try {
System.out.println("socket not null "+socket);
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Error shoews in client side :
E/AndroidRuntime: FATAL EXCEPTION: Thread-2648
Process: com.example.moraya.socketfileserverside1, PID: 30793
java.lang.ArrayIndexOutOfBoundsException: length=8192; regionStart=0; regionLength=-1
at java.util.Arrays.checkOffsetAndCount(Arrays.java:1719)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:135)
hi sir, i am trying to transfer file client to server by using socket, but after click on connect button client side application says unfortunately application has stopped and also the empty text file send into the sdcard.
please help me what is the error and how to solve it.

How to transmit of stream of data to multiple devices using sockets in Android?

I am trying to transmit a continuous stream of data to multiple devices over a portable hotspot connection using sockets.
I am facing two problems:
The message only gets displayed to the client AFTER all the messages are displayed in msg TextView on the server end. So if I use an infinite while(true) loop instead of for(int i = 0; i < 1000; i++), in ServerSocketReplyThread, the message never gets transmitted, and the client eventually crashes
I am unable to connect another client to the server until all the messages have been transmitted to the first client.
How do I structure the code to ensure simultaneous, real-time transmission to multiple clients?
Here's what the code looks like:
I am using an activity called Transmit activity, where I am instantiating the msg Textview, which replays the sent messages, and a server object.
msg = (TextView) findViewById(R.id.server_replayed_messages);
Server server = new Server(this);
The Server class is as follows:
public class Server {
TransmitActivity activity;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;
ArrayList<Socket> socketList = new ArrayList<Socket>();
public Server(TransmitActivity a) {
this.activity = a;
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public int getPort() {
return socketServerPORT;
}
public void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
int count = 0;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread =
new SocketServerReplyThread(socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
for(int i = 0; i < 1000; i++) {
String msgReply = DateFormat.getDateTimeInstance().format(new Date());
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.flush();
message += "replayed: " + msgReply + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong in SocketServerReplyThread! " + e.toString() + "\n";
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
}
}
}
}
On the client side I have a ReceiveActivity, where I am using the following code when a "Connect" button is clicked:
Client myClient = new Client(editTextAddress.getText()
.toString(), Integer.parseInt(editTextPort
.getText().toString()), response);
myClient.execute();
The Client class is as follows:
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse = textResponse;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice: inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
Any help would be much appreciated.

How to get client ip which is connected to android mobile hotspot in java scoket?

Is there any way to get client ip which is connected to android hotspot in java scoket, i have to send input values to client ip on submit
Here what i tried :
private class AttemptSubmit {
public ArrayList<String> getClientList1() {
ArrayList<String> clientList = new ArrayList<>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] clientInfo = line.split(" +");
String mac = clientInfo[3];
if (mac.matches("..:..:..:..:..:..")) {
clientList.add(clientInfo[0]);
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(clientInfo[0], 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(editUsername.getText().toString());
dataOutputStream.writeUTF(editPassword.getText().toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
} catch (java.io.IOException aE) {
aE.printStackTrace();
return null;
}
return getClientList1();
}
Submit action :
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptSubmit attemptSubmit= new AttemptSubmit();
attemptSubmit.getClientList1();
}
});
The problem is, when i click on submit button i'm getting this error "Unfortunately,Aqua has stooped."

connecting to socket over wifi - android

I am trying to use sockets in Android to connect over wifi to some UDP port (some_port) on a machine in my local network whose ip is some_ip.
When I run
socket = new Socket(some_ip, some_port);
I get no message error but the program does not seem to read this line and I can't log the error when surrounding with try/catch.
How can I debug that ?
Edit 1 : here's my try/catch
try{
socket = new Socket(some_ip, some_port);
}
catch(ConnectException e) {
e.printStackTrace();
}
Edit 2 : here's the entire code
private void getUDPData() throws IOException {
class ProcessUPDTask extends AsyncTask<String, Void, Socket> {
private Exception exception;
private Socket socket;
public ProcessUPDTask() throws IOException {
}
private void runThread(){
new Thread() {
public void run() {
Toast.makeText(activity, "Own Message", Toast.LENGTH_LONG).show();
}
}.start();
}
protected Socket doInBackground(String... urls) {
try {
try{
socket = new Socket(some_ip, some_port);
socket.setSoTimeout(1500);
}
catch(IOException e) {
e.printStackTrace();
}
Log.d("TAG","this line is reached");
while(true){
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
this.exception = e;
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Socket socket) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
new ProcessUPDTask().execute();
}
Try this
try {
Socket socket = new Socket(IP_ADDRESS, PORT);
socket.setSoTimeout(1500);
} catch (IOException ex) {
Log.e("Connection Error",String.valueOf(ex));
}
Replace your code with this and wait some seconds(60 sec for now) you can see the error toast..
private void getUDPData() throws IOException {
class ProcessUPDTask extends AsyncTask<String, Void, Socket> {
private Exception exception;
private Socket socket;
public ProcessUPDTask() throws IOException {
}
protected Socket doInBackground(String... urls) {
try {
try {
socket = new Socket("192.168.1.101", 1234);
socket.setSoTimeout(1500);
} catch (IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
});
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Reached", Toast.LENGTH_LONG).show();
}
});
while (true) {
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
this.exception = e;
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Socket socket) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
new ProcessUPDTask().execute();
}
You can configure this and use transData() between connectivity.
private void transData(int sending_msg_int) throws IOException {
String sending_msg = Integer.toString(sending_msg_int);
SocketAddress socketAddress = new InetSocketAddress(ip, Data.Port);
DatagramSocket ds = new DatagramSocket();
byte[] buffer = sending_msg.getBytes();
DatagramPacket dp = new DatagramPacket(buffer, buffer.length,
socketAddress);
ds.send(dp);
ds.close();
}

Second connection to Bluetooth device fails in Android

I'm trying to establish a Bluetooth connection in Android 4.4 but the connect method of BluetoothSocket seems to be working strangely. My app can assume the device is already bonded, so I can connect via MAC address. The thing is that it connects perfectly and immediately the first time the device is bonded, but if I relaunch it, the connection isn't established and a timeout occurs. I do this inside a while loop until it connects, but it takes too long for a real solution or it doesn't work at all. Here's a sample of my code:
public class BluetoothManager{
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket socket;
private OutputStream output;
private InputStream input;
public BluetoothManager() {
/***************/
/* Constructor */
/***************/
// lock = new Object();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
public boolean turnOnBluetooth() {
/**************************************/
/* Turn on Bluetooth an notify result */
/**************************************/
// check if bluetooth is supported
if (bluetoothAdapter == null) {
return (false);
} else {
// enable Bluetooth if not enabled yet
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
}
while (!bluetoothAdapter.isEnabled()) {
Log.i("Debug", "Waiting for bluetooth to turn on");
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
return (true);
}
}
public boolean turnOffBluetooth() {
/***************************************/
/* Turn off Bluetooth an notify result */
/***************************************/
// check if bluetooth is supported
if (bluetoothAdapter == null) {
return (false);
} else {
// disable Bluetooth if not enabled yet
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
}
while (bluetoothAdapter.isEnabled()) {
Log.i("Debug
Thread.sleep(500);
} catch (Exception e) {
}
}
return (true);
}
}
public boolean configureBluetooth(String MACaddress) {
/***********************************************************************/
/* Configures to the specified bluetooth device and returns the result */
/***********************************************************************/
Log.i("Debug", "Connecting to Bluetooth Device");
bluetoothDevice = bluetoothAdapter.getRemoteDevice(MACaddress);
return (true);
}
#SuppressLint("NewApi")
public void createSocket() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
final UUID serialUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
socket = null;
output = null;
input = null;
Method m = bluetoothDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class });
socket = (BluetoothSocket)m.invoke(bluetoothDevice, 1);
}
#SuppressLint("NewApi")
public void connect() throws IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
/************************************/
/* Connects to the bluetooth device */
/************************************/
Log.i("Debug", "en connect");
while (!socket.isConnected()) { // we try until the connection is established
try {
socket.connect();
output = socket.getOutputStream();
input = socket.getInputStream();
} catch (IOException e) {
Log.i("Depuración", "Connection not established. Another run : "+e);
try {
Thread.sleep(1000);
} catch (Exception e1) {
}
}
}
}
public void terminateConnection() throws IOException {
Log.i("Debug", "terminating connection");
if(output!=null){
Log.i("Debug", "output!=null - stop streaming");
stopStreaming();
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
if(input!=null){
Log.i("Debug", "input!=null");
input.close();
input=null;
}
if(output!=null){
Log.i("Depuración", "output!=null");
output.close();
output = null;
}
if(socket!=null){
Log.i("Debug", "socket!=null");
socket.close();
socket=null;
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
turnOffBluetooth();
try {
Thread.sleep(100);
} catch (Exception e) {
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
System.gc();
}
If I call this methods from my MainActivity, it works, but only the first time the device is bonded. If I launch the app again I get an exception trying to connect to the device in:
socket.connect();
I suspect it has something to do with the way I terminate the connection, but I can't figure it out. Here's the sequential call of the methods:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothManager = new BluetoothManager();
try {
bluetoothManager.terminateConnection();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
bluetoothManager.turnOffBluetooth();
bluetoothManager.turnOnBluetooth();
boolean configured = false;
while (!configured) {
Log.i("Debug", "Configuration Attemp");
configured = bluetoothManager.configureBluetooth(MACaddress);
}
Log.i("Debug", "Bluetooth Configured");
try {
bluetoothManager.createSocket();
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.i("Depuración", "Socket created");
try {
bluetoothManager.connect();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("Debug", "Connected!!!!");
protected void onPause() {
Log.i("Debug", "On pause");
// TODO Auto-generated method stub
try {
bluetoothManager.terminateConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bluetoothManager = null;
System.gc();
super.onPause();
};
I've been trying to solve this for days and I still can't find a reason.
Well I'm not a Pro on this, but it looks like you should call bluetoothManager.terminateConnection(); when app is closing, lets say onDestroy, but not onCreate; I also had problems to connect, if previous connection was not terminated correctly. just try add this method to your main activity:
#Override
public void onDestroy(){
if (bluetoothManager != null){
bluetoothManager.terminateConnection();
}
super.onDestroy();
}
hope that helps.

Categories

Resources