Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีทำให้อุปกรณ์ Android กระทบ (Vibrate) ด้วยโค้ด

การควบคุม Vibrator ทำให้โทรศัพท์กระทบโดยโปรแกรม

ตัวอย่างนี้แสดงวิธีใช้ Vibrator และ VibrationEffect (API 26+) เพื่อทำให้อุปกรณ์กระทบ รองรับทั้ง API เก่าและใหม่

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → File → New Project → กรอกรายละเอียด → Finish

ขั้นตอนที่ 2: Layout - res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:padding="16dp"
        android:text="ตัวอย่าง Vibration"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</RelativeLayout>

ขั้นตอนที่ 3: MainActivity.java

package app.tutorialspoint.com.sample;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        
        if (vibrator != null && vibrator.hasVibrator()) {
            // กระทบ 500 มิลลิวินาที
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // API 26+ ใช้ VibrationEffect
                vibrator.vibrate(VibrationEffect.createOneShot(
                    500, 
                    VibrationEffect.DEFAULT_AMPLITUDE
                ));
            } else {
                // API 25 ลงมา (Deprecated)
                vibrator.vibrate(500);
            }
        }
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.sample">
    <uses-permission android:name="android.permission.VIBRATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

VibrationEffect Patterns (API 26+)

1. Single Shot (กระทบครั้งเดียว)

// createOneShot(durationMs, amplitude)
vibrator.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE));

2. Pattern (รูปแบบซ้ำ)

// pattern: {delay, vibrate, delay, vibrate, ...}
// repeat: index ใน pattern ที่จะวนซ้ำ (-1 = ไม่วน)
long[] pattern = {0, 500, 200, 500, 200, 500}; // กระทบ 500ms, หยุด 200ms, กระทบ 500ms...
vibrator.vibrate(VibrationEffect.createWaveform(pattern, -1));

3. Predefined Effects

// ต้องใช้ VibrationEffect.EFFECT_*
vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK));
vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK));
vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK));

4. ยกเลิกการกระทบ

vibrator.cancel();

การตรวจสอบอุปกรณ์รองรับ

Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null) {
    boolean hasVibrator = vibrator.hasVibrator(); // API 11+
    boolean hasAmplitudeControl = vibrator.hasAmplitudeControl(); // API 26+
}

⚠️ ข้อควรระวัง

  • ต้องเพิ่ม <uses-permission android:name="android.permission.VIBRATE"/>
  • บางอุปกรณ์ไม่มี Motor กระทบ (hasVibrator() = false)
  • Amplitude (ความเข้ม) รองรับได้เฉพาะ API 26+ และอุปกรณ์ที่รองรับ
  • ใช้ VibrationEffect แทน vibrate(long[]) เดิมที่ Deprecated
  • Android 12+ อาจจำกัดการกระทบใน Background

การทดสอบ

รันบนอุปกรณ์จริง (Emulator ไม่มี Vibrator) → โทรศัพท์จะกระทบ 500ms ทันทีเปิดแอป