I'm trying to write a code I can write all the results values from accelerometer sensor into a .txt file. I can't write all the data in somehow. I think there is a problem in my loop. It is just reading about 10 to 15 samples.
How can I write all the values of the sensor into that file until I toggle off the button to stop? here is the code I wrote.
Thanks in advance!
public class MainActivity extends Activity implements SensorEventListener {
public SensorManager sm;
Sensor accelermeter;
private static final String DEBUG = "LogAccelermeter";
ToggleButton OnStore;
Button OffStore;
Button btnOn, btnOff;
TextView txtArduino, txtString, txtStringLength, sensorView0, sensorView1, sensorView2, sensorView3;
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 BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
TextView sensorText;
// String for MAC address
private static String address;
private GestureDetectorCompat mDetector;
FileOutputStream fileOutputStream;
double TotalAccelerate;
ArrayList<Double> list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<Double>();
//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);
sensorView1 = (TextView) findViewById(R.id.sensorView1);
sensorView2 = (TextView) findViewById(R.id.sensorView2);
sensorView3 = (TextView) findViewById(R.id.sensorView3);
//for Accelermeter
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorText = (TextView) findViewById(R.id.sensor);
accelermeter = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelermeter, SensorManager.SENSOR_DELAY_NORMAL);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File Root = Environment.getExternalStorageDirectory();
File dir = new File(Root.getAbsolutePath() + "/MyApp");
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir, "MyMessage.txt");
try {
fileOutputStream = new FileOutputStream(file, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "SDcard not found", Toast.LENGTH_LONG).show();
}
OnStore = (ToggleButton) findViewById(R.id.onStore);
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
try {
for(double TotalAccelerate : list){
// System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
// fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}if (!OnStore.isChecked()){
try {
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
list.clear();
Collections.synchronizedList(list);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
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, 5); //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(" Sensor 0 Voltage = " + sensor0 + "V"); //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 OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0"); // Send "0" via Bluetooth
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1"); // Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
}//end OnCreate Method
#Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
#Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
double xx = event.values[0];
double yy = event.values[1];
double zz = event.values[2];
TotalAccelerate = Math.round(Math.sqrt(Math.pow(xx, 2)
+ Math.pow(yy, 2)
+ Math.pow(zz, 2)));
Log.i(DEBUG, "Accelerometer = " + TotalAccelerate);
list.add(TotalAccelerate);
findPeaks(list);
sensorText.setText("Total: " + TotalAccelerate);
Log.i(DEBUG, "list values " + list);
}
//Find peak values.
public static ArrayList<Double> findPeaks(List<Double> points) {
ArrayList<Double> peaks = new ArrayList<Double>();
if (points == null || points.size() < 1)
return peaks;
Double x1_n_ref = 0.0;
int alpha = 0; //0=down, 1=up.
int size = points.size();// -1)/100;
for (int i = 0; i < size; i += 5) {
Double IndexValues = points.get(i);
if (IndexValues > 9) {
Double delta = (x1_n_ref - IndexValues);
if (delta < 0) {
x1_n_ref = IndexValues;
alpha = 1;
} else if (alpha == 1 && delta > 0) {
peaks.add(x1_n_ref);
alpha = 0;
}
} else if (alpha == 0) {
x1_n_ref = IndexValues;
}
}
return peaks;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
this.mDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final String DEBUG_TAG = "Gestures";
#Override
public boolean onDown(MotionEvent event) {
Log.d(DEBUG_TAG, "onDown: " + event.toString());
Toast.makeText(getApplication(), "OnDown Touch Occur", Toast.LENGTH_LONG).show();
if (event.getX() > 0) {
mConnectedThread.write("1");
}
return true;
}
#Override
public void onLongPress(MotionEvent event) {
Log.d(DEBUG_TAG, "onLongPress: " + event.toString());
mConnectedThread.write("0");
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//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(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
//create device and set the MAC address
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
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();
}
}
}
}
Could you try this for the toggle button onClick callback? It should write all the data when it's unchecked.
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
// should do nothing
} else if (!OnStore.isChecked()){
try {
for(double TotalAccelerate : list){
//System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
fileOutputStream.flush();
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
To regulate the code to start/stop listen to the sensor event, add the following variable somewhere in this class:
private boolean isListening = false;
And make the following modifications to your existing code:
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
//
// set listening flag to true
//
isListening = true;
} else if (!OnStore.isChecked()){
//
// set listening flag to false
//
isListening = false;
try {
for(double TotalAccelerate : list){
//System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
fileOutputStream.flush();
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
#Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
//
// regulate
//
if (isListening) {
double xx = event.values[0];
double yy = event.values[1];
double zz = event.values[2];
TotalAccelerate = Math.round(Math.sqrt(Math.pow(xx, 2)
+ Math.pow(yy, 2)
+ Math.pow(zz, 2)));
Log.i(DEBUG, "Accelerometer = " + TotalAccelerate);
list.add(TotalAccelerate);
findPeaks(list);
sensorText.setText("Total: " + TotalAccelerate);
Log.i(DEBUG, "list values " + list);
}
}
Related
In the below code which is for bluetooth messaging with arduino i am trying to change color on some static strings.
1.On the start button listener i have a message"Connection opened" which i am changing color using the xml file and creating there a string with specific color. This method works only there.
2. i tried another method with spannable string on the send button listener but is not working at all the message comes in black.
what i want to to do is that when i send a message on my textview i see the "send data: "+ string(msg i send) and i want this send data to be red for examle and the same for the receive one.
What i tried untill now is on the code.If there is any idea to try i will be grateful.
public class MainActivity extends Activity {
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");//Serial Port Service ID
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
Button startButton, sendButton,clearButton,stopButton;
TextView textView;
EditText editText;
boolean deviceConnected=false;
//Thread thread;
byte[] buffer;
//int bufferPosition;
boolean stopThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = findViewById(R.id.buttonStart);
sendButton = findViewById(R.id.buttonSend);
clearButton = findViewById(R.id.buttonClear);
stopButton = findViewById(R.id.buttonStop);
editText = findViewById(R.id.editText);
textView = findViewById(R.id.textView);
textView.setMovementMethod(new ScrollingMovementMethod());
setUiEnabled(false);
startButton.setOnClickListener(v -> {
if(BTinit())
{
if(BTconnect())
{
setUiEnabled(true);
deviceConnected=true;
beginListenForData();
//textView.append("Connection Opened!");
String greenString = getResources().getString(R.string.Connection_Opened);
textView.append(Html.fromHtml(greenString));
}
}
});
sendButton.setOnClickListener(v -> {
String t = "Send Data: ";
SpannableString spannableString = new SpannableString(t);
ForegroundColorSpan green = new ForegroundColorSpan(getResources().getColor(R.color.private_green));
spannableString.setSpan(green, 0, 9, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
String string = editText.getText().toString();
String str = string.concat("\n");
try {
outputStream.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
textView.append(spannableString + str);
});
stopButton.setOnClickListener(v -> {
try {
stopThread = true;
outputStream.close();
inputStream.close();
socket.close();
setUiEnabled(false);
deviceConnected=false;
textView.append("Connection Closed!");
}catch (IOException e){
e.printStackTrace();
}
});
clearButton.setOnClickListener(v -> textView.setText(""));
}
public void setUiEnabled(boolean bool)
{
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public boolean BTinit()
{
boolean found=false;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(bluetoothAdapter !=null)
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
}
assert bluetoothAdapter != null;
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if(bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
}
else
{
for (BluetoothDevice iterator : bondedDevices)
{
//private final String DEVICE_NAME="ArduinoBT";
String DEVICE_ADDRESS = "98:DA:C0:00:2C:E2";
if(iterator.getAddress().equals(DEVICE_ADDRESS))
{
device=iterator;
found=true;
break;
}
}
}
return found;
}
public boolean BTconnect()
{
boolean connected=true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
connected=false;
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
return connected;
}
void beginListenForData()
{
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];
Thread thread = new Thread(() -> {
while(!Thread.currentThread().isInterrupted() && !stopThread)
{
try
{
int byteCount = inputStream.available();
if(byteCount > 0)
{
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
final String string=new String(rawBytes, StandardCharsets.UTF_8);
handler.post(() -> textView.append("Receive data: " + string));
}
}
catch (IOException ex)
{
stopThread = true;
}
}
});
thread.start();
}
}
Try like this;
Spannable text = new SpannableString("Send Data:");
text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.private_green)), 0, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
I'm facing a technician code problem. I want to write all the values I get from TotalAccelerate into my .txt file through Toggle button. the code is now writing only one value at a time once I toggle the button. How can I manually write and stop writing into the file?
Thanks in advance.
FileOutputStream fileOutputStream;
double TotalAccelerate; //I made it global variable
ArrayList<Double> list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<Double>();
//for Accelermeter
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorText = (TextView) findViewById(R.id.sensor);
accelermeter = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelermeter, SensorManager.SENSOR_DELAY_NORMAL);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File Root = Environment.getExternalStorageDirectory();
File dir = new File(Root.getAbsolutePath() + "/MyApp");
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir, "MyMessage.txt");
try {
fileOutputStream = new FileOutputStream(file, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "SDcard not found", Toast.LENGTH_LONG).show();
}
OnStore = (ToggleButton) findViewById(R.id.onStore);
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
try {
for(TotalAccelerate : list){
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
}
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}if (!OnStore.isChecked()){
try {
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
//added
list.clear();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
}// end OnCreate method
//Find the total acccerleration from the three sensors,
then write the values into a file for off-line analysis
#Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
double xx = event.values[0];
double yy = event.values[1];
double zz = event.values[2];
TotalAccelerate = Math.round(Math.sqrt(Math.pow(xx, 2)
+ Math.pow(yy, 2)
+ Math.pow(zz, 2)));
Log.i(DEBUG, "Accelerometer = " + TotalAccelerate);
// list = new ArrayList<Double>();
list.add(TotalAccelerate);
findPeaks(list);
sensorText.setText("Total: " + list);
Log.i(DEBUG, "Total " + list);
}
You are creating a new List each time the sensor changes, with the line:-
list = new ArrayList<Double>();
Move this to the start of your program, and empty the list once you have written it to the file. You will also need to synchronize the places where the list is modified.
After selecting multiple images from a gallery, I want to upload them to an ftp server. During the upload, I get the following error:
"java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20150724_220209.jpg /storage/emulated/0/DCIM/Screenshots/Screenshot_2015-08-04-14-47-38.png "
Can anyone help?
public class MainActivity extends Activity implements View.OnClickListener{
private LinearLayout lnrImages;
private Button btnAddPhots;
private Button btnSaveImages;
private ArrayList<String> imagesPathList;
private Bitmap yourbitmap;
private Bitmap resized;
private final int PICK_IMAGE_MULTIPLE =1;
static final String FTP_HOST = "";
static final String FTP_USER = "";
static final String FTP_PASS = "";
String j;
Uri uri;
String[] th;
String str;
String picturepath,currentpath;
Button b;
String r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lnrImages = (LinearLayout)findViewById(R.id.lnrImages);
btnAddPhots = (Button)findViewById(R.id.btnAddPhots);
btnSaveImages = (Button)findViewById(R.id.btnSaveImages);
b=(Button)findViewById(R.id.btnSaveImages1);
btnAddPhots.setOnClickListener(this);
btnSaveImages.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnAddPhots:
Intent intent = new Intent(MainActivity.this,CustomPhotoGalleryActivity.class);
startActivityForResult(intent,PICK_IMAGE_MULTIPLE);
break;
case R.id.btnSaveImages:
if(imagesPathList !=null){
if(imagesPathList.size()>=1) {
File f = new File("" + r);
Log.e("File", "" + f);
doFileUpload(f);
Log.d("saveimages", "" + imagesPathList);
Toast.makeText(MainActivity.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, imagesPathList.size() + " no of image are selected", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this," no images are selected", Toast.LENGTH_SHORT).show();
}
break;
}
}
public void doFileUpload(File f) {
FTPClient client = new FTPClient();
try {
client.connect(FTP_HOST, 21);
Log.e("clientconnect", "" + client);
client.login(FTP_USER, FTP_PASS);
Log.e("clientlogin", "" + client);
client.setType(FTPClient.TYPE_BINARY);
Log.e("clienttype", "" + client);
client.changeDirectory("/real/");
Log.i("", "$$$$$$$$$$$$$$$$$" + ("/real/"));
// int reply = client.getReplyCode();
client.upload(f, new MyTransferListener());
// Log.e("filenameupload", "" + photoFile);
Log.e("clientupload", "" + client);
// Log.e("file",""+fileName);
} catch (Exception e) {
e.printStackTrace();
try {
client.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public class MyTransferListener implements FTPDataTransferListener {
public void started() {
// btn.setVisibility(View.GONE);
// Transfer started
Toast.makeText(getApplicationContext(), " Upload Started ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" Upload Started ...");
}
public void transferred(int length) {
// Yet other length bytes has been transferred since the last time
// this
// method was called
Toast.makeText(getApplicationContext(),
" transferred ..." + length, Toast.LENGTH_SHORT).show();
// System.out.println(" transferred ..." + length);
}
public void completed() {
// btn.setVisibility(View.VISIBLE);
// Transfer completed
Toast.makeText(getApplicationContext(), " completed ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" completed ..." );
}
public void aborted() {
// btn.setVisibility(View.VISIBLE);
// Transfer aborted
Toast.makeText(getApplicationContext(),
" transfer aborted , please try again...",
Toast.LENGTH_SHORT).show();
// System.out.println(" aborted ..." );
}
public void failed() {
// btn.setVisibility(View.VISIBLE);
// Transfer failed
System.out.println(" failed ...");
}
// Jibble.
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode ==Activity.RESULT_OK
&& null != data) {
//uri=data.getData();
// System.out.println("Current image Path is ----->" + getRealPathFromURI(uri));
imagesPathList = new ArrayList<String>();
String[] imagesPath = data.getStringExtra("data").split("\\|");
try{
lnrImages.removeAllViews();
}catch (Throwable e){
e.printStackTrace();
}
for (int i=0;i<imagesPath.length;i++){
Log.e("imagesPath can", ""+imagesPath);
imagesPathList.add(imagesPath[i]);
Log.w("imagesPathList are", ""+imagesPathList);
yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
Log.d("yourbitmap is", ""+yourbitmap);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourbitmap);
imageView.setAdjustViewBounds(true);
lnrImages.addView(imageView);
String listString = "";
for (String s : imagesPathList)
{
listString += s + "\t";
}
j=listString.toString();
uri=Uri.parse(j);
r=uri.toString();
Log.d("mnmnmnmnmnmnmhjjuigyigsuiagducfuducgfasicfgds", ""+r);
Log.d("anananananananananananananananananananananannananand", ""+uri);
}
}
}
private void decodeFile(String picturePath) {
// TODO Auto-generated method stub
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
yourbitmap = BitmapFactory.decodeFile(picturePath, o2);
}}
Public class MainActivity extends Activity implements View.OnClickListener {
private LinearLayout lnrImages;
private Button btnAddPhots;
private Button btnSaveImages;
private ArrayList<String> imagesPathList;
private Bitmap yourbitmap;
private Bitmap resized;
private final int PICK_IMAGE_MULTIPLE = 1;
static final String FTP_HOST = "";
static final String FTP_USER = "";
static final String FTP_PASS = "";
String j;
Uri uri;
String str;
String picturepath, currentpath;
Button b;
String r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lnrImages = (LinearLayout) findViewById(R.id.lnrImages);
btnAddPhots = (Button) findViewById(R.id.btnAddPhots);
btnSaveImages = (Button) findViewById(R.id.btnSaveImages);
b = (Button) findViewById(R.id.btnSaveImages1);
btnAddPhots.setOnClickListener(this);
btnSaveImages.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnAddPhots:
Intent intent = new Intent(MainActivity.this,
CustomPhotoGalleryActivity.class);
startActivityForResult(intent, PICK_IMAGE_MULTIPLE);
break;
case R.id.btnSaveImages:
//upload multiple images
if (imagesPathList != null) {
if (imagesPathList.size() >= 1) {
for (int i = 0; i < imagesPath.length; i++) {
String strImg = imagesPath[i];
File f = new File("" + strImg);
Log.e("File", "" + f);
doFileUpload(f);
Log.d("saveimages", "" + imagesPathList);
}
Toast.makeText(
MainActivity.this,
imagesPathList.size()
+ " no of images are selected",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
MainActivity.this,
imagesPathList.size() + " no of image are selected",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, " no images are selected",
Toast.LENGTH_SHORT).show();
}
break;
}
}
public void doFileUpload(File f) {
FTPClient client = new FTPClient();
try {
client.connect(FTP_HOST, 21);
Log.e("clientconnect", "" + client);
client.login(FTP_USER, FTP_PASS);
Log.e("clientlogin", "" + client);
client.setType(FTPClient.TYPE_BINARY);
Log.e("clienttype", "" + client);
client.changeDirectory("/ramesh2/");
Log.i("", "$$$$$$$$$$$$$$$$$" + ("/ramesh2/"));
// int reply = client.getReplyCode();
client.upload(f, new MyTransferListener());
// Log.e("filenameupload", "" + photoFile);
Log.e("clientupload", "" + client);
// Log.e("file",""+fileName);
} catch (Exception e) {
e.printStackTrace();
try {
client.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public class MyTransferListener implements FTPDataTransferListener {
public void started() {
// btn.setVisibility(View.GONE);
// Transfer started
Toast.makeText(getApplicationContext(), " Upload Started ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" Upload Started ...");
}
public void transferred(int length) {
// Yet other length bytes has been transferred since the last time
// this
// method was called
Toast.makeText(getApplicationContext(),
" transferred ..." + length, Toast.LENGTH_SHORT).show();
// System.out.println(" transferred ..." + length);
}
public void completed() {
// btn.setVisibility(View.VISIBLE);
// Transfer completed
Toast.makeText(getApplicationContext(), " completed ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" completed ..." );
}
public void aborted() {
// btn.setVisibility(View.VISIBLE);
// Transfer aborted
Toast.makeText(getApplicationContext(),
" transfer aborted , please try again...",
Toast.LENGTH_SHORT).show();
// System.out.println(" aborted ..." );
}
public void failed() {
// btn.setVisibility(View.VISIBLE);
// Transfer failed
System.out.println(" failed ...");
}
// Jibble.
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_MULTIPLE
&& resultCode == Activity.RESULT_OK && null != data) {
// uri=data.getData();
// System.out.println("Current image Path is ----->" +
// getRealPathFromURI(uri));
imagesPathList = new ArrayList<String>();
imagesPath = data.getStringExtra("data").split("\\|");
try {
lnrImages.removeAllViews();
} catch (Throwable e) {
e.printStackTrace();
}
for (int i = 0; i < imagesPath.length; i++) {
Log.e("imagesPath can", "" + imagesPath);
imagesPathList.add(imagesPath[i]);
Log.w("imagesPathList are", "" + imagesPathList);
yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
Log.d("yourbitmap is", "" + yourbitmap);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourbitmap);
imageView.setAdjustViewBounds(true);
lnrImages.addView(imageView);
String listString = "";
for (String s : imagesPathList) {
listString += s + "\t";
}
j = listString.toString();
uri = Uri.parse(j);
r = uri.toString();
Log.d("mnmnmnmnmnmnmhjjuigyigsuiagducfuducgfasicfgds", "" + r);
Log.d("anananananananananananananananananananananannananand",
"" + uri);
}
}
}
I am trying to print multiple times base on inputted integer. I can print now once at a time but after trying to print multiple times the result is always printing only 1 times, and sometimes it is not printing.
MainActivity.java
//This is my global variable for printing
BluetoothAdapter mBTAdapter;
BluetoothSocket mBTSocket = null;
Dialog dialogProgress;
String BILL, TRANS_ID;
String PRINTER_MAC_ID;
final String ERROR_MESSAGE = "There has been an error in printing the bill.";
//The copyPrint is a String Var which will contain the inputted integer and it will convert into Int so it will become copyPrintIs.
int copyPrintIs = Integer.parseInt(copyPrint);
for(int x = 1; x <= copyPrintIs; x++){
printNow(thePrinted);
//Call the printNow and repeat calling on it base on inputted integer
//The thePrinted will contain String Text which will become the result of printing
}
and here is my code when the printNow function is called
public void printNow(String thePrintedvalue) {
try {
PRINTER_MAC_ID = "00:12:F3:19:4D:D8";
BILL = thePrintedvalue; //thePrintedvalue will be pass on BILL Var
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
dialogProgress = new Dialog(Ticketing.this);
try {
if (mBTAdapter.isDiscovering())
mBTAdapter.cancelDiscovery();
else
mBTAdapter.startDiscovery();
} catch (Exception e) {
Toast.makeText(this, "A: " + e, Toast.LENGTH_LONG).show();
}
System.out.println("BT Searching status :"
+ mBTAdapter.isDiscovering());
if (mBTAdapter == null) {
Toast.makeText(this, "Device has no bluetooth capability",
Toast.LENGTH_LONG).show();
} else {
if (!mBTAdapter.isEnabled()) {
Intent i = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i, 0);
}
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
} catch (Exception e) {
Toast.makeText(this, "B: " + e, Toast.LENGTH_LONG).show();
}
}
/********/
public void printBillToDevice(final String address) {
mBTAdapter.cancelDiscovery();
try { BluetoothDevice mdevice = mBTAdapter.getRemoteDevice(address);
Method m = mdevice.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);
mBTSocket.connect();
OutputStream os = mBTSocket.getOutputStream();
os.flush();
os.write(BILL.getBytes());
System.out.println(BILL);
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
mBTSocket.close();
setResult(RESULT_OK);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
// Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE,
// Toast.LENGTH_SHORT).show();
e.printStackTrace();
setResult(RESULT_CANCELED);
}
}
/********/
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("***" + device.getName() + " : "
+ device.getAddress());
if (device.getAddress().equalsIgnoreCase(PRINTER_MAC_ID)) {
mBTAdapter.cancelDiscovery();
dialogProgress.dismiss();
Toast.makeText(Ticketing.this,device.getName() + " Printing data", Toast.LENGTH_LONG).show();
printBillToDevice(PRINTER_MAC_ID);
}
}
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
};
All of the code above is inside on MainActivity.java.
I cant figure out where I need to put the loop so it will continue printing copies of paper.
Please help!
try this:
Remove the loop here.
for(int x = 1; x <= copyPrintIs; x++){
printNow(thePrinted);
//Call the printNow and repeat calling on it base on inputted integer
//The thePrinted will contain String Text which will become the result of printing
}
and then change this code
public void printBillToDevice(final String address) {
mBTAdapter.cancelDiscovery();
try { BluetoothDevice mdevice = mBTAdapter.getRemoteDevice(address);
Method m = mdevice.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);
mBTSocket.connect();
OutputStream os = mBTSocket.getOutputStream();
os.flush();
os.write(BILL.getBytes());
System.out.println(BILL);
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
mBTSocket.close();
setResult(RESULT_OK);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
// Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE,
// Toast.LENGTH_SHORT).show();
e.printStackTrace();
setResult(RESULT_CANCELED);
}
}
to this code
public void printBillToDevice(final String address) {
mBTAdapter.cancelDiscovery();
try { BluetoothDevice mdevice = mBTAdapter.getRemoteDevice(address);
Method m = mdevice.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);
mBTSocket.connect();
//this will do the code
int copyPrintIs = Integer.parseInt(copyPrint);
for (int x = 1; x <= copyPrintIs; x++) {
OutputStream os = mBTSocket.getOutputStream();
os.flush();
os.write(BILL.getBytes());
System.out.println(BILL);
SystemClock.sleep(4000);//This will pause every 4 seconds after printing once and the continue and pause again
}
copyPrint = "1";//This will change the copyPrint back to 1 value
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
mBTSocket.close();
setResult(RESULT_OK);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
// Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE,
// Toast.LENGTH_SHORT).show();
e.printStackTrace();
setResult(RESULT_CANCELED);
}
}
I, will be asking how to combine/fuse 2 java files if,the outstring was initiated in the BluetoothcommandService.java file I will be editing my Post sir and post my MainActivity.java file and BluetoothCommandService.java file..I just doent know how to combine it..
this is the MainActivity.java
public class MainActivity extends Activity {
//public class MainActivity extends Activity implements OnClickListener {
BluetoothAdapter BTAdapter;
BluetoothDevice BTDevice;
private TextView title;
private static final int REQUEST_DEVICE_CONNECT = 1;
private static final int REQUEST_ENABLE_BLUETOOTH = 2;
private BluetoothCommandService commandService = null;
private String connectedDeviceName = null;
//Message types sent from the Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final int RECIEVE_MESSAGE = 6;
//Will be used in BluetoothCommandSrvice jave file
public static final String TOAST = "toast";
public static final String DEVICENAME = "device name";
//#######for the controller
public static final String tagStateCTRL = "Controller";
private OutputStream outStream = null;
private static final UUID myUUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static String address = "00:00:00:00:00:00"; // Insert your bluetooth devices MAC address
private StringBuilder sb = new StringBuilder();
Button btn_d1_on, btn_d1_off;
//for changing the device_1 name
TextView device1;
Button change;
EditText renameDevice;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main); gi move sa ubos sa request window
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
title = (TextView) findViewById(R.id.title_left_text); // Set up the custom title
title.setText(R.string.app_name); // Set up the custom title
title = (TextView) findViewById(R.id.title_right_text); // Set up the custom title
//Button openButton = (Button)findViewById(R.id.open);
//##########for the controller
btn_d1_on = (Button) findViewById(R.id.device1_on);
btn_d1_off = (Button) findViewById(R.id.device1_off);
//########for changing the device_1 name
device1 = (TextView)findViewById(R.id.device1);
change = (Button)findViewById(R.id.buttonTest);
renameDevice = (EditText)findViewById(R.id.editTest);
change.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String change_device1 = renameDevice.getText().toString();
device1.setText(change_device1);
}
});
// AUTO REQUEST OF ENABLING THE BLUETOOTH
BTAdapter = BluetoothAdapter.getDefaultAdapter();
//A code that will detect if BT is enabled otherwise will require it.
if (BTAdapter == null)
{
//Toast.makeText(context, text, duration)
Toast.makeText(this, "No Bluetooth adapter is available.", Toast.LENGTH_LONG).show();
finish();
return;
}
//##########for the controller
btn_d1_on.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//sendData("1");
//Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
//msg.show()
btn_d1_on.setEnabled(false);
sendData("1");
}
});
//##########for the controller
btn_d1_off.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//sendData("0");
//Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
//msg.show();
btn_d1_off.setEnabled(false);
sendData("0");
}
});
}
#Override
protected void onStart() {
super.onStart();
//Requesting Bluetooth automatically when its not yet enabled.
if (!BTAdapter.isEnabled())
{
Intent enableIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableIntent, 0);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}
else
{
if (commandService == null)
setupCommand();
}
}
//if (BTAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
//{
//Intent discoverableIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
//startActivity(discoverableIntent);
//}
#Override
protected void onResume() {
super.onResume();
if (commandService != null)
{
if (commandService.getState() == BluetoothCommandService.stateNothing)
{
commandService.start();
}
}
}
private void setupCommand()
{
commandService = new BluetoothCommandService(this, bluetoothHandler);
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (commandService != null)
commandService.stop();
}
private void ensureDiscoverable()
{
//Get the current Bluetooth scan mode of the local Bluetooth adapter. The Bluetooth scan mode determines if the local adapter is connectable and/or discoverable from remote Bluetooth devices.
if (BTAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
{
Intent ensureDiscoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
ensureDiscoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(ensureDiscoverableIntent);
}
}
//This gets information back from the "BluetoothChatService"/"BluetoothCommandService"
//#SuppressLint("HandlerLeak")
//private final Handler bluetoothHandler = new Handler(new Handler.Callback()
#SuppressLint("HandlerLeak")
public final Handler bluetoothHandler = new Handler()
{
#Override
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case MESSAGE_STATE_CHANGE:
switch (msg.arg1)
{
case BluetoothCommandService.stateConnected:
title.setText(R.string.title_connectedTo);
title.append(connectedDeviceName);
break;
case BluetoothCommandService.stateConnecting:
title.setText(R.string.title_connecting);
break;
case BluetoothCommandService.stateListen:
case BluetoothCommandService.stateNothing:
title.setText(getString(R.string.title_notConnected));
break;
}
break;
case MESSAGE_DEVICE_NAME:
connectedDeviceName = msg.getData().getString(DEVICENAME);
Toast.makeText(getApplicationContext(), "Connected to " + connectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
break;
case RECIEVE_MESSAGE: // if receive message
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
if (endOfLineIndex > 0) { // if end-of-line,
//String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
//txtArduino.setText("Data from Arduino: " + sbprint); // update TextView
//1/4/14
btn_d1_on.setEnabled(true);
btn_d1_off.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
//return false;
}
};
//});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_DEVICE_CONNECT:
// When DeviceList Activity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = BTAdapter.getRemoteDevice(address);
// Attempt to connect to the device
commandService.connect(device);
}
break;
case REQUEST_ENABLE_BLUETOOTH:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupCommand();
} else {
// User did not enable Bluetooth or an error occured
Toast.makeText(this, R.string.notEnabledBluetooth, Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
//Creating an Option Menu for connectivity and discoverability of a BT device
public boolean onCreateOptionsMenu(Menu menu)
{
//MenuInflater is a class
MenuInflater OptionMenu = getMenuInflater();
//OptionMenu.inflate(menuRes, menu)
OptionMenu.inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.connect:
Intent serverIntent = new Intent(this, DeviceList.class);
//this.startActivityForResult(serverIntent, REQUEST_DEVICE_CONNECT);
startActivityForResult(serverIntent, REQUEST_DEVICE_CONNECT);
return true;
case R.id.discoverable:
ensureDiscoverable();
return true;
//case R.id.abouts:
//Intent intentabouts = new Intent(this,abouts.class);
//return true;
//default:
//return super.onOptionsItemSelected(item);
}
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
commandService.write(BluetoothCommandService.VOL_UP);
return true;
}
else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
commandService.write(BluetoothCommandService.VOL_DOWN);
return true;
}
return super.onKeyDown(keyCode, event);
}
//#########################################
private void sendData(String message)
//public void sendData(String message)
{
byte[] msgBuffer = message.getBytes();
Log.d(tagStateCTRL, "...Sending data: " + message + "...");
try {
outStream.write(msgBuffer);
}
catch (IOException e){
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + myUUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getBaseContext(),
title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
finish();
}
//#########################################
}
This is the BluetoothCommanService.java
public class BluetoothCommandService {
private final BluetoothAdapter BTAdapter;
private final Handler bluetoothHandler;
private int connectionState;
private ConnectThread connectThread;
//private ConnectedThread connectedThread;
public ConnectedThread connectedThread;
//***Added 12/27/13
private AcceptThread mainAcceptThread;
//connection states of the Bluetooth
public static final int stateNothing = 0; //doing nothing
public static final int stateListen = 1; //listening for incoming connections
public static final int stateConnecting = 2; //initiating an outgoing connection
public static final int stateConnected = 3;
//constants that indicate command to computer
public static final int exitCMD = -1;
public static final int VOL_UP = 1;
public static final int VOL_DOWN = 2;
private static final boolean D = true;
private static final String tagState = "BluetoothCommandService";
//universally unique identifier (UUID)
//The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination
//private static final UUID myUUID = UUID.fromString("04c6093b-0000-1000-8000-00805f9b34fb");
private static final UUID myUUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
//Name for the SDP (don;t know what is it) record when creating server socket
private static final String name = "BluetoothCommand";
public BluetoothCommandService(Context context, Handler handler) { // context == UI Activity Context && handler == send message back to the UI Activity
BTAdapter = BluetoothAdapter.getDefaultAdapter();
connectionState = stateNothing;
bluetoothHandler = handler;
}
private synchronized void setState(int state) { // state == current connection state; an integer
if (D) Log.d(tagState, "setState() " + connectionState + " -> " + state);
connectionState = state;
//Give the new state to the Handler so that the UI Activity can update
//bluetoothHandler.obtainMessage(what, arg1, arg2)
bluetoothHandler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
public synchronized int getState() { //return the current connection state
return connectionState;
}
public synchronized void start() {
if (D) Log.d(tagState, "start");
// Cancel any thread attempting to make a connection
if (connectThread != null)
{
connectThread.cancel();
connectThread = null;
}
// Cancel any thread currently running a connection
if (connectedThread != null)
{
connectedThread.cancel();
connectedThread = null;
}
// Start the thread to listen on a BluetoothServerSocket
if (mainAcceptThread == null)
{
mainAcceptThread = new AcceptThread();
mainAcceptThread.start();
}
setState(stateListen);
}
//device == the BluetoothDevice to connect
public synchronized void connect(BluetoothDevice device) {
if (D) Log.d(tagState, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (connectionState == stateConnecting) {
if (connectThread != null)
{
connectThread.cancel();
connectThread = null;
}
}
// Cancel any thread currently running a connection
if (connectedThread != null)
{
connectedThread.cancel();
connectedThread = null;
}
// Cancel the accept thread because we only want to connect to one device
if (mainAcceptThread != null)
{
mainAcceptThread.cancel();
mainAcceptThread = null;
}
// Start the thread to connect with the given device
connectThread = new ConnectThread(device);
connectThread.start();
setState(stateConnecting);
}
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
if (D) Log.d(tagState, "connected");
// Cancel the thread that completed the connection
if (connectThread != null)
{
connectThread.cancel();
connectThread = null;
}
// Cancel any thread currently running a connection
if (connectedThread != null)
{
connectedThread.cancel();
connectedThread = null;
}
if (mainAcceptThread != null)
{
mainAcceptThread.cancel();
mainAcceptThread = null;
}
// Start the thread to manage the connection and perform transmissions
connectedThread = new ConnectedThread(socket);
connectedThread.start();
Message msg = bluetoothHandler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.DEVICENAME, device.getName());
msg.setData(bundle);
bluetoothHandler.sendMessage(msg);
setState(stateConnected);
}
public synchronized void stop() {
if (D) Log.d(tagState, "stop");
if (connectThread != null)
{
connectThread.cancel();
connectThread = null;
}
if (connectedThread != null)
{
connectedThread.cancel();
connectedThread = null;
}
if (mainAcceptThread != null)
{
mainAcceptThread.cancel();
mainAcceptThread = null;
}
setState(stateNothing);
}
public void write(byte[] out) {
ConnectedThread r;
synchronized (this) {
if (connectionState != stateConnected) return;
r = connectedThread;
}
r.write(out);
}
public void write(int out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (connectionState != stateConnected) return;
r = connectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
private void connectionFailed() {
setState(stateListen);
// Send a failure message back to the Activity
Message msg = bluetoothHandler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Unable to connect device");
msg.setData(bundle);
bluetoothHandler.sendMessage(msg);
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
setState(stateListen);
Message msg = bluetoothHandler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Device connection was lost");
msg.setData(bundle);
bluetoothHandler.sendMessage(msg);
}
private class ConnectThread extends Thread {
private final BluetoothSocket connectThread_socket;
private final BluetoothDevice connectThread_device;
public ConnectThread(BluetoothDevice device) {
connectThread_device = device;
BluetoothSocket tmp = null;
//Get a BluetoothSocket for a connection w/ the given BT device
//try {
//catch (IOException e) {
//Log.e(tag, msg, tr)
//Log.e(tagState, "create() failed", e);}
//Added 12/28/13
Method m;
try {
m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connectThread_socket = tmp;
}
public void run() {
Log.i(tagState, "BEGIN ConnectThread");
setName("ConnectThread");
BTAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
connectThread_socket.connect();}
catch (IOException e) {
connectionFailed();
try {
connectThread_socket.close();
} catch (IOException e2) {
Log.e(tagState, "Unable to close() socket during connection failure", e2);
}
BluetoothCommandService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothCommandService.this) {
connectThread = null;
}
// Start the connected thread
connected(connectThread_socket, connectThread_device); //ERROR: will still create "connected"
}
public void cancel() {
try {
connectThread_socket.close();
} catch (IOException e) {
Log.e(tagState, "close() of connect socket failed", e);
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket connectedThread_socket;
private final InputStream connectedThread_inStream;
private final OutputStream connectedThread_outStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(tagState, "create ConnectedThread");
connectedThread_socket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(tagState, "temp sockets not created", e);
}
connectedThread_inStream = tmpIn;
connectedThread_outStream = tmpOut;
}
public void run() {
Log.i(tagState, "BEGIN ConnectedThread");
byte[] buffer = new byte[1024]; // WALA JUD KO KASABOT ANI MAN :D
while (true) {
try {
int bytes = connectedThread_inStream.read(buffer);
bluetoothHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(tagState, "disconnected", e);
connectionLost(); //ERROR: will still create "private void CONNECTIONLOST"
break;
}
}
}
public void write(byte[] buffer) {
try {
connectedThread_outStream.write(buffer);
} catch (IOException e) {
Log.e(tagState, "Exception during write", e);
}
}
public void write(int out) {
try {
connectedThread_outStream.write(out);
} catch (IOException e) {
Log.e(tagState, "Exception during write", e);
}
}
public void cancel() {
try {
connectedThread_outStream.write(exitCMD);
connectedThread_socket.close();
} catch (IOException e) {
Log.e(tagState, "close() of connect socket failed", e);
}
}
}
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket acceptThread_ServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
tmp = BTAdapter.listenUsingRfcommWithServiceRecord(name, myUUID);
} catch (IOException e) {
Log.e(tagState, "listen() failed", e);
}
acceptThread_ServerSocket = tmp;
}
public void run() {
if (D) Log.d(tagState, "BEGIN mainAcceptThread" + this);
setName("AcceptThread");
BluetoothSocket socket = null;
while (connectionState != stateConnected) {
try {
socket = acceptThread_ServerSocket.accept();
} catch (IOException e) {
Log.e(tagState, "accept() failed", e);
break;
}
if (socket != null) {
synchronized (BluetoothCommandService.this) {
switch (connectionState) {
case stateListen:
case stateConnecting:
connected(socket, socket.getRemoteDevice());
break;
case stateNothing:
case stateConnected:
try {
socket.close();
} catch (IOException e) {
Log.e(tagState, "Could not close unwanted socket", e);
}
break;
}
}
}
}
if (D) Log.i(tagState, "END mainAcceptThread");
}
public void cancel() {
if (D) Log.d(tagState, "cancel " + this);
try {
acceptThread_ServerSocket.close();
} catch (IOException e) {
Log.e(tagState, "close() of server failed", e);
}
}
}
}