Android how call function after amount of time in loop - android

I am new in Android programming, I used to program microcontroller, now I need a few assistance from you guys.
I want to call two function with delay after each function called repeatedly until the stop button pressed.
btnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//I want perform these series of function repeatedly
//until stop button pressed
while(true){
bluetoothDisconnect();
delay(3000);
bluetoothConnect();
delay(3000);
if(status == true){
break;
}
}
}
});
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
status = true;
}
});
Big Thanks,

You need to thread the code in btnStart otherwise it will lock the GUI. Sorry to not be more helpful, I write Android apps using Mono (C#), I am unsure how to do it in Java.

Try this:
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = false;
Thread t = new Thread(new Runnable() {
#Override
public void run() {
doLoop();
}
});
t.start();
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
status = true;
}
});
where
private void doLoop(){
do {
bluetoothDisconnect();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bluetoothConnect();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (!status);
}
and status is a global variable, FALSE by default (declared as boolean status = false)
This code works as a simple solution, however I'd suggest you to look at the AsyncTask class:
http://developer.android.com/guide/components/processes-and-threads.html

Create an handler to delay the task .
Create the runnable thread and run your handler like:
Handler mhandler=new Handler();
Runnable mRunnable=new Runnable() {
#Override
public void run() {
bluetoothDisconnect();
btnStart.performClick() ;
}
};
btnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//I want perform these series of function repeatedly
//until stop button pressed
while(true){
bluetoothconnect();
mhandler.postDelayed(mRunnable,3*1000);
if(status == true){
break;
}
}
}
});

Related

Run a timer infinitely until button pressed?

How can I add timed functionality that doesn't end unless the button is clicked again?
This runs a thread okay but it won't restart unless I go to another tab in the app and go back to it.
metroStartBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
metronomeOn = !metronomeOn;
if(metronomeOn)
{
final Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
while(!toExit){
// Your code
try {
playSound(getContext(), 1);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
else
{
toExit = true;
}
}
});
Because after the first run , toExit is true therefore your while loop will not execute after that
metroStartBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
metronomeOn = !metronomeOn;
if(metronomeOn)
{
final Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
while(metronomeOn){
// Your code
try {
playSound(getContext(), 1);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
}
});

How to perform click continuously while something is enable

I'm beginner... I need to run some code after 10 seconds continuously while my button is enable.
and when I clicked on it and it turned to disable-state, timer get stop.
I use below code but it run just once when I click on timerbutton every time again...
I think I have to use threed and I think I used it too! But I did not get to my goal.
private View.OnClickListener ontimerclicked = new View.OnClickListener() {
#Override
public void onClick(View view) {
Handler myHandler = new Handler();
myHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (endistimer==false) {
endistimer=true;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#E91E63"));
varbtnimgnext.performClick();
intdelay=10000;
}
else
{
endistimer=false;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#dddddd"));
intdelay=0;
}
}
}, intdelay);
}
};
I finaly solved it with below code.I put it for anothers:
private View.OnClickListener ontimerclicked = new View.OnClickListener() {
#Override
public void onClick(View view) {
mHandler = new Handler();
if (endistimer==false) {
endistimer=true;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#E91E63"));
}
else
{
endistimer=false;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#dddddd"));
intdelay=5000;
cntsec=0;
varbtnplusfive.setText(arrsec[0] +" Sec");
}
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (endistimer) {
try {
Thread.sleep(intdelay);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// your codes
// you can set continue_or_stop to false, for stop
}
});
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(slideword.this,e.toString(),Toast.LENGTH_SHORT);
}
}
}
}).start();
}
};

Android update TextView inside dialog in runOnUiThread

