Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách làm rung thiết bị Android bằng lập trình?

Giới thiệu

Bài viết minh họa cách kích hoạt rung (vibration) trên thiết bị Android qua Vibrator system service, hỗ trợ cả API cũ và mới (API 26+).

Các bước thực hiện

Bước 1: Tạo dự án mới

Khởi tạo project Android Studio.

Bước 2: Giao diện đơn giản (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="Ví dụ Rung"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</RelativeLayout>

Bước 3: Logic rung (src/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 android.support.v7.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) return;

        // Rung 500 milliseconds
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // API 26+ (Android 8.0 Oreo)
            vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            // Deprecated trong API 26 nhưng vẫn hoạt động
            vibrator.vibrate(500);
        }
    }
}

Bước 4: AndroidManifest.xml (cần quyền VIBRATE)

<?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>

Chạy ứng dụng

Kết nối thiết bị thật (emulator thường không rung), nhấn Run. Thiết bị sẽ rung 0.5 giây ngay khi app khởi động.

Cách làm rung thiết bị Android bằng lập trình?

Mở rộng: Các mẫu rung nâng cao (API 26+)

1. Rung theo mẫu (Pattern)

// {delay, rung, delay, rung, ...} đơn vị milliseconds
long[] pattern = {0, 100, 200, 100, 300, 200, 100};
vibrator.vibrate(VibrationEffect.createWaveform(pattern, -1)); // -1 = không lặp

2. Rung lặp lại

// Lặp từ index 0
vibrator.vibrate(VibrationEffect.createWaveform(pattern, 0));

3. Hủy rung

vibrator.cancel();

4. Kiểm tra hỗ trợ rung

boolean hasVibrator = vibrator.hasVibrator(); // API 11+
// API 29+
boolean hasAmplitudeControl = vibrator.hasAmplitudeControl();

5. Predefined Effects (API 29+)

// Hiệu ứng định sẵn: click, tick, heavy click, double click
vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK));
vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_HEAVY_CLICK));

Lưu ý

  • Quyền VIBRATE là normal permission → tự động cấp
  • Emulator thường không có motor rung → test trên thiết bị thật
  • API 26+ khuyến khích dùng VibrationEffect thay vì vibrate(long[]) cũ
  • Tránh lạm dụng rung - ảnh hưởng pin và trải nghiệm người dùng