简体   繁体   English

如何在我的主要活动中循环一段代码?

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

I am using Android Studio and I wanted to loop this every half a second 我正在使用Android Studio,并且想每半秒循环一次

"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; 打包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! 我爱所有的堆栈溢出!

Use postDelayed() . 使用postDelayed() For example, this activity shows a Toast every five seconds: 例如,此活动每五秒钟显示一次Toast

/***
  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. run()Runnable run()方法中进行工作,并安排Runnable在所需的延迟时间后再次运行。 Just call removeCallbacks() to end the looping. 只需调用removeCallbacks()即可结束循环。 You can call postDelayed() on any widget; 您可以在任何小部件上调用postDelayed() in my case, I am using the framework-supplied FrameLayout known as android.R.id.content , as this activity has no other UI. 就我而言,我正在使用框架提供的FrameLayout称为android.R.id.content ,因为此活动没有其他UI。

Use this 用这个

create this in onCreate 在onCreate上创建

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

handler.postDelayed(myRunnable, 100);

declare it outside onCreate 在onCreate外部声明

myRunnable=new Runnable() {

        @Override
        public void run() {

           int value = rand.nextInt(10);
            handler.postDelayed(this, 100);
        }
    }
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);

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. 您可以在代码中的任何位置执行此操作,但是您可能会问,因为如果在其中运行UI线程并且您可能不希望这样做,它将阻塞UI线程。

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. 那是基本的答案-在MAIN或UI线程之外的另一个线程上运行此循环。 (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). 如果您希望每半秒在屏幕上显示一个随机数,那么这些选项中的许多选项都很好,只是它们不能解释如果您在其他线程中运行它们,则需要在Activity创建该类,然后使用runOnUiThread线程方法更新您的视图类(否则您将得到错误)。

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. 如果要使用它作为开始进行进一步的后台处理的起点,则应考虑使用Service ,在其中可以扩展循环的功能以及在UI线程运行时可能需要执行的其他任务。 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 . 例如,如果您需要随机数来选择屏幕上显示的图像,则可能要在向Activity提供图像的服务中运行它。

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM