NFC Pair Bluetooth Connection Android Bidirectional Socket issue - android

Hi I want to connect two android phones application using Bluetooth and NFC.
I am currently sending the UUID and the MAC over NFC from one device to another;
The issue is that when it comes to opening the sockets I get the following error:
java.io.IOException: Service discovery failed
On the client side of the application:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluerec);
JSONObject oneObject = null;
//NFC
Intent intent = getIntent();
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage message = (NdefMessage)messages[0];
NdefRecord record = message.getRecords()[0];
payload = new String(record.getPayload());
String add = null;
String uuid = null;
try {
oneObject = new JSONObject(payload);
add = oneObject.getString("MAC");
uuid = oneObject.getString("UUID");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(payload);
UUID uuid2 = UUID.fromString(uuid);
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
this.bluetooth = bluetooth;
BluetoothDevice device = bluetooth.getRemoteDevice(add);
connectToServerSocket(device, uuid2 );
}
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid);
// Block until server connection accepted.
clientSocket.connect();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = clientSocket;
} catch (IOException e) {
Log.e("BLUETOOTH", "Blueooth client I/O Exception", e);
}
}
And on the Server side:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Bluetooth
//NFC
jsonObj = getMacAddress();
payload = jsonObj.toString();
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
String mimeType = "application/com.example.cpayvendingcomm";
byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
NdefMessage nfcMessage = new NdefMessage(
new NdefRecord[]
{
// Create the NFC payload.
new NdefRecord(
NdefRecord.TNF_MIME_MEDIA,
mimeBytes,
new byte[0],
payload.getBytes()),
// Add the AAR (Android Application Record)
//NdefRecord.createApplicationRecord("com.paad.nfcbeam")
});
nfcAdapter.setNdefPushMessage(nfcMessage, this);
initBluetooth();
}
private static final int ENABLE_BLUETOOTH = 1;
private void initBluetooth() {
if (!bluetooth.isEnabled()) {
// Bluetooth isn't enabled, prompt the user to turn it on.
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, ENABLE_BLUETOOTH);
} else {
// Bluetooth is enabled, initialize the UI.
initBluetoothUI();
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
this.bluetooth = bluetooth;
startServerSocket(bluetooth);
}
}
private void initBluetoothUI() {
// TODO Auto-generated method stub
}
private ArrayList<BluetoothDevice> deviceList =
new ArrayList<BluetoothDevice>();
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
deviceList.add(remoteDevice);
Log.d(TAG, "Discovered " + remoteDeviceName);
}
};
private BluetoothSocket transferSocket;
private UUID startServerSocket(BluetoothAdapter bluetooth) {
UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c545");
String name = "bluetoothserver";
try {
final BluetoothServerSocket btserver =
bluetooth.listenUsingRfcommWithServiceRecord(name, uuid);
Thread acceptThread = new Thread(new Runnable() {
public void run() {
try {
// Block until client connection established.
BluetoothSocket serverSocket = btserver.accept();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(serverSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = serverSocket;
} catch (IOException e) {
Log.e("BLUETOOTH", "Server connection IO Exception", e);
}
}
});
acceptThread.start();
} catch (IOException e) {
Log.e("BLUETOOTH", "Socket listener IO Exception", e);
}
return uuid;
}
// Listener for messages
private boolean listening = false;
private void listenForMessages(BluetoothSocket socket, StringBuilder incoming) {
listening = true;
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
while (listening) {
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
String result = "";
while ((bytesRead == bufferSize) &&
(buffer[bufferSize-1] != 0)){
result = result + new String(buffer, 0, bytesRead - 1);
bytesRead = instream.read(buffer);
}
result = result + new String(buffer, 0, bytesRead - 1);
incoming.append(result);
}
socket.close();
}
} catch (IOException e) {
Log.e(TAG, "Message received failed.", e);
}
finally {
}
}

Passing the Bluetooth address assumes you are connecting without prior pairing of the Bluetooth devices. Depending on whether you want to pair the two devices or not you can implement it two ways:
No Pairing. Use createInsecureRfcommSocketToServiceRecord() instead of createRfcommSocketToServiceRecord() on the client as described in how to create insecure server connection in Android. Use listenUsingInsecureRfcommWithServiceRecord() on the server.
Pairing with Secure Simple Pairing with passing OOB via NFC. It's a more involved process, beyond what you are asking.

Related

Bluetooth issue

