Input/Output between C binary and Java on Android - java

I need to grab text questions from C binary and display it in my TextView. Also, I need to grab an answers from input field and pass it to C binary, etc. I read this topic and tried to run it on Android. C binary works in shell, but my app doesn't work (blank screen). I am very new in Java and I need help.
package com.example.helloapp;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class HelloApp extends Activity
{
private Button btn;
private EditText editText;
private TextView textView;
private BlockingQueue<String> m_queue;
private BufferedReader bufIn;
private InputStream in;
private InputThread inputThread;
private PrintWriter printOut;
private Process p;
private Handler handler;
private String input = null;
// show nice popup on error
private void popup(String msg)
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler()
{
#Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace();
HelloApp.this.finish();
}
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView1);
btn = (Button)findViewById(R.id.button1);
Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
// new Thread cannot change our TextView, so we use Handler
handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
String text = (String) msg.obj;
textView.setText(text);
}
};
File f = new File(getCacheDir()+"/hello");
if(!f.exists())
try {
// unpack our binary...
InputStream is = getAssets().open("hello");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
// ... and make it executable
try {
Process chmod = Runtime.getRuntime().exec("/system/bin/chmod 777 " +f.getPath());
chmod.waitFor();
} catch(IOException e) { popup(e.getMessage()); } catch(InterruptedException e) { popup(e.getMessage()); }
} catch(IOException e) { popup(e.getMessage()); }
try {
p = Runtime.getRuntime().exec(f.getPath());
InputStream in = p.getInputStream() ;
OutputStream out = p.getOutputStream ();
InputStream err = p.getErrorStream();
printOut = new PrintWriter(out);
m_queue = new ArrayBlockingQueue<String>(10);
inputThread = new InputThread(in, m_queue);
inputThread.start();
} catch(Exception e) { popup(e.getMessage()); }
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
editText = (EditText)findViewById(R.id.editText1);
input = editText.getText().toString();
// pass something to C binary
printOut.println(input+"\n");
printOut.flush();
}
});
}
private void setTextHandler(final String text)
{
Message msg = new Message();
msg.obj = text;
handler.sendMessage(msg);
}
private void mainLoop()
{
String line;
while(true)
{
try {
line = bufIn.readLine();
// stdin is always empty... why?
if(line != null) { setTextHandler(line); }
}
catch(IOException e) { popup(e.getMessage()); return; }
}
}
private class InputThread extends Thread
{
InputThread(InputStream in, BlockingQueue<String> queue)
{
bufIn = new BufferedReader(new InputStreamReader(in));
m_queue = queue;
}
public void run() {
try { mainLoop(); }
catch(Throwable t) { popup(t.getMessage()); }
}
}
}
UPDATE: if I compile the following C code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *s;
setvbuf(stdout, NULL, _IONBF, 0); // <<<= disable buffering globally
printf("Enter your name:\n");
fflush(stdout);
scanf("%s", &s);
printf("Hello, %s", s);
fflush(stdout);
return 0;
}
I get results only when binary exits, ie. I run android app, see a blank screen (must see "Enter your name:"), input something, press OK button - binary exits and I get "Enter your name: Hello, Eugene" at once.
PROBLEM SOLVED! See updated C code.

Related

why android client new socket command is not working