I have been spending couple hours to try to update the textview inside the dialog, but failed.
When the option is clicked, there are new dialog is shown, and inside the dialog, there are textviews and button, when I click the button, the textview will be update.
Here is the code related to the button onClick listener:
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < 50 ; i ++){
final String currentNum = String.valueOf(i + 1);
Thread t = new Thread() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(currentNum); //it is fine
currentNum.setText(currentNum); //it is the problem, the setText only work when the for loop is finished.
}
});
}
};
t.start();
}
}
});
Please let me know if you need more information. Thanks a lot in advance!
//it is a optionmenu
case R.id.action_refresh:
final TextView currentNum;
final ImageButton start;
String currentNum = Integer.toString(songList.size());
final Dialog lyricsAnalysis = new Dialog(this,R.style.cust_dialog);
lyricsAnalysis.requestWindowFeature(Window.FEATURE_NO_TITLE);
lyricsAnalysis.setContentView(R.layout.analysis);
lyricsAnalysis.setCancelable(true); //back button to cancel
lyricsAnalysis.setCanceledOnTouchOutside(true);
start = (ImageButton) lyricsAnalysis.findViewById(R.id.start);
//first value
currentNum.setText(String.valueOf(currentNum));
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < 50 ; i ++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateTextView(lyricsAnalysis,i);
}
}
});
lyricsAnalysis.show();
lyricsAnalysis.getWindow().setLayout(600, 1000);
break;
}
return super.onOptionsItemSelected(item); }
public void updateTextView(Dialog dialog, int i) {
final TextView currentNum = (TextView) dialog.findViewById(R.id.currentNum);
currentNum.setText(Stri`enter code here`ng.valueOf(i));
//return;
}
Try this method. This may helps you. It's work for me.(But I am not use this in dialog)
public void updateTextView(String toThis) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(toThis);
//return;
}
try like this
int elapsedtime=0;
boolean isTimerRunning=false;
Timer timerr;
inside onCreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//declare your textview here;
timerr=new Timer();
startTimer();
}
/*
* timer for displaying message bubble
*/
protected static void startTimer() {
isTimerRunning = true;
elapsedtime = 0;
// recordingseek.setProgress(0);
timerr.scheduleAtFixedRate(new TimerTask() {
public void run() {
// increase every sec
elapsedtime++;
mmHandler.obtainMessage(1).sendToTarget();
System.out.println("recording time" + elapsedtime);
if(elapsedtime==50)
timerr.cancel();
}
}, 1000, 2000);
};
public static Handler mmHandler = new Handler() {
public void handleMessage(Message msg) {
textview.setText(elapsedtime);
}
};
}
};

how to stop progressbar which run on runnable thread in android

I am developing a quiz application in which I am using runnable thread for seekbar functionality. seekbar shows how much time is remaining. Now I want to stop the seekbar when a answer button is click.
here is my code for runnable thread.
new Thread(new Runnable() {
public void run() {
while (seekbarStatus < 100) {
seekbarStatus = LoadingStatus();
// sleep 1 second to show the progress
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
seekbar.setProgress(seekbarStatus);
}
});
}
if (seekbarStatus >= 100) {
// sleep for 2 seconds, so that you can see the 100% of file download
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!(Ans_1.getTag()=="clicked" ||Ans_2.getTag()=="clicked" || Ans_3.getTag()=="clicked" ))
{
Ans_1.setEnabled(false);
Ans_2.setEnabled(false);
Ans_3.setEnabled(false);
Ans_1.setBackgroundColor(Color.GREEN);
points.setText("0 Punkt");
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
showDialogView();
}
}, SPLASH_DISPLAY_LENGHT);
}
}
public void showDialogView() {
// TODO Auto-generated method stub
dialog.show();
}
});
}
}
}).start();
please help me. Any help would be appreciated.
I am not getting how to solve it.
Thanks in advance.
Just add an instance variable:
private boolean isCancelled = false;
Then in the button onClick:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
isCancelled = true;
}
});
Then change
while (seekbarStatus < 100) {
to
while (seekbarStatus < 100 && !isCancelled) {

why thread creation is failed?

I want to turn on/off the flash light in infinite loop, so when it turned on it should wait for 5 seconds and then turned off then wait 5 seconds to turned on again, and so on...
how I can do that?
here is my code:
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// num = Integer.parseInt(n.getText().toString());
while(bl){
if(camera == null){
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
turnOn();
}
});
}
}).start();
}
else{
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
turnOff();
}
});
}
}).start();
}
}
}
});
I would recommend not using Threads in order to achieve this. Why not use the Runnable class and post it with a delay via a Handler? For example:
Handler handler = new Handler(); // make this a member variable of your class
boolean isOn = false; // make this a member variable of your class
final Runnable flashRunnable = new Runnable() {
#Override
public void run() {
if (isOn) {
turnOff();
isOn = false;
} else {
turnOn();
isOn = true;
}
handler.postDelayed(flashRunnable, 5000);
}
};
handler.postDelayed(flashRunnable, 5000);
If you need to run the code inside the Runnable on the UI thread, you even call postDelayed on a View instead of creating a Handler
Try something like so, using Executors instead of (ugly) Thread.sleep():
boolean cameraOn = true
final Runnable runnable = new Runnable() {
#Override
public void run() {
// your logic here:
// if (cameraOn) ...
// else ...
// cameraOn = !cameraOn
}
};
Executors.newScheduledThreadPool(1).schedule(new Runnable() {
#Override
public void run() {
runnable.run();
}
}, 5, TimeUnit.SECONDS);

Categories

Resources