I am building an app which connects through bluetooth but the problem is that it is crushing the device when I try to open the activity as the app should transfer the data from arduino to android app and display on it.I am having problem with the default bluetooth device issue when i see it on terminal
Here is the code
public class BlankActivity extends AppCompatActivity {
Button btnOn, btnOff;
TextView txtString, txtStringLength, sensorView0;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
private static String address;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensors_layout);
//Link the buttons and textViews to respective views
btnOn = (Button) findViewById(R.id.buttonOn);
btnOff = (Button) findViewById(R.id.buttonOff);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
sensorView0 = (TextView) findViewById(R.id.sensorView0);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
//txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length(); //get length of data received
//txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, endOfLineIndex); //get sensor value from string between indices 1-5
//String sensor1 = recDataString.substring(6, 10); //same again...
//String sensor2 = recDataString.substring(11, 15);
//String sensor3 = recDataString.substring(16, 20);
sensorView0.setText(" Intensity = " + sensor0 + " Raw "); //update the textviews with sensor values
//sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
//sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
//sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
// strIncom =" ";
dataInPrint = " ";
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
// Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
btnOff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0"); // Send "0" via Bluetooth
Toast.makeText(getBaseContext(), "Measurement Off!!!", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1"); // Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Please Wait ", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(myUUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(MainLayout.EXTRA_ADDRESS);
//create device and set the MAC address //I am having problem here in android monitor
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
// I have problem with this line
****mConnectedThread.write("x");**
}**
#Override
public void onPause() {
super.onPause();
try {
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {
if (btAdapter == null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
This is the crash code when I am facing when I click the button
at de.zmt.photometerapp.BlankActivity$3.onClick(BlankActivity.java:114)

Android VpnService to capture packets won't send packet

I want to the new android (4.0) VpnService interface to implement simple packet capture and analysis. I have successfully capture the packet(IP packet) from the filedescriptor, but because I have no server, I want to send the packet to its original destination directly. I try to get IP and port from the packet, which are used to create protect tunnel and send packet. But when I use Fiddler to detect, I get nothing.
private Thread mThread;
private ParcelFileDescriptor mInterface;
private static String TAG = "VPN_SERVICE";
Builder builder = new Builder();
#Override
public int onStartCommand(Intent intent, final int flags, int startId) {
mThread = new Thread(new Runnable() {
#Override
public void run() {
try {
mInterface = builder.setSession("MyVPNService")
.addAddress("192.168.0.1", 24)
// .addDnsServer("8.8.8.8")
.addRoute("0.0.0.0", 0)
.establish();
FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
FileOutputStream out1 = openFileOutput("216427.txt", Context.MODE_APPEND);
ByteBuffer packet = ByteBuffer.allocate(512);
int length;
while (true){
while ((length = in.read(packet.array())) > 0){
packet.limit(length);
out1.write(packet.array());
ResolvePacket resolvePacket = new ResolvePacket();
resolvePacket.debugPacket(packet);
String desIP = resolvePacket.DESTINATION_IP;
String desPORT = resolvePacket.DESTINATION_PORT;
Log.d("IP + PORT:", "*******" + desIP + "******" + desPORT + "******");
DatagramChannel tmp_tunnel = DatagramChannel.open();
tmp_tunnel.connect(new InetSocketAddress(desIP, Integer.parseInt(desPORT)));
protect(tmp_tunnel.socket());
tmp_tunnel.write(packet);
tmp_tunnel.close();
packet.clear();
}
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(mInterface != null){
mInterface.close();
mInterface = null;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}, "MyVpnRunnable");
mThread.start();
return START_STICKY;
}

java.lang.IllegalArgumentException: Illegal character in query at index 56

This is the error caused after runnung the code
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.lang.Thread.run(Thread.java:841)
03-13 16:43:00.901: E/AndroidRuntime(18994): Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 56: http://suprabha.orgfree.com/ecg/temp.php?name=10&temper= 31,w=t
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.net.URI.create(URI.java:727)
03-13 16:43:00.901: E/AndroidRuntime(18994): at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
03-13 16:43:00.901: E/AndroidRuntime(18994): at com.example.mobilehealthcare.Temperature$DownloadWebPageTask.doInBackground(Temperature.java:271)
java file
package com.example.mobilehealthcare;
public class Temperature extends Activity {
private static final String TAG = "bluetooth2";
Button btnOn, btnOff;
TextView txtArduino;
Handler h;
private GraphView mGraph;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
// private static String address = "00:12:09:29:42:57";
// private static String address = "00:15:83:15:A3:10";
// private static String address = "20:13:07:12:04:17";
String sdop = "";
String pd = "";
String s1,sa,s1nom,sakom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temperature);
SharedPreferences pre = getSharedPreferences("pref", 0);
s1 = pre.getString("savedDatasd", "10");
s1nom = pre.getString("savedDatad", "10");
mGraph = (GraphView)findViewById(R.id.grap);
txtArduino = (TextView)findViewById(R.id.texView1);
mGraph.setMaxValue(1024);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
// int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
int endOfLineIndex = sb.indexOf("/");
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
Toast.makeText(getApplicationContext(), "received message"+"----"+sbprint, 30).show();
sb.delete(0, sb.length()); // and clear
txtArduino.setText(sbprint); // update TextView
// final int s = Integer.parseInt(sbprint);
// mGraph.addDataPoint(s);
sdop+= txtArduino.getText().toString()+",";
}
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}
public void tyre(View v)
{
mConnectedThread.write("t");
Toast.makeText(this, "waid for values to be received", Toast.LENGTH_SHORT).show();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(s1);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
#Override
public void onPause() {
super.onPause();
SharedPreferences preferences = getSharedPreferences("pref", 0);
SharedPreferences.Editor editor = preferences.edit();
//"savedData" is the key that we will use in onCreate to get the saved data
//mDataString is the string we want to save
// editor.putString("savedDatasd", sa);
// editor.putString("savedDatad", sakom);
// commit the edits
editor.commit();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket 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[256]; // 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); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
public void bus(View v)
{
Intent jkl = new Intent(this,Select.class);
startActivity(jkl);
finish();
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
//msg.setText(result);
if (result.contains("success")) {
Toast.makeText(getApplicationContext(), "Values are isent to Doctor", 30).show();
}else{Toast.makeText(getApplicationContext(), "Values are not sent to Doctor", 30).show();}
}
}
public void sav(View v)
{
String e = "t";
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://suprabha.orgfree.com/ecg/temp.php?name="+s1nom+"&temper="+sdop+"w="+e });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.temperature, menu);
return true;
}
}
Is it due to the php code?
or is the error in this java file.?
Which charater should be changed?
The error is in download web page task.
Edit:
This is the other code with same concept:
this works without error
public class Register extends Activity {
EditText a,b,c,d,e,f,g;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
a = (EditText) findViewById(R.id.editname1);
b = (EditText) findViewById(R.id.editpas1);
c = (EditText) findViewById(R.id.age);
d = (EditText) findViewById(R.id.editph1);
e = (EditText) findViewById(R.id.editadd1);
f = (EditText) findViewById(R.id.editem1);
g = (EditText) findViewById(R.id.dph);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
//msg.setText(result);
if (result.contains("success")) {
Intent i2 = new Intent(getApplicationContext(), Login.class);
//i.putExtra("id",na);
startActivity(i2);
}else{Toast.makeText(getApplicationContext(), result, 30).show();}
}
}
public void insert(View v)
{
String h,i,j,k,l,m,n;
h = a.getText().toString();
i = b.getText().toString();
j = c.getText().toString();
k = d.getText().toString();
l = e.getText().toString();
m = f.getText().toString();
n = g.getText().toString();
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://suprabha.orgfree.com/ecg/regis.php?name="+h+"&pass="+i+"&age="+j+"&ph="+k+"&addr="+l+"&em="+m+"&docph="+n });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register, menu);
return true;
}
}
seems to me that the query url "__http://suprabha.orgfree.com/ecg/temp.php?name=10&temper= 31,w=t" is where the program is encountering problem.
the 56th character is "=" which shouldnt be unexpected. However the spaces before the "31" in the string, can those be a point of concern?
If the spaces are not required as per your design, i would suggest you to remove and try it. If, they are however required, i would suggest escaping it before using the same.
Hope it helps.
note: ignore the undescores before the url. did that to prevent hyperlinking.
Problem are the blank spaces after the = symbol. You can avoid this simply with String:trimm(), but won't solve other problems, so, to avoid this, with URL's use java.net.URLEncoder to fit your needed enconding, for example:
URLEncoder.encode(url, "UTF-8");
In your case:
HttpGet httpGet = new HttpGet(URLEncoder.encode(url, "UTF-8"));

Android Sockets

I'm programming a simple Bluetooth chat.
When I want to handle sockets to receive and send message I don't know how to use these methods that i've implemented.
I attach my code and if some one know how to help me...
I have methods to create connection with thread, listen and write with socket. But I don't know how to use it on the main (onCreate).
Thank you.
public class messages_activity extends Activity {
private Button send;
private TextView message;
private EditText write;
private BluetoothSocket transferSocket;
private BluetoothAdapter mBluetoothAdapter;
final UUID applicationUUID = UUID.fromString("27012F0C-68AF-4FBF-8DBE-6BBAF7AA432A");
private boolean listening = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messages);
send = (Button) findViewById(R.id.button4);
message = (TextView) findViewById(R.id.textView2);
write = (EditText) findViewById(R.id.editText);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Intent intent = getIntent();
String macAddress = intent.getStringExtra("MacAddress"); //On macAddress I receive the macAddress of the other device that I want to send and receive
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAddress);
startServerSocket(mBluetoothAdapter);
connectToServerSocket(device, applicationUUID);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage(transferSocket, write.getText().toString()); //write is a textField when I write what I want to send
}
});
}
//Bluetooth Socket Server Connection
private UUID startServerSocket(BluetoothAdapter bluetooth){
try{
final BluetoothServerSocket btserver = bluetooth.listenUsingRfcommWithServiceRecord(mBluetoothAdapter.getName(), applicationUUID);
Thread acceptThread = new Thread(new Runnable() {
public void run() {
try{
//Block until client connection established
BluetoothSocket serverSocket = btserver.accept();
//Start listening for messages
StringBuilder incoming = new StringBuilder();
listenForMessages(serverSocket, incoming);
//Add a reference to the socket used to send messages
transferSocket = serverSocket;
}catch (IOException e){}
}
});
acceptThread.start();
}catch (IOException e){}
return applicationUUID;
}
//Creating a Bluetooth client socket
private void connectToServerSocket (BluetoothDevice device, UUID uuid){
try {
BluetoothSocket clientSocket = device.createRfcommSocketToServiceRecord(applicationUUID);
//Block until server connection accept
clientSocket.connect();
//Start listening for messages
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
//Add a reference to the socket used to send messages
transferSocket = clientSocket;
}catch (IOException e){}
}
private void sendMessage(BluetoothSocket socket, String message) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
// Add a stop character.
byte[] byteArray = (message + " ").getBytes();
byteArray[byteArray.length - 1] = 0;
outStream.write(byteArray);
outStream.flush();
} catch (IOException e) {
}
}
private void listenForMessages(BluetoothSocket socket, StringBuilder incoming){
listening = true;
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try{
InputStream instream = socket.getInputStream();
int bytesRead = -1;
while(listening){
bytesRead = instream.read(buffer);
if(bytesRead != -1){
String result = "";
while((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0)){
result = result + new String (buffer, 0, bytesRead - 1 );
bytesRead = instream.read(buffer);
}
result = result + new String (buffer, 0, bytesRead - 1 );
incoming.append(result);
message.setText(incoming); //message is a textview to show what I've received
}
socket.close();
}
}catch(IOException e){}
finally {
}
}
I haven't run the code so I don't know if it works.
listenForMessages shows the received message being inserted into the message textview message.setText(incoming);
This should then show on your screen.
If you want a chat, you should be doing something like:
Enter text in send box, click send.
In the onClick method of send.onClickListener, add a line to the messagetext(Chat window) box showing your message being sent:
ME: Hi! How are you?
Then clear the message text box
The onClick method then fires send message as coded.
When a message is received listenForMessage should add the received message to the Chat Window: ID: message.
FRIEND: I'm all snowed in? You?
Now you are ready for another round of messages.

