本節の導入:

本節で紹介するのはVibrator(バイブレーター)です。スマホに内蔵されているバイブレーターです。検索エンジンの百度で直接バイブレーターを検索しないでください。検索結果に、図のような神秘的な道具や、他の神秘的な道具が表示される可能性があるからです:

さて、本節で紹介するVibratorとは、Androidが提供する端末本体を振動させるためのサービスです!例えば、前述のNotificationでも振動を設定でき、プッシュ通知を受け取ったときに振動アラートを設定できます。ゲームには必須で、例えば「飛行機を撃つ」ゲームで、自分の飛行機が撃ち落とされたときに長く振動します!

それでは、簡単な例を作成して、このVibratorの使い方を理解しましょう!

公式APIドキュメント:Vibrator


1. Vibratorインスタンスを取得:


Vibrator vb = (Vibrator)getSystemService(Service.VIBRATOR_SERVICE);


2. 使用できる関連メソッド:

  • abstract void cancel():バイブレーターをオフにする、または停止する
  • abstract boolean hasVibrator():ハードウェアにバイブレーターが搭載されているかを判定する
  • void vibrate(long milliseconds):スマートフォンをmillisecondsミリ秒間振動させる
  • void vibrate(long[] pattern, int repeat):スマートフォンをpatternで指定したパターンで振動させます!例えば、patternがnew int[200,400,600,800]の場合、200、400、600、800の時間でバイブレーターを交互に起動・停止させます!2番目の引数は繰り返し回数で、-1の場合は1回だけ振動し、0の場合はずっと振動します。他にも2つのメソッドがありますがあまり使われません〜。そうそう、バイブレーターを使用するには、AndroidManifest.xmlに以下の権限を追加する必要があります:<uses-permission android:name="android.permission.VIBRATE"/>

3. 使用例:周波数の異なるバイブレーターの設定:

Vibratorが最も広く使われているのは、いそゆるスマホマッサージ器系のアプリでしょう。アプリ市場で検索すると、たくさん出てきます。筆者は適当にいくつかダウンロードして見てみましたが、どれも大同小異です。こんな小さなものが8万以上のダウンロード数あるんですね...まあ、多くはないようですが、一般的な機能は振動周波数を切り替えて実現しています。そして、いわゆるマッサージ効果が本当に有効かどうかは分かりません。それでは、次に簡単なマッサージ器を実装してみましょう!核心は、vibrate()の配列のパラメータで、自分のニーズに合わせて配列を書くだけです!下記のコードは実機でのテストが必要です!

実行効果図:

実装コード:

簡単なレイアウトファイル、5つのボタン:activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <Button
        android:id="@+id/btn_hasVibrator"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="判断是否有振动器" />


    <Button
        android:id="@+id/btn_short"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="短振动" />

    <Button
        android:id="@+id/btn_long"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="长振动" />

    <Button
        android:id="@+id/btn_rhythm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="节奏振动" />

    <Button
        android:id="@+id/btn_cancle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="取消振动" />
</LinearLayout>

続いてはMainActivity.java部分:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_hasVibrator;
    private Button btn_short;
    private Button btn_long;
    private Button btn_rhythm;
    private Button btn_cancle;
    private Vibrator myVibrator;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获得系统的Vibrator实例:
        myVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
        mContext = MainActivity.this;
        bindViews();
    }

    private void bindViews() {
        btn_hasVibrator = (Button) findViewById(R.id.btn_hasVibrator);
        btn_short = (Button) findViewById(R.id.btn_short);
        btn_long = (Button) findViewById(R.id.btn_long);
        btn_rhythm = (Button) findViewById(R.id.btn_rhythm);
        btn_cancle = (Button) findViewById(R.id.btn_cancle);

        btn_hasVibrator.setOnClickListener(this);
        btn_short.setOnClickListener(this);
        btn_long.setOnClickListener(this);
        btn_rhythm.setOnClickListener(this);
        btn_cancle.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_hasVibrator:
                Toast.makeText(mContext, myVibrator.hasVibrator() ? "当前设备有振动器" : "当前设备无振动器",
                        Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_short:
                myVibrator.cancel();
                myVibrator.vibrate(new long[]{100, 200, 100, 200}, 0);
                Toast.makeText(mContext, "短振动", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_long:
                myVibrator.cancel();
                myVibrator.vibrate(new long[]{100, 100, 100, 1000}, 0);
                Toast.makeText(mContext, "长振动", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_rhythm:
                myVibrator.cancel();
                myVibrator.vibrate(new long[]{500, 100, 500, 100, 500, 100}, 0);
                Toast.makeText(mContext, "节奏振动", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_cancle:
                myVibrator.cancel();
                Toast.makeText(mContext, "取消振动", Toast.LENGTH_SHORT).show();
        }
    }
}

そうそう、バイブレーターの権限を忘れないでくださいね!

<uses-permission android:name="android.permission.VIBRATE"/>

4. サンプルコードのダウンロード:

VibratorDemo.zip


本節のまとめ:

はい、本節ではVibrator(バイブレーター)の基本的な使い方を学びました。コードはとても簡単です。ぜひあなたのアプリに追加して、アプリを盛り上げてください〜。では、これくらいにしておきます。ありがとうございました。日も暮れてきたので、子豚はそろそろ帰宅します!何せ私はまだ純真な乙男ですから!万が一濡れてしまったら大変ですからね〜