How do I loop a piece of code in my main activity?

2019-04-13 09:58发布

问题:

I am using Android Studio and I wanted to loop this every half a second

"Random rand = new Random(); 
int value = rand.nextInt(10);"

So anyway thanks for your time and if you can help that would be great. :)

Sincerely,
Igor

EDIT
Thanks everyone for the kind and helpful answers. I will choose the best answer soon after I try each one out. (Not with my computer right now) But once again, thank you all. Edit
For anyone having a similar problem I got it to work. Here is the final code. package sarju7.click;

import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.util.Random;


public class MainActivity extends ActionBarActivity {

    Random rand = new Random();
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Runnable r = new Runnable() {
            public void run() {
                int value = rand.nextInt(10);
                TextView t1 = (TextView) findViewById(R.id.clicker);
                t1.setText(Integer.toString(value));
                handler.postDelayed(this, 400);
            }
        };
        handler.postDelayed(r, 400);
    }

    }

Once again thanks everyone. You guys are the best. I love all of stack overflow!

回答1:

Random rand = new Random();
Handler handler = new Handler()

Runnable r=new Runnable() {
        public void run() { 
            int value = rand.nextInt(10);
            handler.postDelayed(this, 500);     
        }
    };

handler.postDelayed(r, 500);


回答2:

Use postDelayed(). For example, this activity shows a Toast every five seconds:

/***
  Copyright (c) 2012 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    http://commonsware.com/Android
 */

package com.commonsware.android.post;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class PostDelayedDemo extends Activity implements Runnable {
  private static final int PERIOD=5000;
  private View root=null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    root=findViewById(android.R.id.content);
  }

  @Override
  public void onResume() {
    super.onResume();

    run();
  }

  @Override
  public void onPause() {
    root.removeCallbacks(this);

    super.onPause();
  }

  @Override
  public void run() {
    Toast.makeText(PostDelayedDemo.this, "Who-hoo!", Toast.LENGTH_SHORT)
         .show();
    root.postDelayed(this, PERIOD);
  }
}

Your run() method of your Runnable is where you do the work and schedule the Runnable to run again after your desired delay period. Just call removeCallbacks() to end the looping. You can call postDelayed() on any widget; in my case, I am using the framework-supplied FrameLayout known as android.R.id.content, as this activity has no other UI.



回答3:

Use this

create this in onCreate

 Random rand = new Random();
handler=new Handler();

handler.postDelayed(myRunnable, 100);

declare it outside onCreate

myRunnable=new Runnable() {

        @Override
        public void run() {

           int value = rand.nextInt(10);
            handler.postDelayed(this, 100);
        }
    }


回答4:

While all of the answers here are good, they do not necessarily address why you want this or what you will do with the result. You can do this anywhere in your code, but you are probably asking because it will block the UI thread if it's run there and you probably don't want that.

You need to run this in the background on a different thread or service so the user can interact while the loop is running. That is the basic answer - run this loop on another thread besides the MAIN or UI thread. (There are a lot of answers here that address that.)

If you want a random number to display on the screen every half second, then a lot of these options are fine except they don't explain that if you run them in a different thread, then you need to create the class in your Activity and then use the runOnUiThread thread method to update your view classes (otherwise you will get errors).

If you want to use it as the start to doing further background processing, you should consider a Service where you can expand the functionality of your loop and whatever other tasks it may need to perform while the UI thread is running. For example, if you are needing random numbers to select images that are displayed on the screen, you may want to run this in a service that provides images to the Activity.

Hope that helps.