Turn ON Flash light every second in Android? - android

I trying to turn ON the phone flash light every second. I have been searching but nothing found useful.
This is the code that I am using:
Thread t = new Thread() {
#Override
public void run() {
seconds = 0;
try {
while (seconds<11) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// Put code here!
seconds++;
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
I will really appreciate your help! Thanks.

Creating the loop is bad idea.
Try to use handler http://developer.android.com/reference/android/os/Handler.html
handler.postDelayed(Runnable r, long delayMillis)
use this at the and of runnable code.

Related

Set ProgressBar in Cursor while SQLite

How I can set dynamically set the progressbar status after reading a value from db SQLite?
I have this code.
int i = 0;
while (!c.isAfterLast()) {
i++;
pb.setProgress(i)
}
But my problem is that progress bar is update only at finish while so without "liveEffect"
You can use runOnUiThread method of Activity class:
runOnUiThread(new Runnable() {
#Override
public void run() {
pb.setProgress(i);
}
});
More here: https://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
Actually, execution time is too low that by live effect not appear . take large cursor around 10000 value then apply loop now you can see progress
I resolved my problem with Handler and Thread.sleep (for simulate live)
new Thread(new Runnable() {
public void run() {
do {
mProgressStatus++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(new Runnable() {
public void run() {
pb.setProgress(mProgressStatus);
}
);
} while (c.moveToNext());
}
}).start();

Wait for thread to finish and then move to next position

i am trying to display a Toast on the screen and when Toast fades off then move to the next question. I have tried with Thread but cannot seem to manage.
My code:
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getUserSelection()){
position = position + 3;
if (position < questionsArray.size()) {
curName = questionsArray.get(position).getName();
curArray = questionsArray.get(position).getAnswers();
curIscorrect = questionsArray.get(position).getIscorrect();
setupQuestionView(curName, curArray, curIscorrect);
} else {
StringGenerator.showToast(QuestionsActivity.this, "Your score : " + score + "/" + (questionsArray.size() / 3));
}
}else {
StringGenerator.showToast(QuestionsActivity.this, getString(R.string.noanswerselected));
}
}
});
and the getUserSelectionMethod:
private boolean getUserSelection() {
correct = (RadioButton)findViewById(group.getCheckedRadioButtonId());
if (correct == null){
return false;
}else {
correctAnswerText = correct.getText().toString();
if (map.get(correctAnswerText).equals(Constants.CORRECTANSWER)) {
score++;
setCorrectMessage();
return true;
} else {
setWrongMessage();
return true;
}
}
}
private void setCorrectMessage() {
correctToast = new Toast(QuestionsActivity.this);
correctToastView = getLayoutInflater().inflate(R.layout.correct, (ViewGroup) findViewById(R.id.correctRootLayout));
correctText = (TextView)correctToastView.findViewById(R.id.correctTextView);
correctText.setText(getString(R.string.correctAnswer));
correctToast.setDuration(Toast.LENGTH_SHORT);
correctToast.setView(correctToastView);
correctToast.show();
correctThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
correctToast.cancel();
}
});
correctThread.start();
}
private void setWrongMessage() {
wrongToast = new Toast(QuestionsActivity.this);
wrongToastView = getLayoutInflater().inflate(R.layout.wrong, (ViewGroup) findViewById(R.id.wrongRootLayout));
wrongText = (TextView)wrongToastView.findViewById(R.id.wrongTextView);
wrongText.setText(getString(R.string.wrongAnswer));
wrongToast.setDuration(Toast.LENGTH_SHORT);
wrongToast.setView(wrongToastView);
wrongToast.show();
wrongThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
wrongToast.cancel();
}
});
wrongThread.start();
}
Any suggestion on how to do this?
You can determine the toast visibility:
toast.getView().getWindowToken()
If the result is null, than your toast isn't visible anymore, and than you can run any code you want.
as stated in this answer you can start a thread that waits the duration of the Toast:
Thread thread = new Thread(){
#Override
public void run() {
try {
Thread.sleep(3500); // 3.5seconds!
// Do the stuff you want to be done after the Toast disappeared
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Toast.LENGTH_SHORT and Toast.LENGTH_LONG are only flags so you have to either hard code the duration or keep them in a constant. The durations are 3.5s (long) and 2s (short).
If you want to manipulate some of your views, you cannot do this in another thread than the "main" UI thread. So you have to implement a kind of callback/polling mechanism to get notified when the SleepThread has finished.
Check this answer to read about a couple of ways to do this. Probably the easiest of them to understand and implement is this:
After you started your Thread you can check if it is still alive and running by calling thread.isAlive(). In this way you can do a while loop that runs while the thread is running:
// start your thread
while(thread.isAlive()){}
// continue the work. The other thread has finished.
Please note that this is NOT the most elegant way to do this! Check the other possibilities in the answer I've mentioned above for more elegant solutions (especially the last one with the listeners is very interesting and worth reading!)
That's because the Thread class is purely executed in the background and you need to manipulate the view in the Main thread. To solve your issue just replace the Thread with AsynTask.
AsyncTask<Void,Void,Void> a = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
correctToast.cancel();
}
};
a.execute();
If you look at my code you can see my onPostExecute, this method is called in the Main Thread.
My Error was because i was trying to acess UI Elements through another Thread so modifying the code like this:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
QuestionsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
moveToNextQuestion();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
did the trick. I hope my answer helps someone!!!

how to start Asychoronous task in a thread finally block in android

i want to start Asynchoronous task after some sleep time. For that i am using thread and i start my asynchronous task in that thread finally block. But it gives cant create a handler inside a thread exception.
i am using the following logic.
thread= new Thread()
{
public void run()
{
try
{
int waited = 0;
while (waited < 300)
{
sleep(100);
waited += 100;
}
}
catch (InterruptedException e)
{
// do nothing
}
finally
{
Load ld=new Load();
ld.execute();
}
}
};
thread.start();
Well, first of all, if the final goal is to run AsyncTask after some delay, I would use Handler.postDelayed instead of creating separate Thread and sleeping there:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new Load().execute();
}
}, 300); //300ms timeout
But, if you really wanna make fun of Android, you can create HandlerThread - special thread which has looper in it, so your AsyncTask will not be complaining anymore:
thread= new HandlerThread("my_thread")
{
public void run()
{
try
{
int waited = 0;
while (waited < 300)
{
sleep(100);
waited += 100;
}
}
catch (InterruptedException e)
{
// do nothing
}
finally
{
Load ld=new Load();
ld.execute();
}
}
};
thread.start();
Please note that you are responsible for calling quit() on this thread. Also I'm not sure what happens if you quit this thread before AsyncTask is done. I don't remember where AsyncTask posts its results - to the main thread, or to the thread it was called from...
In any case, second option is just a mess, so don't do it:) Use the first one
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Do whatever you want.
}
}, SPLASH_TIME_OUT);
}
You can use like above. there SPLASH_TIME_OUT is the millisecond value that u want to make a delay.
Use Handler class, and define Runnable YourAsyncTask that will contain code executed after sleepTime
mHandler.postDelayed(YourAsyncTask, sleepTime);
You must run AsyncTask in UI thread, so you can use something like this:
class YourThread extends Thread{
private Activity _activity;
public YourThread(Activity _activity){
this activity = _activity;}
public void run()
{
try
{
int waited = 0;
while (waited < 300)
{
sleep(100);
waited += 100;
}
}
catch (InterruptedException e)
{
// do nothing
}
finally
{
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Load ld=new Load();
ld.execute();
}
});
}
}
}
and in your activity call thread like this:
YourThread thread = new YourThread(this);
thread.start();
also note: use soft reference to activity or do not forget kill thred when activity will be destroyed.
just do your like below code:
define a thread globally.
public static Thread thread;
thread= new Thread() {
public void run() {
sleep(time);
Message msg = setTextHandler.obtainMessage(2);
setTextHandler.sendMessage(msg);
}
};
thread.start();
and your handler look like
private final Handler setTextHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (thread!= null) {
thread.interrupt();
thread= null;
}
switch (msg.what) {
case 2: //do your work here
Load ld=new Load();
ld.execute();
break;
}
}
};

