Which is best method to post delay when send message to Bluetooth? - android

I want to send five data to Bluetooth. First one is turn on and second one is turn off, third one is turn on, and so on... I want post delay between turn on and turn off (about 1 second). Which is best one to do it. Currently, I am using sleep in Thread class
for (int i=1;i<5;i++) {
try {
if(i%2==0){
send(1);
Thread.sleep(500);
}
else{
send(0);
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Related

Android live server connection status

Wondering if its possible to monitor constantly some wifi connection to a server (some ip and port) and display the status of the connection, that is if the server is accessible/responsive or not.
By displaying the status i mean updating some textview displaying either "server up" or "server down".
(something similar to the wifi icon next to the battery indication at the top right..)
the answer is to make a thread class, which will constantly call (with a while loop) an asynctask. The asynctask will (try to) connect to the mysql server. the connection will be successful or not and accordingly a textview or something will be updated in the UIthread (using runOnUiThread)
an example of the code for the thread:
class servlookthread extends Thread {
#Override
public void run() {
while (keeplookingserver){
lookforserver lserv = new lookforserver(); // this is the asynctask thread
try {lserv.execute().get();} catch (ExecutionException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();} //! .get() it waits until the asynctask finishes
try {Thread.sleep(4000);} catch (InterruptedException e) {e.printStackTrace();} // some delay, 4 seconds
}
return;
}
}
the keeplookingserver is a boolean, "global" variable used to control the execution of the thread.
hope this helps someone! although i think its not elegant, its working for me

Tasks.await() is not returning when expected

I am trying to save data into a Firebase RealtimeDatabase.
The process of saving is fine and works just well, but I was curious about an idea I had: To force the .setValue operation into a synchronous structure. I know, that that way isn't the best one, but I wanted to try it regardless of that fact.
So I came up with this code:
Thread t1 = new Thread(){
public void run(){
try {
Tasks.await(databaseReference.child("someChild").setValue(someObject));
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("finished");
}
In theory, that code snippet is intended to first set the value in the Database, then wait for the completion of that (through the Tasks.await()), and then print out **after that* the line "finished".
I wrapped the Tasks.await()-command in a second thread because when I don't, I get an exception which says something like "Tasks.await() must not be called in the main application thread".
But when I run the whole thing, it just gets stuck at t1.join();.
When I delete the t1.join();-statement, everything works just fine, but the second Thread (t1) isn't finished before the "finished"-output is there. I know why this is like that, but I am nontheless interested in a solution to that problem.

How to create a delay on click button with Esspresso tests

I'm really new with esspresso issues and I have a little question, I need to emulate that users click on a button, tree times, but with some delay. A Human, takes some time to click a button, maybe with one second delay.
Whats the better way to made that on an esspresso test? othere frameworks have sleep, and so on... but I think that espresso hasen't. Any idea?
--Edited:
I made this, but don't know if it's correct:
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Another way, but more clear, if you don't use thread.interrupt() is this:
SystemClock.sleep(millis)
for (int = i; i < numOfClicks; i++) {
onView(<matcher for your view>).perform(click());
SystemClock.sleep(1000);
}

Puzzle: Bluetooth data send interval shortened by half after each reconnect

I modified the standard Bluetoothchat example to send 4 bytes of data at a time to a bluetooth device every half a second. It works fine if I start the App fresh. However, there is a problem if I reconnect as follows:
While Bluetooth is connected, I click the connect button again on the menu and select the same device. This disconnects the bluetooth (not sure whether this is the right procedure to disconnect). Then, I connect again by selecting the device, and it will be reconnected. After reconnection, a very strange problem appears: instead of sending the data every half a second, it will send the data every quarter a second. If I go through the process again and reconnect, the time interval will become even shorter. It gets to a point that the bluetooth device on the receiving end can't keep up with the data. At this point, the only way out is to kill the app and restart again. Then everything becomes normal, till next time I try to reconnect again.
I have tried different things but nothing appear to fix this. For example, I made sure the thread sending the data is killed when disconnected so no multiple threads are sending the data. I was wondering whether the baud rate changed when reconnected, but then why would the baud rate affect the Thread.sleep(500); statement (which is responsible for controlling the half a second data send). Any help would be greatly appreciated.
Here is the code, the SendClass is created under the MainActivity:
class SendClass implements Runnable {
public void run() {
bytearr[0]=0;bytearr[1]=0;bytearr[2]=0;bytearr[3]=0;
while (!Thread.currentThread().isInterrupted()) {
if (mChatService==null || mChatService.getState()
!=BluetoothChatService.STATE_CONNECTED) {
continue;
} else {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mChatService.write(bytearr);
}
}//end of run
}//end of runnable
Then under STATE_CONNECTED:
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to,mConnectedDeviceName));
/*
if(sendingThread!=null){
//sendingThread.stop();
sendingThread.interrupt();
if(D) Log.i(TAG, "after sendingThread");
sendingThread = null;
}*/
sendingThread = new Thread(new SendClass());
sendingThread.start();
break;
As you can see, I tried to kill the thread before creating a new one but that didn't make any difference. Any suggestions?
You are creating a thread that never actually stops, even after you create a new thread and assign to the same variable that particular thread wont stop running.
You need to make sure that the thread will stop after it disconnects.
Here is my suggestion
Change your SendClass to:
class SendClass implements Runnable {
private boolean stopped = false;
public void setStopped(boolean s){
this.stopped = s;
}
public void run() {
bytearr[0]=0;bytearr[1]=0;bytearr[2]=0;bytearr[3]=0;
while (!Thread.currentThread().isInterrupted() && !stopped) {
if (mChatService==null || mChatService.getState() !=BluetoothChatService.STATE_CONNECTED) {
continue;
} else {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mChatService.write(bytearr);
}
}//end of run
}//end of runnable
Then when you start your thread keep the reference to the Runnable so you can call the setStopped(true); like this
SendClass sc = new SendClass();
sendingThread = new Thread(sc);
sendingThread.start();
When you disconnect the bluetooth dont forget to call sc.setStopped(true); so your thread will finish by not going into the while.

Changing postdelayed method every entrance

I have to change ttyS1 port's baudrate every second. So i need to wake-up remote machine on 9600 Bauds and after communicate with it on 19200 Bauds. But there is a time limit between wake-up signal and real data communication. I use Handler&Thread for this trick.
I done it and seems okay with Handler&Thread. I toggled postdelayed every entrance for 1 milliseconds and 500 milliseconds. But it works bad. Sometimes 1 milliseconds task takes almost 10-15 milliseconds.
Also i noticed that when i add "runOnUiThread" with some UI update, result goes worst like 30milliseconds.
Note: I need to send Wake-up signal everytime not just one time.
Any idea?
public void serial_query(){
try {
Runnable cookimageupdate = new Runnable(){
public void run(){
try {
if (mOutputStream != null) {
mSerialPort.close();
if (mLAP==0) //First LAP is used to HOLTEK Wake-Up. Second one is real data.
{mLAP=1; mSerialPort=new SerialPort(new File("/dev/ttyS1"), 9600, 0); mBufferbuf = (byte)0x00; mOutputStream.write(mBufferbuf);}
else {mLAP=0; mSerialPort=new SerialPort(new File("/dev/ttyS1"), 19200, 0); mOutputStream.write(mBuffer);}
} else {
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
}
try{
runOnUiThread(new Runnable() {
public void run() {
//meat_temp.setText(_meatprobe_temp.toString());
if (_pt1000_status==1) {pt_status.setText(" PT1000 open-circuit");}
else if (_pt1000_status==2){pt_status.setText(" PT1000 short-circuit");}
else if (_pt1000_status==0){pt_status.setText(" -");}
}
});
}
catch (Exception e)
{
e.getLocalizedMessage();
}
if (mLAP==1)
{handler_serial.postDelayed(this, 1);}
else {handler_serial.postDelayed(this, 500);}
}
};
handler_serial.postDelayed(cookimageupdate, 50); //start with 50mSec. delay
}
catch(Exception e){
e.printStackTrace();
return;
}
};
1 millisecond is too short a time delay to post a delayed runnable. Most handlers take more time than that to process your message.
For such low delays you would be better off using
Thread.sleep().

Categories

Resources