【问题标题】:How do I loop a piece of code in my main activity?如何在我的主要活动中循环一段代码?
【发布时间】:2015-08-15 13:50:07
【问题描述】:

我正在使用 Android Studio,我想每半秒循环一次

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

无论如何,感谢您的宝贵时间,如果您能提供帮助,那就太好了。 :)

此致
伊戈尔

编辑
感谢大家的友好和有用的答案。我会在尝试每个答案后尽快选择最佳答案。 (现在不是我的电脑)但是再次感谢大家。 编辑
对于任何有类似问题的人,我让它工作。这是最终的代码。 包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);
    }

    }

再次感谢大家。你们是最棒的。我喜欢所有的堆栈溢出!

【问题讨论】:

    标签: java android loops random


    【解决方案1】:

    使用postDelayed()。例如,此活动每五秒显示一个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);
      }
    }
    

    Runnablerun() 方法是您执行工作并安排 Runnable 在所需延迟期后再次运行的地方。只需调用removeCallbacks() 即可结束循环。您可以在任何小部件上调用postDelayed();就我而言,我使用的是框架提供的 FrameLayout,称为 android.R.id.content,因为此活动没有其他 UI。

    【讨论】:

      【解决方案2】:
      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);
      

      【讨论】:

      • run() 中添加条件,仅当条件为真时才调用postDelayedif (condition) { handler.postDelayed(this, 500); }
      • 我不认为使用 if 条件会在代码运行后停止代码。它只会在条件为 True 且永不停止时启动代码。
      【解决方案3】:

      使用这个

      在 onCreate 中创建它

       Random rand = new Random();
      handler=new Handler();
      
      handler.postDelayed(myRunnable, 100);
      

      在 onCreate 外部声明

      myRunnable=new Runnable() {
      
              @Override
              public void run() {
      
                 int value = rand.nextInt(10);
                  handler.postDelayed(this, 100);
              }
          }
      

      【讨论】:

      • 只是一个简单的问题,我应该把它放在哪里?在我的 onCreate 还是其他地方?
      【解决方案4】:

      虽然这里的所有答案都很好,但它们不一定能说明为什么你想要这个或你会用结果做什么。您可以在代码中的任何位置执行此操作,但您可能会问,因为如果 UI 线程在那里运行,它会阻塞 UI 线程,而您可能不希望这样做。

      您需要在后台在不同的线程或服务上运行它,以便用户可以在循环运行时进行交互。这是基本答案 - 在除 MAIN 或 UI 线程之外的另一个线程上运行此循环。 (这里有很多答案可以解决这个问题。)

      如果您希望每半秒在屏幕上显示一个随机数,那么很多这些选项都可以,只是它们没有说明如果您在不同的线程中运行它们,那么您需要在你的Activity 然后使用runOnUiThread 线程方法来更新你的视图类(否则你会得到错误)。

      如果您想使用它作为进一步后台处理的开始,您应该考虑使用Service,您可以在其中扩展循环的功能以及在 UI 线程运行时它可能需要执行的任何其他任务。例如,如果您需要随机数来选择屏幕上显示的图像,您可能希望在向Activity 提供图像的服务中运行它。

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多