Android sending command via bluetooth failed

I am going to implement the module of sending commands from my Android tablet to electronic device embedded with Bluetooth IC-chips Andrino HC-06 , for configuration of my device via Bluetooth. When it comes to execution, it seems that there is no observable response from the device when sending 22 23 54 01 C8.
It show the following timeout exception
It is expected that the device will restart and return many messages. What should I know more about when sending these eta commands to my device for remote control ?
The log cat message
05-23 18:19:44.866: E/BluetoothChatService(512): java.io.IOException: bt socket closed, read return: -1
05-23 18:19:44.866: E/BluetoothChatService(512): at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:429)
05-23 18:19:44.866: E/BluetoothChatService(512): at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
05-23 18:19:44.866: E/BluetoothChatService(512): at java.io.InputStream.read(InputStream.java:162)
05-23 18:19:44.866: E/BluetoothChatService(512): at com.example.android.BluetoothChat.BluetoothChatService$ConnectedThread.run(BluetoothChatService.java:485)
The below is my code
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT)
.show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
Sending Commands
public void write(byte[] buffer) {
try {
boolean connected = false;
BluetoothSocket sock = null;
InputStream in = null ;
OutputStream out = null ;
BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:14:01:12:28:12");
Method m = zee.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
sock = (BluetoothSocket) m.invoke(zee, Integer.valueOf(1));
sock.connect();
in = sock.getInputStream();
out = sock.getOutputStream();
char[] test = { 0x22 , 0x21 , 0x03 , 0x00 , 0xc9};
for(int k=0; k < test.length; k++){
new DataOutputStream(sock.getOutputStream()).writeByte(test[k]);
}
byte [] bfferX = new String(test).getBytes("UTF-8");*/
mmOutStream.write(buffer);
mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I suppose the device are already paired and that the android device performs the discovery.
Why do you think it is a matter of timeout? The exception tells that the communication socket is already closed. Maybe you succeed in create a BluetoothSocket and close it "accidentally" (maybe, after flushing, you close the output or input stream related to the socket).
Since you are following the Android BluetoothChat example you should:
1) perform the discovery and listen for available devices:
private final BroadcastReceiver deviceFoundBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action) && mState==STATE_DISCOVERING) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
new ConnectThread(device).start();
}
}
};
2) connect to the device:
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
private BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = InsecureBluetooth.createRfcommSocketToServiceRecord(mmDevice, YOUR_UUID, false);
}
catch (IOException e) { }
mmSocket = tmp;
}
#Override
public void run() {
try {
btAdapter.cancelDiscovery(); // be sure discovery is cancelled
mmSocket.connect(); // blocking call, returns only on a successful connection or an exception
connected(mmSocket, mmSocket.getRemoteDevice());
new ConnectedThread(mmSocket, mmDevice.getAddress()).start(); // start connected thread
}
catch (IOException e) {}
}
public void cancel() {}
}
3) Retrieve the input and output stream for communicating with the paired device (do not close the streams while communication is needed):
private class ConnectedThread extends Thread {
private BluetoothSocket mmSocket;
private String macAddress;
public ConnectedThread(BluetoothSocket socket, String macAddress) {
this.macAddress = macAddress;
this.mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
mmInStream = mmSocket.getInputStream();
mmOutStream = mmSocket.getOutputStream();
}
catch (IOException e) {}
}
#Override
public void run() {
// perform communication
}
}
The class InsecureBluetooth is used to "avoid" the pairing phase and is based on this Stanford peace of code:
#TargetApi(10)
public class InsecureBluetooth {
static private class InUse extends RuntimeException { }
public static BluetoothServerSocket listenUsingRfcommWithServiceRecord(BluetoothAdapter adapter, String name, UUID uuid, boolean encrypt) throws IOException {
if(Build.VERSION.SDK_INT<10) {
try {
Class c_rfcomm_channel_picker = null;
Class[] children = BluetoothAdapter.class.getDeclaredClasses();
for(Class c : children) {
Log.e("TO", "class " + c.getCanonicalName());
if(c.getCanonicalName().equals(BluetoothAdapter.class.getName() + ".RfcommChannelPicker")) {
c_rfcomm_channel_picker = c;
break;
}
}
if(c_rfcomm_channel_picker == null)
throw new RuntimeException("can't find the rfcomm channel picker class");
Constructor constructor = c_rfcomm_channel_picker.getDeclaredConstructor(UUID.class);
if(constructor == null)
throw new RuntimeException("can't find the constructor for rfcomm channel picker");
Object rfcomm_channel_picker = constructor.newInstance(new Object[] {uuid});
Method m_next_channel = c_rfcomm_channel_picker.getDeclaredMethod("nextChannel", new Class[] {});
m_next_channel.setAccessible(true);
BluetoothServerSocket socket = null;
int channel;
int errno;
while (true) {
channel = (Integer)m_next_channel.invoke(rfcomm_channel_picker, new Object[] {});
if (channel == -1) {
throw new IOException("No available channels");
}
try {
socket = listenUsingRfcomm(channel, encrypt);
break;
} catch(InUse e) {
continue;
}
}
Field f_internal_service = adapter.getClass().getDeclaredField("mService");
f_internal_service.setAccessible(true);
Object internal_service = f_internal_service.get(adapter);
Method m_add_rfcomm_service_record = internal_service.getClass().getDeclaredMethod("addRfcommServiceRecord", new Class[] {String.class, ParcelUuid.class, int.class, IBinder.class});
m_add_rfcomm_service_record.setAccessible(true);
int handle = (Integer)m_add_rfcomm_service_record.invoke(internal_service, new Object[] { name, new ParcelUuid(uuid), channel, new Binder() } );
if (handle == -1) {
try {
socket.close();
} catch (IOException e) {}
throw new IOException("Not able to register SDP record for " + name);
}
Field f_internal_handler = null;
try {
f_internal_handler = adapter.getClass().getDeclaredField("mServiceRecordHandler");
} catch(Exception e) {
f_internal_handler = adapter.getClass().getDeclaredField("mHandler");
}
f_internal_handler.setAccessible(true);
Object internal_handler = f_internal_handler.get(adapter);
Method m_set_close_handler = socket.getClass().getDeclaredMethod("setCloseHandler", new Class[] {Handler.class, int.class});
m_set_close_handler.setAccessible(true);
m_set_close_handler.invoke(socket, new Object[] { internal_handler, handle});
return socket;
} catch (Exception e) {}
}
else {
return adapter.listenUsingInsecureRfcommWithServiceRecord(name, uuid);
}
}
private static BluetoothServerSocket listenUsingRfcomm(int port, boolean encrypt, boolean reuse) throws IOException, InUse {
BluetoothServerSocket socket = null;
try {
Constructor<BluetoothServerSocket> constructor = BluetoothServerSocket.class.getDeclaredConstructor(int.class, boolean.class, boolean.class, int.class);
if(constructor == null)
throw new RuntimeException("can't find the constructor");
constructor.setAccessible(true);
Field f_rfcomm_type = BluetoothSocket.class.getDeclaredField("TYPE_RFCOMM");
f_rfcomm_type.setAccessible(true);
int rfcomm_type = (Integer)f_rfcomm_type.get(null);
Field f_e_addr_in_use = BluetoothSocket.class.getDeclaredField("EADDRINUSE");
f_e_addr_in_use.setAccessible(true);
int e_addr_in_use = (Integer)f_e_addr_in_use.get(null);
socket = constructor.newInstance(new Object[] { rfcomm_type, false, encrypt, port } );
Field f_internal_socket = socket.getClass().getDeclaredField("mSocket");
f_internal_socket.setAccessible(true);
Object internal_socket = f_internal_socket.get(socket);
Method m_bind_listen = internal_socket.getClass().getDeclaredMethod("bindListen", new Class[] {});
m_bind_listen.setAccessible(true);
Object result = m_bind_listen.invoke(internal_socket, new Object[] {});
int errno = (Integer)result;
if(reuse && errno == e_addr_in_use) {
throw new InUse();
} else if (errno != 0) {
try {
socket.close();
} catch (IOException e) {}
internal_socket.getClass().getMethod("throwErrnoNative", new Class[] {int.class}).invoke(internal_socket, new Object[] { errno });
}
return socket;
} catch (Exception e) {}
}
public static BluetoothServerSocket listenUsingRfcomm(int port, boolean encrypt) throws IOException {
return listenUsingRfcomm(port, encrypt, false);
}
private static BluetoothSocket createRfcommSocketToServiceRecord(BluetoothDevice device, int port, UUID uuid, boolean encrypt) throws IOException {
try {
BluetoothSocket socket = null;
Constructor<BluetoothSocket> constructor = BluetoothSocket.class.getDeclaredConstructor(
int.class, int.class, boolean.class, boolean.class, BluetoothDevice.class, int.class, ParcelUuid.class);
if(constructor == null)
throw new RuntimeException("can't find the constructor for socket");
constructor.setAccessible(true);
Field f_rfcomm_type = BluetoothSocket.class.getDeclaredField("TYPE_RFCOMM");
f_rfcomm_type.setAccessible(true);
int rfcomm_type = (Integer)f_rfcomm_type.get(null);
socket = constructor.newInstance(new Object[] { rfcomm_type, -1, false, true, device, port, uuid != null ? new ParcelUuid(uuid) : null} );
return socket;
} catch (Exception e) {}
}
public static BluetoothSocket createRfcommSocketToServiceRecord(BluetoothDevice device, UUID uuid, boolean encrypt) throws IOException{
if(Build.VERSION.SDK_INT<10) {
return createRfcommSocketToServiceRecord(device, -1, uuid, encrypt);
}
else {
return device.createInsecureRfcommSocketToServiceRecord(uuid);
}
}
public static BluetoothSocket createRfcommSocket(BluetoothDevice device, int port, boolean encrypt) throws IOException {
return createRfcommSocketToServiceRecord(device, port, null, encrypt);
}
}

Categories

Resources