So I have this really weird problem that I simply cannot understand why it doesn't work. I am building a strobe light as part of my app and have created a separate Strobelight class. When I call the turnOn method or update method, the intervals never are changed. I guess it would make it easier to explain using some code:
public class Strobelight{
private int delayOn, delayOff;
public void turnStrobeOn(){...}
public void update(int a_delayOn, int a_delayOff){
delayOn = a_delayOn;
delayOff = a_delayOff;
}
public void turnOn(int a_delayOn, int a_delayOff){
delayOn = a_delayOn;
delayOff = a_delayOff;
this.turnStrobeOn();
}
Depending on whether the strobe light is already on or not, one of these methods are called to change turn on the strobe light with the specified intervals or simply to change the intervals.
Instead of changing the intervals to something custom, the application just uses the smallest possible intervals when calling Thread.sleep() for the flashlight being on or off
EDIT: this is the thread code, and code that turns the flashlight on
public void turnStrobeOn(){
for ( int i = 0; i < 3; i++){
isInCycle = true;
cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview(); // the flashlight is now on
lightIsOn = true;
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(delayOn);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
cam.stopPreview();
cam.release();
lightIsOn = false;
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(delayOff);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
} //end of for loop
isInCycle = false;
} // end of turnStrobeOn
You might want to get someone else's advice on this buy my best guess is that you can't be so specific on sleep(). Also don't forget to use miliseconds for that. I'd suggest using the android handler and doing postDelayed for this instead of sleeping.
How to pause / sleep thread or process in Android?
Related
Need To Do One Animation, Sleep 1000 Then Do The Next Sleep 1000 And So On, Instead It Sleeps For The Entire Time Then Plays All Animations At Once. No Idea What Im Doing.
Tried Timers, Running The Animation Before The tread.sleep And Using A While Loop Instead Of A For.
private void playLaunchAnimation()
{
final Animation animation = AnimationUtils.loadAnimation(this, R.anim.fadein);
for(int i=0; i < buttons.size();i++)
{
try {
Thread.sleep(1000);
buttons.get(i).startAnimation(animation);
} catch (Exception e){
/*
main declares that it throws InterruptedException. This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch InterruptedException.
*/
}
}
}
Hi, Make sure this code helps you
public static void main(String[] args) throws Exception {
for(int i=0; i < 10;i++) {
try {
Thread.sleep(1000);
System.out.println(i);
if(i==9) {
i=0;
}
} catch (Exception e){
System.out.println("error");
}
}
}
(Answer assumes Android which wasn't entirely clear in OP.)
This is somewhat of a lazy way to do it - but maybe get you thinking. It would
be more interesting to have the handler invoke the next handler so only one handler is declared - but that would be a little more work.
private void playLaunchAnimation() {
final Animation animation = AnimationUtils.loadAnimation(this, R.anim.fadein);
for(int i=0; i < buttons.size();i++)
{
// Create a handler on the UI thread to execute after a delay.
// The delay is a function of loop index.
//
// It may be necessary to declare buttons final - but your
// OP did not list where it is defined.
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
buttons.get(i).startAnimation(animation);
}
}, ((i+1)*1000));
}
}
References:
How to call a method after a delay in Android
Android basics: running code in the UI thread
It sounds like you are calling Thread.Sleep from the User Interface thread. This will ultimately result in the entire User Interface freezing up for the duration of the sleep. What you really want is to launch sleep from a background thread.
For example:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
for(int i=0; i < buttons.size();i++)
{
try {
Thread.sleep(1000);
activity.runOnUiThread(new Runnable() {
buttons.get(i).startAnimation(animation);
});
} catch (Exception e){}
}
});
Another way you could do this using post delay:
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
buttons.get(i).startAnimation(animation);
new android.os.Handler().postDelayed(this, 1000);
}
},
1000);
I'm developing my first android game without xml files for layouts in eclipse. This is calling MyGameView.class(extends View) from MyGameActivity.class(extends View implements OnTouchListener)
MyGameView myView;
myView = new MyGameView(this);
myView.setOnTouchListener(this);
setContentView(myView);
Everytime, I touch (MotionEvent.ACTION_DOWN), I update the Canvas in MyGameView.class with the following code. This is the code I use to update MyGameView.class from MyGameActivity.class.
myView.invalidate();
Yes it works!But I got a serious problem now.I need to move Canvas in MyGameView.class by every 0.3 second.I use Thread to update but it forced stop!!!! I tried again and again and again! I failed!
public void runtime() {
i = 0;
Thread timer = new Thread(new Runnable() {
#Override
public void run() {
while (i<1500) {
try {
Thread.sleep(300);
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
if (right) {
i++;
//This is static int a from MyGameView.
MyGameView.a += 2;
myView.invalidate();
}
else {
i = 1500;
}
}
}
}
});
timer.start();
}
Updating Static int or boolean to MyGameView.class from MyGameActivity.class with myView.invaldate(); is working. But I can't control it with Thread! Is there something wrong with my Thread running code?
It's probably up to Thread because I can move +2 along X-axis to right everytime I press (MotionEvent.ACTION_DOWN).
//I can Move with this code but not with Thread!
case MotionEvent.ACTION_DOWN:
MyGameView.a += 2;
myView.invalidate();
break;
With Thread, it stops! Please give me a solution for this! In other words, I need to count with time without error and update canvas on every count!
Invalidate must be called from the UI thread. Try calling
postInvalidate()
instead.
See this for reference.
private void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
while (running) {
try {
checkPixel();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public void stop() {
this.running = false;
}
public void start() {
this.running = true;
}
So I have some code someone provided me to monitor the change in color in the middle of the screen. I want to essentially turn on/off checkPixel() after I press something like F9 but how can I do this without a GUI because I can't seem to find anything that allows this. I believe KeyListeners only work with GUIs?
EDIT: Ok so instead while I'm checking for pixel changes in the thread. Once a pixel change has been detected I want to cause create a "left click action" in checkPixel() then turn off the thread. Any help with this?
I guess you want functionality provided by JNativeHook library.
The library allows for grabbing a key from the backgrond.
I have a function which is meant to scroll my Image-view so that it falls 5 pixels every 0.1 seconds, however as soon as I run this function I get Sorry Application has stopped responding
You can check my code below.:
void startGameLoop(){
boolean alive=true;
while(alive){
int x = theSprite.getScrollX();
int y = theSprite.getScrollY();
y-=5;
theSprite.scrollTo(x, y);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Any help on this would be much appreciated.
If you put this code Thread.sleep(100); on the main thread that will happen.
Use a Handler with delay instead. The handler can change things like ImageView because it operates on the main Ui Thread.
Something like this..
private final Runnable timerRunnable = new Runnable() {
#Override
public void run() {
int x = theSprite.getScrollX();
int y = theSprite.getScrollY();
y-=5;
theSprite.scrollTo(x, y);
if (!closing)
startTimer();
}
};
handler = new Handler();
startTimer();
/**
* Start periodically callbacks.
*/
private void startTimer() {
runOnUiThreadDelay(timerRunnable, 400L);
}
public void runOnUiThreadDelay(final Runnable runnable, long delayMillis) {
handler.postDelayed(runnable, delayMillis);
}
I am following a guide that shows how to create a Pong game. There is a part, where I am supposed to create a Thread, and call a function that moves the ball.
This is the code I created:
package com.ozadari.pingpong;
public class PingPongGame extends Thread {
private Ball gameBall;
private PingPongView gameView;
public PingPongGame(Ball theBall,PingPongView mainView)
{
this.gameBall = theBall;
this.gameView = mainView;
}
#Override
public void run()
{
while(true)
{
this.gameBall.moveBall();
this.gameView.postInvalidate();
try
{
PingPongGame.sleep(5);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}}
The thread is called and working, but it doesn't print anything. I tried to cancel the infinte loop and make the loop run 100 times. After I wait a while, it prints to the screen as it should be after 100 runs, but it doesn't print anything in the middle.
What is the problem? How can I fix it?
Unsure from the code you've posted but anyway, you can use a handler and have it run once every second like so (change the time to what you want):
Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
//do your stuff here
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
http://developer.android.com/reference/android/os/Handler.html
You can also use a normal thread, and call start at the end.
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();