I wrote simple android java client , main activity with socketTask and and a handler in mainactivity. and it doesn't working .
I used debuger and found that the problem is in this line :
this.socket = new Socket(IP_ADDRESS, PORT);
I also had this error massage in the studio :
An unexpected packet was received before the handshake
the server is ok and responding to any other program .
Can some one advice what is the problem . I attaching mainactivity and socket task .
thanks a lot .
main activity
package com.example.app24;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
Button btnSend ;
TextView tvFromServer;
EditText etToSend;
String strToSend,strFromServer;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend = (Button) findViewById(R.id.btnSend);
btnSend.setOnClickListener(this);
etToSend = (EditText) findViewById(R.id.etToSend);
tvFromServer = (TextView) findViewById(R.id.tvFromServer);
tvFromServer = (TextView) findViewById(R.id.tvFromServer);
}
#Override
public void onClick(View v)
{
if (v == btnSend)
{
strToSend = etToSend.getText().toString();
new Thread(new Runnable() {
#Override
public void run() {
SocketTask send1 = new SocketTask(strToSend);
strFromServer=send1.sendReceive();
runOnUiThread(new Runnable() {
public void run() {
tvFromServer.setText(strFromServer);
}
});
}
}).start();
}
}
}
'''
SocketTask.
```
package com.example.newproj;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import androidx.annotation.RequiresApi;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class SocketTask
{
//private final static String IP_ADDRESS = "172.19.16.179";
private final static String IP_ADDRESS = "192.168.1.124";
private final static int PORT = 8821; // HTTP port
private final static int PACKET_SIZE = 1024; // standard 1kb packet size
private Socket socket;
private String sendingStr="";
private String receivingStr="";
BufferedReader reader;
public SocketTask(String str1)
{
this.sendingStr = str1;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void send()
{
try {
OutputStreamWriter writer = new OutputStreamWriter(this.socket.getOutputStream(), StandardCharsets.UTF_8); // outputStreamWriter creating
writer.write(this.sendingStr);
writer.flush();
Log.d("Result", "sent");
}
catch (Exception e) {
Log.e("Exception", e.toString());
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void receive() {
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
char[] charBuffer = new char[1024];
StringBuilder stringBuilder = new StringBuilder();
reader.read(charBuffer);
stringBuilder.append(charBuffer);
reader.close();
receivingStr = stringBuilder.toString();
}
catch (IOException e)
{
Log.e("Exception", e.toString());
}
}
public String sendReceive()
{
try {
this.socket = new Socket(IP_ADDRESS, PORT);
send();
receive();
this.socket.close();
} catch (Exception e) {
Log.e("Exception", e.toString());
}
return this.receivingStr;
}
}
```

Receiving image through sockets on androidstudio

I have written a code on Android Studio to receive images from a socket server and the application connects to the server every time a button is clicked.
However, when I run the app and click the button nothing shows up but the server sends a message saying the photo is sent. When I click the button again, for the second time (the server is not connected) the image pops up instantly.
I think the issue is that the thread isn't shutting down completely when I click the button once but if I click it again, the thread shuts down forcefully and starts a new one so the image is shown.
The code for the main activity java file is :
package com.example.myapplication;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTextViewReplyFromServer;
private EditText mEditTextSendMessage;
private ImageView mImg;
private byte [] imgbyte;
Handler updateConversationHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonSend = (Button) findViewById(R.id.btn_send);
mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message);
mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server);
mImg = (ImageView)findViewById(R.id.imageView);
String filepath = "/sdcard/DCIM/img.jpeg";
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
Thread fst = new Thread(new ServerThread());
fst.start();
break;
}
}
public class ServerThread implements Runnable {
byte [] line;
Bitmap bitmap;
public void run() {
try {
Socket client = new Socket("192.168.1.145", 5560);
while (true) {
// LISTEN FOR INCOMING CLIENTS
try {
int bytesRead;
int current = 0;
int filesize=215320;
byte [] mybytearray2 = new byte [filesize];
InputStream is = client.getInputStream();
FileOutputStream fos = new FileOutputStream("/sdcard/DCIM/img.jpg"); // destination path and name of file
//FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray2,0,mybytearray2.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray2, current, (mybytearray2.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray2, 0 , current);
bos.flush();
// bitmap = BitmapFactory.decodeByteArray(mybytearray2 , 0, mybytearray2.length);
// mImg.setImageBitmap(bitmap);
//System.out.println(end-start);
updateConversationHandler.post(new updateUIThread(mybytearray2));
bos.close();
client.close();
break;
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class updateUIThread implements Runnable {
private byte[] byteArray;//private String msg;
public updateUIThread(byte[] array){ //public updateUIThread(String str) {
this.byteArray=array; //this.msg = str;
}
#Override
public void run() {
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray , 0, byteArray .length);
mImg.setImageBitmap(bitmap);//text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
Is there anyway I can kill the thread immediately after the image is recieved?
My image also shows up on the android emulator but does not show up on my phone. What could be the reason for this?
Edit : if i start the thread on the oncreate section, the image pops up as soon as the application is started
Edit : python server code :
import socket
from time import sleep
from time import time
host = ''
port = 5560
filePath = "/media/pi/ESD-USB/image.jpg"
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created.")
try:
s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind comlete.")
return s
def setupConnection():
s.listen(1) # Allows one connection at a time.
conn, address = s.accept()
print("Connected to: " + address[0] + ":" + str(address[1]))
return conn
def sendPic(s, filePath):
print(filePath)
pic = open(filePath, 'rb')
chunk = pic.read()
size = len(chunk)
print (size)
t = time()
print("Sending Picture")
s.sendall(chunk)
pic.close()
print("Done sending")
print("Elapsed time = " + str(time() - t) + 's')
s.close()
return "Done sending"
def backup(filePath):
conn = setupConnection()
response = sendPic(conn, filePath)
return response
s = setupServer()
while True:
print(filePath)
backup(filePath)
print("Everything should be backed up now.")
break
I figured out what to do. the while loop was causing an issue and i implemented runonui thread like blackapps suggested.
The working code is shown below :
package com.example.myapplication;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTextViewReplyFromServer;
private EditText mEditTextSendMessage;
private ImageView mImg;
private byte [] imgbyte;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonSend = (Button) findViewById(R.id.btn_send);
mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message);
mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server);
mImg = (ImageView)findViewById(R.id.imageView);
String filepath = "/sdcard/DCIM/img.jpeg";
}
#Override
public void onClick(View v) {
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
byte [] line;
Bitmap bitmap;
public void run() {
try {
Socket client = new Socket("192.168.1.145", 5560);
try {
int bytesRead;
int current = 0;
int filesize = 300000;
byte [] mybytearray2 = new byte [filesize];
InputStream is = client.getInputStream();
FileOutputStream fos = new FileOutputStream("/sdcard/DCIM/img.jpg"); // destination path and name of file
//FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray2,0,mybytearray2.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray2, current, (mybytearray2.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray2, 0 , current);
bos.flush();
bitmap = BitmapFactory.decodeByteArray(mybytearray2 , 0, mybytearray2.length);
long end = System.currentTimeMillis();
runOnUiThread(new Runnable() {
#Override
public void run() {
mImg.setImageBitmap(bitmap);
}
});
bos.close();
client.close();
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
e.printStackTrace();
}
});
e.printStackTrace();
}
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
e.printStackTrace();
}
});
e.printStackTrace();
}
}
}
}
the next step for me is to send the filesize of the image from the python server to the android app. also to figure out why my image does not show up on the an actual android but on the emulator.

Reconnecting to Bluetooth in android / Reading after Reconnect

I have a program that establishes a Bluetooth connection, reads the InputStream to a textView, and can disconnect from the module. While I can successfully disconnect and reconnect to the module (HC-05) as many times as I please, I can't get an InputStream read anymore after I reconnect. I believe it is because I don't know how to reinitialize the thread I'm using to read the InputStream. I am very new to java and android programming, any help with this issue would be appreciated.This is my code:
The textView for the read display is called 'Status' and I am hoping to "reset" the thread upon the onclick connect().
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements Runnable {
private BluetoothAdapter adapter;
private InputStream inputStream;
private OutputStream outputStream;
private Thread thread;
private TextView Status;
private TextView Connection;
private BluetoothSocket socket = null;
private boolean threadStatusInitial=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Status=(TextView) findViewById(R.id.StatusID);
Connection=(TextView) findViewById(R.id.ConnectionStatus);
adapter= BluetoothAdapter.getDefaultAdapter();
if(adapter==null){
Toast.makeText(this,"bluetooth is unavailable",Toast.LENGTH_SHORT).show();
finish();
return;
}
thread=new Thread(this);
}
public void connect(View view){
Set<BluetoothDevice> devices=adapter.getBondedDevices();
for(BluetoothDevice device:devices){
if(device.getName().startsWith("HC-05")){
try {
socket=device.createRfcommSocketToServiceRecord(device.getUuids()[0].getUuid());
socket.connect();
Connection.setText("Connected");
inputStream=socket.getInputStream();
outputStream=socket.getOutputStream();
if (threadStatusInitial){
thread.start();
threadStatusInitial=false; //this ensures that the thread.start() method will only be called during the first connection
}
} catch (IOException e) {
Toast.makeText(this,"Can't Connect",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
break;
}
}
}
public void Disconnect(View view) throws InterruptedException {
if (inputStream != null) {
try {inputStream.close();} catch (Exception e) {}
inputStream = null;
}
if (outputStream != null) {
try {outputStream.close();} catch (Exception e) {}
outputStream = null;
}
if (socket != null) {
try {socket.close();} catch (Exception e) {Toast.makeText(this,"Can't Connect",Toast.LENGTH_LONG).show();}
socket = null;
}
Connection.setText("Disconnected");
}
#Override
public void run() {
String textInput = "hi";
byte[] writeBytes=textInput.getBytes();
if(outputStream!=null){
try {
outputStream.write(writeBytes);
} catch (IOException e) {
Toast.makeText(this,"Unable to Write to Bluetooth ",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
while(inputStream!=null){
byte [] buffer=new byte[2048];
try {
int length=inputStream.read(buffer);
final String strReceived = new String(buffer, 0, length);
runOnUiThread(new Runnable(){
#Override
public void run() {
Status.setText(strReceived);
}});
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Saving string array list to internal file directory android

I'm currently developing an android application with makes some user data while running which is saved in two ArrayList. Once the application closes, I need to save the datas on to the internal memory but in my logcat I'm always getting the error IOException file not found.
I'm confused about why it always happen. The following is my code for my activity. Please help me!
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
public static ArrayList<String> myArrayList=new ArrayList<String>();
public static ArrayList<String> myArrayListwr=new ArrayList<String>();
static int close=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
close=1;
System.out.println("Oncreate called");
try{
final File dir = new File(getApplicationContext().getFilesDir() + "/file");
if(!(dir.exists()))
{
dir.mkdirs(); //create folders where write files
}
final File file = new File(dir+ "/lines.txt");
if(!(file.exists())) {
file.createNewFile();
}
BufferedReader br = new BufferedReader(new FileReader(file));
if (br.readLine() == null) {
close=0;
}
br.close();
}
catch (IOException exc) { exc.printStackTrace(); }
try {
if(myArrayList.size()==0 && close!=0)
{
System.out.println("retriving data from file lines");
FileInputStream input =openFileInput("lines.txt"); // Open input stream
DataInputStream din = new DataInputStream(input);
int sz = din.readInt(); // Read line count
for (int i=0;i<sz;i++) { // Read lines
String line = din.readUTF();
myArrayList.add(line);
}
din.close();
}
}
catch (IOException exc) { exc.printStackTrace(); }
try {
if(myArrayListwr.size()==0 && close!=0)
{
System.out.println("retriving data from file lineswr");
final File dirwr = new File(getApplicationContext().getFilesDir() + "/file");
if(!dirwr.exists())
dirwr.mkdirs(); //create folders where write files
final File filewr = new File(dirwr+ "/lineswr.txt");
if(!filewr.exists()) {
filewr.createNewFile();
}
FileInputStream inputwr = openFileInput("lineswr.txt"); // Open input stream
DataInputStream dinwr = new DataInputStream(inputwr);
int szwr = dinwr.readInt(); // Read line count
for (int iwr=0;iwr<szwr;iwr++) { // Read lines
String linewr = dinwr.readUTF();
myArrayListwr.add(linewr);
}
dinwr.close();
}
}
catch (IOException exc) { exc.printStackTrace(); }
Button phy = (Button) findViewById(R.id.button3);
Button mat = (Button) findViewById(R.id.button1);
Button bio = (Button) findViewById(R.id.button2);
Button chem = (Button) findViewById(R.id.button4);
}
#Override
public void onBackPressed() {
super.onBackPressed();
try {
if(myArrayList.size()!=0)
{
System.out.println("inside on back pressed saving data to lines");
//Modes: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITABLE
String fileName = getApplicationContext().getFilesDir()+"/file/"+ "lines.txt";
FileOutputStream output = openFileOutput("lines.txt",MODE_PRIVATE);
DataOutputStream dout = new DataOutputStream(output);
dout.writeInt(myArrayList.size()); // Save line count
for(String line : myArrayList) // Save lines
dout.writeUTF(line);
dout.flush(); // Flush stream ...
dout.close(); // ... and close.
}
}
catch (IOException exc) { exc.printStackTrace(); }
try {
if(myArrayListwr.size()!=0)
{
System.out.println("inside on back pressed saving data to lineswr");
//Modes: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITABLE
String fileNamewr = getApplicationContext().getFilesDir()+"/file/"+ "lineswr.txt";
FileOutputStream outputwr = openFileOutput("lineswr.txt",MODE_PRIVATE);
DataOutputStream doutwr = new DataOutputStream(outputwr);
doutwr.writeInt(myArrayListwr.size()); // Save line count
for(String linewr : myArrayListwr) // Save lines
doutwr.writeUTF(linewr);
doutwr.flush(); // Flush stream ...
doutwr.close(); // ... and close.
}
}
catch (IOException exc) { exc.printStackTrace(); }
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
}

Receive a string via RFCOMM in android

I am trying to recieve a string via RFCOMM in android
I am a newbie to android and please help me
I can send data
but receiving fails
Here is my code
Please help me
package com.example.btspp;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Scanner;
import java.util.UUID;
import java.util.regex.Pattern;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Buttons extends Activity {
private BluetoothAdapter btAdaptor;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private InputStream inStream = null;
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
public String addressToConnect;
public static StringBuilder readStr;
TextView tv;
int aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buttons);
tv = (TextView) findViewById(R.id.textView1);
addressToConnect = getIntent().getStringExtra("addressToConnect");
connectToDevice(addressToConnect);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
sendData("H");
// Toast.makeText(getBaseContext(), addressToConnect,
// Toast.LENGTH_SHORT).show();
}
});
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
try {
// final BT bt = new BT();
outStream.write(msgBuffer);
//readData();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(),
"Not Sent BT Data : " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}
/*private void readData(){
String instring = "";
try {
inStream = btSocket.getInputStream();
} catch (Exception e) {
// TODO: handle exception
}
Scanner scan = new Scanner(new InputStreamReader(inStream));
scan.useDelimiter(Pattern.compile("[\\r\\n]+"));
instring = scan.next();
scan = null;
Toast.makeText(getApplicationContext(),
"Got Data : " + instring, Toast.LENGTH_SHORT)
.show();
//return instring;
}*/
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = inStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
inStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
tv.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
private void connectToDevice(String address) {
btAdaptor = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdaptor.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
outStream = btSocket.getOutputStream();
inStream = btSocket.getInputStream();
beginListenForData();
tv.setText("Bluetooth Opened");
//listenForMessages(btSocket, readStr);
// beginListenForData();
} catch (IOException e) {
// errorExit("Fatal Error",
// "In onResume() and socket create failed: " + e.getMessage() +
// ".");
Toast.makeText(getApplicationContext(),
"Not Connected : " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_buttons, menu);
return true;
}
}
I am a newbie to android and please help me
I can send data
but receiving fails
Here is my code
Please help me
Isn't 13 "\r" the usual delimiter and not 10?

Categories

Resources