how to create a thread to refresh data in 3 second interval

I need a thread (it does httppost ,and parse the answer xml and refresh listview to set the changes from parsed xml) in 3 sec interval
I have already tried this code
Timer timer = new Timer();
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
try {
httpPostList(url);
saxParseList();
list.invalidateViews();
Thread.sleep(1000);
} catch (Exception ie) {
}
}
}, 1000, 1000 * 30);
I would appreciate you to create a Service with an AsyncTask in it.
Async Tasks are the Android Synonym to normal Java Tasks, Documentation finding here: http://developer.android.com/reference/android/os/AsyncTask.html
Services are Background Processes, seeing this Doc:
http://developer.android.com/reference/android/app/Service.html
Try using handlers:
Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
// ...
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
updateUI();
}
};
Thread thread = new Thread() {
#Override
public void run() {
while(true) {
Message msg = new Message();
handler.sendMessage(msg);
try {
sleep(3*1000); // 3 seconds
} catch (InterruptedException e) {
}
}
}
};
thread.start();
}
private synchronized void updateUI() {
// ...
}
Finally I made it using "Async task".

sleep function not working

I want to show 1 to 100 in a changeable text. I like to use sleep()function so that it looks like that it is increasing form 1 to 100. my code is
for(int i= 0;i<100;i++) {
scorelevel.setText(String.valueOf(i));
try{
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
but it did not show properly. Any help or suggestion is appreciated.
Don't block UI thread, use AsyncTask instead
Use Timer and TimerTask to perform any time based task.
You can start counter using runOnUiThread to update textView as:
private boolean mClockRunning=false;
private int millisUntilFinished=0;
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
while(mClockRunning)
{
Thread.sleep(1000L);// set time here for refresh time in textview
YourCurrentActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(mClockRunning)
{
if(millisUntilFinished==100)
{
mClockRunning=false;
millisUntilFinished=0;
}
else
{
millisUntilFinished++;
scorelevel.setText(String.valueOf(millisUntilFinished));//update textview here
}
}
};
}
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
You could use a TimerTask (link), too.

Categories

Resources