2012-04-01 211 views
0

我正在制作应用程序中的一部分,如果按下按钮,则手机会振动,如果再次按下按钮,手机将停止振动。我正在为我的按钮使用单选按钮。我的代码是正确的,现在的振动部分:android vibrator打开和关闭

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

手机振动,但它并不像充满电振动,单选按钮不会改变。我也无法关闭它,因为手机基本冻结。任何人有任何想法来解决这个问题?

回答

0

我已经尝试过自己。我认为下面的代码是你在找什么:

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"/> 
1

您编程了一个无限循环。您的设备没有机会改变您的单选按钮的状态,因为它仍处于while循环中。

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

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

+0

我希望它不断地振动寿所以会把谓的Thread.Sleep使得它,所以它续。振动。 – 2012-04-03 04:25:08

+0

我还没有测试过,但只要睡眠值低于振动值,它应该以这种方式工作。 – 2012-04-03 08:14:52

+0

我尝试过,但它仍然无法工作,我想我现在可能只是做两个按钮,并有一个取消它,一个启动它。如果你想别的,请分享。 – 2012-04-05 13:21:34

1

你正在使用while循环hard.isChecked()这将永远是真的,现在它循环到无限循环。所以使用break语句在while循环

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

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

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

好吧,我希望它不断振动,所以如果我把它放在休息或if语句会使它如此,电话只振动一次1000米。 – 2012-04-03 04:24:21