在Android上使用“异步任务”生成随机数和输出

时间:2011-09-02 07:45:27

标签: android asynchronous random

我正在编写一个随机数生成器程序,每秒显示一次输出。

概述是每当随机数改变时我想要随机数输出到'EditText'框。有可能吗?

我对它进行了研究,但结果不成功(主要是因为异步的工作方式)。

这是我写的代码:

package com.example;

import java.util.Random;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AsyncTasksActivity extends Activity {

EditText txtMessage;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);         

    String ranString = "";

    try{
        ranString = "";
        for(int a = 0; a < 33; a++)
        {
        Random rn = new Random();
        int i = rn.nextInt(256);

        ranString = ranString + i + " ";

        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
    txtMessage = (EditText) findViewById(R.id.txtMessage);
    txtMessage.setText(ranString);
}

public class runRandomly extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }

    @Override
    protected void onProgressUpdate(String... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }

    }


}

如果您需要运行代码以确保其正常工作,我将xml代码放在此处:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">

<TextView  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="Null"
/>
<EditText 
android:id="@+id/Null"  
android:layout_width="fill_parent" 
android:layout_height="wrap_content"
android:singleLine="true"
android:inputType="numberDecimal"/>

<TextView  
android:layout_width="fill_parent" 
android:layout_height="wrap_content"         
android:text="Random Key"/>
<EditText 
android:id="@+id/txtMessage"  
android:layout_width="fill_parent" 
android:gravity="center"
android:editable="false" android:layout_height="61dp" android:layout_weight="0.14"/>

<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</LinearLayout>

<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>   

</LinearLayout>

非常感谢!

2 个答案:

答案 0 :(得分:0)

将此行放在for循环之外,它将重新生成新对象,因此不需要循环

Random rn = new Random();

for(int a = 0; a < 33; a++)
{
    int i = rn.nextInt(256);

    ranString = ranString + i + " ";
}

你需要Handler和Runnable对象,它使用runRandomly对象调用AsynTask执行方法

喜欢创建这个对象

Handler handler = new Handler();
runRandomly randomly = new runRandomly();


Runnable callRandom = new Runnable(){
   public void run(){
        //// call the execute method 
        randomly.execute();
        ///// here handler call this runnable every 1 sec i.e 1000 delay time
        handler.postDelay(callRandom,1000);
   }
}
onBackground中的

生成数字     @覆盖     protected String doInBackground(String ... params){         String ranString =“”;

    Random rn = new Random();

    for(int a = 0; a < 33; a++)
    {
        int i = rn.nextInt(256);

        ranString = ranString + i + " ";
    }
    return ranString;
}

以上方法将生成随机数字符串,完成后将该字符串返回给postExecute();

@Override
protected void onProgressUpdate(String values) {
    super.onProgressUpdate(values);
    if(values!=null & !values.equals(""))
       txtMessage.setText(ranString);

}

答案 1 :(得分:0)

从我的角度来看,

  1. 使AsyncTask类的构造函数传递活动签名, 喜欢,

    public runRandomly(Activity activity) {
    this.activity = activity;
    context = activity;
    }
    
  2. 也会覆盖此方法

    @Override
    protected void onProgressUpdate(Integer... values)
    {
    
    super.onProgressUpdate(values);
    if (values[0] == 0) {
    mDialog.setTitle("Processing...");
    }
    
    mDialog.setProgress(values[0]);
    
    } 
    
  3. 从doInBackground(String ... params)方法更新onProgressUpdate(调用它)

  4. 编辑:您还可以在AsyncTask构造函数中提供EditText视图的引用,并在onProgressUpdate方法中进行更新。

    编辑:使用此代码..

    public class NewClass extends Activity {
    /** Called when the activity is first created. */
    EditText edt;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.newclass);
        edt=(EditText)findViewById(R.id.ed);
    
        new runRandomly(this,edt).execute();
    }
    
    
    public class runRandomly extends AsyncTask<String, String, String> {
    
    String ranString="";
    Activity activity;
    EditText edtt;
    
    public runRandomly(Activity activity,EditText edit) {
        this.activity = activity;
        edtt=edit;
        }
    
    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
    
        try{
    
            for(int a = 0; a < 33; a++)
            {
            Random rn = new Random();
            int i = rn.nextInt(256);
    
            ranString = ranString + i + " ";
    
            }
            onProgressUpdate();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    
        return null;
    }
    
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }
    
    @Override
    protected void onProgressUpdate(String... values) {
        // TODO Auto-generated method stub
    
        edtt.setText(""+ranString);
        super.onProgressUpdate(values);
    }
    
    }
    
    
    }
    

    简单,Thanx。