【问题标题】:android vibrator turn on and turn offandroid振动器打开和关闭
【发布时间】:2012-04-01 14:58:07
【问题描述】:

我在我的应用程序中做了一个部分,如果你按下按钮,手机就会振动,如果你再次按下按钮,手机就会停止振动。我正在为我的按钮使用单选按钮。我的代码现在用于振动部分:

                while(hard.isChecked()==true){
                    vt.vibrate(1000);
                }

手机会振动,但不喜欢满电振动,并且单选按钮不会改变。我也无法关闭它,因为手机基本上冻结了。有人有解决这个问题的想法吗?

【问题讨论】:

    标签: android radio-button vibration ischecked


    【解决方案1】:

    您编写了一个无限循环。您的设备无法更改单选按钮的状态,因为它仍处于 while 循环中。

    一种可能性是在单独的线程中启动振动代码。

    另一种可能性是在你的 while 循环中添加一个 Thread.Sleep(100) 左右。

    【讨论】:

    • 我希望它能够持续振动,这样可以让 thread.sleep 让它继续振动。振动。
    • 我没有测试过,但只要睡眠值低于振动值,它就应该这样工作。
    • 我试过了,但还是不行,我想我现在可以只做两个按钮,一个取消,一个启动。如果您有其他想法,请分享。
    【解决方案2】:

    您正在使用 while 循环 hard.isChecked() 这将永远为真,现在它循环进入无限循环。所以在while循环中使用break语句

    while(hard.isChecked()==true){
        vt.vibrate(1000);
    break;
     }
    

    或者你可以使用下面的代码:

    if(hard.isChecked()){
       vt.vibrate(1000);
    }
    

    【讨论】:

    • 好吧,我希望它持续振动,所以如果我输入 break 或 if 语句,手机只会振动一次,持续 1000 毫秒。
    【解决方案3】:

    我自己试过了。我认为下面的代码是您正在寻找的:

    private Vibrator vibrator;
    private CheckBox checkbox;
    private Thread vibrateThread;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        vibrator = ((Vibrator)getSystemService(VIBRATOR_SERVICE));
        checkbox = (CheckBox)findViewById(R.id.checkBox1);
        vibrateThread = new VibrateThread();
    }
    
    public void onCheckBox1Click(View view) throws InterruptedException{
        if(checkbox.isChecked()){
            if (vibrateThread.isAlive()) {
                vibrateThread.interrupt();
                vibrateThread = new VibrateThread();
            } else {
                vibrateThread.start();
            }
        } else{
            vibrateThread.interrupt();
            vibrateThread = new VibrateThread();
        }
    }
    
    class VibrateThread extends Thread {
        public VibrateThread() {
            super();
        }
        public void run() {
            while(checkbox.isChecked()){                
                try {
                    vibrator.vibrate(1000);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    这里是布局:

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CheckBox"
        android:onClick="onCheckBox1Click"/>
    

    【讨论】:

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