0

I have a runnable that I want to execute 4 times a second. Here is my runnable:

shoot = new Runnable() {
        @Override
        public void run() {
            //Add bullet
            parts.add(new Part(1, (int)(screenWidth*.01),
                    Part.TYPE_CIRCLE, (int)parts.get(activeShooter).center.x,
                    (int)parts.get(activeShooter).center.y));
            parts.get(parts.size()-1).x_vel = (int)(Math.cos(parts.get(activeShooter).rotation)*bulletSpeed);
            parts.get(parts.size()-1).y_vel = (int)(-Math.sin(parts.get(activeShooter).rotation)*bulletSpeed);
            activeShooter = (activeShooter == numShooters) ? 0 : activeShooter + 1;
            shooter.postDelayed(shoot, 250);
        }
    };

And here is my initial handler setup:

private void startBullets(){
    Looper.prepare();
    shooter = new Handler();
    shooter.postDelayed(shoot, 250);
}

In all my other projects, I didn't have to call Looper.prepare but it throws an exception if I don't in this project. I don't know why. I basically copied a working code from another project (one that didn't require me to call Looper.prepare()). Can anyone see why my runnable isn't executing?

sadelbrid
  • 411
  • 1
  • 4
  • 16

1 Answers1

0
private void startBullets(){
    shooter = new Handler();
    shooter.postDelayed(shoot, 250);
}

Make sure you quit your Looper via Looper.quit() when you're done.

Gennadii Saprykin
  • 4,505
  • 8
  • 31
  • 41
  • That seemed to interrupt my main timer because when I added Looper.loop() the program stopped updating. (normally updates 60 times a second) – sadelbrid Aug 01 '15 at 00:36
  • can you show how you use startBullets method? is this a background thread? – Gennadii Saprykin Aug 01 '15 at 04:44
  • `if(!readyToShoot){ /*random stuff*/ } else { startBullets(); } }` This task is run on the main thread I believe. I'm not super familiar with threads but the flow of my program is this: splashscreen displays, then I use an intent to enter my InGame class - which holds the object of the class I'm having trouble with the handler/runnable. The line shown is in a method that gets called about 60 times a second via a timer scheduled in my InGame class. – sadelbrid Aug 01 '15 at 05:44
  • on the UI thread you don't need to prepare Looper at all, it's already there. Just create a ui handler and use it.. I've updated my answer – Gennadii Saprykin Aug 02 '15 at 00:18