Android:震动

时间:2012-02-17 10:26:12

标签: android

我在应用程序中实现振动功能时遇到了一些问题。 我的代码是:

public class VibrationActivity extends Activity {

private Vibrator vib;

private long[] pattern = { 0, 500, 200, 500 };

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

vib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);

}

public void onClick(View v) {
int id = v.getId();

if (id == R.id.button1) {
vib.vibrate(pattern, -1);
}
}

}

我已经在清单中声明了使用声明,所以这不是问题。当我点击按钮时,实际上什么也没发生......任何人都有任何想法?

提前致谢!

3 个答案:

答案 0 :(得分:3)

使用此代码:

public class testVibrate extends Activity {
    /** Called when the activity is first created. */
    private Vibrator vib;
    private long[] pattern = { 0, 500, 200, 500 };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        vib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                vib.vibrate(pattern, -1);
            }
        });
    }

答案 1 :(得分:0)

在你的onCreate()中使用:

setContentView(R.layout.main);
vib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);

Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
    public void onClick(View view) {
        vib.vibrate(pattern, -1);
    }

});

答案 2 :(得分:0)

您必须对布局进行充气才能按ID找到按钮。 然后将一个监听器附加到按钮上。

 public class VibrationActivity extends Activity {  
    private Vibrator vib;

    private Button button;

    private long[] pattern = { 0, 500, 200, 500 };

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.your_layout);

        vib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);

        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(mOnClickListener);
    }

    private OnClickListener mOnClickListener = new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            int id = v.getId();

            if (id == R.id.button1)
            {
                vib.vibrate(pattern, -1);
            }
        }
    };

}