When i click the button ,I want an callback to capture again every 5 seconds. this is my code
but when i try to click again the camera is not shown.
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable, 5000); // called after 5 seconds
button.setText("Waiting...");
}};
There is no certain timer programmatically for the Camera . so the best thing is that you should create a thread for the camera Action and then repeat that thread after 5 seconds
Your code will trigger only one time ... so what you have to do is that after creation of thread call that thread on button click and the thread will run automatically....
private Handler handler = new Handler();
runnable.run();
private Runnable runnable = new Runnable()
{
public void run()
{
//
// Do the stuff
//
handler.postDelayed(this, 1000);
}
};
Related
So I am trying to start my sensor reading method after 10 seconds and stop it after say 5 minutes. This is the code for the same.
case R.id.btn_pos_poll_side: {
final Handler handler = new Handler();
//Delay Runner Here
handler.postDelayed(new Runnable() {
#Override
public void run() {
side_output.setText("Delayed Data Collection");
//Start reading LIGHT SENSOR Data, Handle Null Light Sensor Data
if (LightSensor != null || mProximity != null || mAccelerometer != null || mGyroscope != null) {
//listen to light sensor.
mySensorManager.registerListener(
MultiSensorListener,
LightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
//listen to proximity sensor.
mySensorManager.registerListener(
MultiSensorListener,
mProximity,
SensorManager.SENSOR_DELAY_NORMAL);
//listen accelerometer, note this has 3-axes.
mySensorManager.registerListener(
MultiSensorListener,
mAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
//listen gyroscope, note this has 3-axes.
mySensorManager.registerListener(
MultiSensorListener,
mGyroscope,
SensorManager.SENSOR_DELAY_NORMAL);
//print output text
side_output.setText(Html.fromHtml("<h3> ----- Data Collection Session Starts Here -----</h3>"));
} else {
side_output.setText("No Sensor Found!");
}
}
}, 10000);
final Handler closeHandler = new Handler();
//Data Sender Runner Here
closeHandler.postDelayed(new Runnable() {
#Override
public void run() {
Button stopCollection = (Button) findViewById(R.id.btn_stop_poll_side);
stopCollection.performClick();
}
}, 120000);
break;
}
However this never works and even the data collected is somewhat corrupt (new data is concatenated to previous data).
What am I doing wrong?
Thanks.
Edit: Some more details. I want to start it after 10 seconds from when I have pressed the button and stop it after say 2 minutes. This happens only once unless I press the button again.
Added: Stop Button Logic
case R.id.btn_stop_poll_side: {
// remove sensor listener
mySensorManager.unregisterListener(MultiSensorListener,
LightSensor);
mySensorManager.unregisterListener(MultiSensorListener,
mProximity);
mySensorManager.unregisterListener(MultiSensorListener,
mAccelerometer);
mySensorManager.unregisterListener(MultiSensorListener,
mGyroscope);
side_output.append("\n" + sensorReading);
/*
Reading data and writing to Dropbox!
*/
new DropboxTask(side_output, "Back Pocket Data Reading", sensorReading).execute();
break;
}
When user presses the button the first time:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// Do what you need to do
}
}
handler.postDelayed(runnable, 10_000 /* Wait 10 seconds */);
When the user presses the button the second time:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// Stop what you want to stop
}
}
handler.postDelayed(runnable, 2*60*1000 /* Wait 2 minutes */);
This has to be done in the onClick of your button:
First define a private boolean like called isButtonAlreadyClicked = false.
Now:
yourButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if(!isButtonAlreadyClicked) {
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// Do what you need to do
}
}
handler.postDelayed(runnable, 10_000 /* Wait 10 seconds */);
isButtonAlreadyClicked = true;
} else {
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// Stop what you want to stop
}
}
handler.postDelayed(runnable, 2*60*1000 /* Wait 2 minutes */);
isButtonAlreadyClicked = false;
}
});
EDIT:
If you want to prevent the runnable to be run while it is waiting, just make sure to declare the handler and your runnables outside of your method (inside your class), so that you can do (for example):
mHandler.removeCallbacks(firstRunnable);
mHandler.removeCallbacks(secondRunnable);
In that way it won't run the Runnables anymore.
Hi im trying to do an app that searchs bluetooth devices that are near every 5-10 seconds, so I tried to do an endless loop but the app is getting stuck when I press the button that starts the loop:
int stopInt=2;
serachB.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
do {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
listAdapter.clear();
getPairedDevices();
startDiscovery();
}
}, 4000);
} while (stopInt>1);
}
private final Handler mMyhandler = new Handler();
private final Runnable checkBluetoothRunnable = new Runnable() {
public void run() {
//Do your work here
mMyHandler.postDelayed(this, 5000);
}
};
serachB.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v){
mMyhandler.post(checkBluetoothRunnable);
}
}
}
Change it this way:
serachB.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
while(true){
listAdapter.clear();
getPairedDevices();
startDiscovery();
Thread.sleep(4000);
}
}
});
}}
You are continually creating new instances of Handler in your while loop which is going to eat up memory. I wouldn't be surprised if you were getting an OutOfMemoryError which is causing the termination. Try creating a single instance outside of your loop.
The Runnable passed to Handler runs on the UIThread since it was created on that thread. This should be avoided for lengthy operations and instead delegated to another thread.
When you create a new Handler, it is bound to the thread / message
queue of the thread that is creating it
Also, rather than using the Handler class you could potentially swap it out to use ScheduledThreadPoolExecutor which will give you a pool of threads which can then periodically execute your device discovery code.
Firstly create a ScheduledExecutorService:
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
Create an instance of your Runnable:
MyRunnable deviceDiscovery = new MyRunnable();
Then in your onClick method you kick off with scheduleAtFixedRate:
ScheduledFuture<?> future = scheduledExecutorService.scheduleAtFixedRate(deviceDiscovery, 0, 1, TimeUnit.MINUTES);
Then when you want to stop it running you need to call cancel on the ScheduledFuture:
future.cancel(true); // Set to true to say it can interrupt if already running
I wanted te delay the interstitial with 1 second after clicking on a button.
I used Thread.sleep() but it didnt work coz the message that it must be shown after clicking the button is also delayef.
I want to click on the button and wait the message 1 secobd then show the ad.
Maybe this is what you are looking for:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showMessage();
...
}
}, ms);
That will delay the operations in run() for the specified ms in milliseconds.
You can use Handler with postDelay. pass duration in milliseconds then run() will call after given duration.
Handler h = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// code that will run after 1 second(1000 ms)
}
};
h.postDelayed(r, 1000);
I have developed an android application which extracts single line text messages from the server. Once a button is clicked, it makes a function call which gets the next message from the server. Some of those messages are time based,
i.e those messages have to be displayed in the TextView for a particular amount of time and after that time is elapsed, it should automatically make the function call to get the next message from the server(i.e without the button being clicked).
Could someone please help me out in achieving this.
I tried using while loop as follows:
while(!presentTime.equals(expiryTime)){
calculatePresentTym(); //This method calculates the presentTime value
display.settext(the received instruction);
}
if(presentTime.equals(expiryTime))
(make the function call)
If I do this, nothing is being displayed till presentTime and expiryTime are equal. Once they are equal, the next instruction is automatically fetched by the function call and is displayed in the TextView.
Use a a handler
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
#Override
public void run() {
// do something
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
T0 cancel the run
m_handler.removeCallbacks(m_handlerTask); // to cancel the run
You can also use a timer but you will have to use runOnUiThread to update ui since timer runs on a different thread.
Timer _t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
//do something
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
//update ui
}
});
}
}, 1000, 1000 );
Note:
gets the next message from the server
Getting the message from server should be done on a background thread.
Edit:
While copy pasting the initialization part was missing. You have a counter i that is displayed in the textview. The counter increases by 1 every second. When it reaches 100 you cancel the run. Modify the below according to your requirements.
public class MainActivity extends Activity {
TextView tv;
Handler m_handler;
Runnable m_handlerTask ;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
m_handler = new Handler();
m_handlerTask = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(i<=100)
{
tv.setText(""+i);
i++;
}
else
{
m_handler.removeCallbacks(m_handlerTask);
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
}
}
Use a timer. Schedule the timer for repeated interval executions, and after each execution you can get the next text from the server and display the same.
Check the Timer reference scheduleAtFixedRate(TimerTask task, long delay, long period)
I set up event listener, for example: setOnClickListener like this
Button stopBtn = (Button)findViewById(R.id.stop);
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doMagic();
}
});
I would like to set this listener a timeout event on 10s if button is not pressed. Use case: i have button1 that activates this stopBtn listener for 10s and if timeout comes it becomes deactivated and i need to press button1 to make stopBtn active again.
Im probably doing it wrong:
final Handler myHandler = new Handler();
startBtn = (Button)findViewById(R.id.start);
myHandler.postDelayed(new Runnable() {
public void run() {
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG,"runned");
}
});
}
}, 10000);
After 10s im still able to click it and that is probably cos event listener is still attached. How can i detach it even if i don't know if its fired or not.
A delayed Runnable posted on a Handler could manage that:
myHandler.postDelayed(new Runnable() {
public void run() {
if(something happened) {
// magic work
} else {
// turn off the event
}
}
, 10000);
You can init the Handler as an instance variable by using this code:
final Handler myHandler = new Handler();
Delayed actions can be arranged by using a Handler. Specifically check the 2 methods: postAtTime(Runnable, long) and postDelayed(Runnable, long).
It is easy to create a Handler, just use its default constructor Handler handler = new Handler() within the Activity.onCreate(Bundle state). Then wrap your desired action into a Runnable and pass to the handler.