如何使用Android进行随机函数调用?

时间:2011-05-31 09:12:59

标签: android function random

我正在开发Android LBS应用程序。我想通过我的应用程序随机调用函数。

我有以下代码。

public class DialANumber extends Activity {
  EditText mEditText_number = null;
  LinearLayout mLinearLayout_no_button = null;
  Button mButton_dial = null;

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

    mLinearLayout_no_button = new LinearLayout(this);

    mEditText_number = new EditText(this);
    mEditText_number.setText("5551222");
    mLinearLayout_no_button.addView(mEditText_number);

    mButton_dial = new Button(this);
    mButton_dial.setText("Dial!");
    mLinearLayout_no_button.addView(mButton_dial);
    mButton_dial.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        performDial();
      }
    });

    setContentView(mLinearLayout_no_button);
  }

  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_CALL) {
      performDial();
      return true;
    }
    return false;
  }

  public void performDial(){
    if(mEditText_number!=null){
      try {
        startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mEditText_number.getText())));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }//if
  }
}

我想随机调用performDial()方法。

1 个答案:

答案 0 :(得分:0)

虽然我仍然不确定我完全理解你的问题,但你可以这样做:

  double rand = Math.random();
  if( rand < 0.2 )
      firstFunction();
  else if( rand < 0.4 )
      secondFunction();
  else if( rand < 0.6 )
      thirdFunction();
  else if( rand < 0.8 )
      fourthFunction();
  else
      fifthFunction();

Math.random()生成大于或等于0.0且小于1.0的随机双精度数。