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

Cách phát hiện chế độ âm thanh (Ringer Mode) trong Android

Giới thiệu

Bài viết này hướng dẫn cách kiểm tra trạng thái âm thanh của thiết bị Android: Bình thường (Normal), Rung (Vibrate), hoặc Im lặng (Silent) sử dụng AudioManager.

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

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

Khởi tạo project Android Studio mới.

Bước 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:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Phát hiện chế độ âm thanh thiết bị"
        android:textSize="24sp"
        android:textStyle="bold" />

</RelativeLayout>

Bước 3: Code Java (src/MainActivity.java)

package app.com.sample;

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkRingerMode();
    }

    private void checkRingerMode() {
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        if (audioManager != null) {
            int ringerMode = audioManager.getRingerMode();

            switch (ringerMode) {
                case AudioManager.RINGER_MODE_SILENT:
                    showToast("Chế độ: Im lặng (Silent)");
                    break;
                case AudioManager.RINGER_MODE_VIBRATE:
                    showToast("Chế độ: Rung (Vibrate)");
                    break;
                case AudioManager.RINGER_MODE_NORMAL:
                    showToast("Chế độ: Bình thường (Normal) - Có âm thanh");
                    break;
                default:
                    showToast("Chế độ không xác định: " + ringerMode);
            }
        }
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
}

Giải thích:

  • AudioManager.getRingerMode(): Trả về int constant biểu thị chế độ hiện tại
  • 3 giá trị chính: RINGER_MODE_NORMAL (2), RINGER_MODE_VIBRATE (1), RINGER_MODE_SILENT (0)
  • Cần import java.util.Objects cho requireNonNull (hoặc check null thủ công)

Bước 4: Manifest (Không cần permission đặc biệt)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <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

Chạy app, Toast sẽ hiển thị chế độ âm thanh hiện tại của thiết bị. Thử chuyển đổi chế độ bằng phím vật lý hoặc quick settings để test.

Cách phát hiện chế độ âm thanh (Ringer Mode) trong Android

Mở rộng: Lắng nghe thay đổi chế độ (BroadcastReceiver)

// Register trong onStart()
IntentFilter filter = new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(ringerModeReceiver, filter);

// Unregister trong onStop()
unregisterReceiver(ringerModeReceiver);

// Receiver
BroadcastReceiver ringerModeReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int mode = am.getRingerMode();
        // Cập nhật UI...
    }
};

Lấy âm lượng chi tiết (Volume per stream)

AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
// Stream types: STREAM_MUSIC, STREAM_RING, STREAM_ALARM, STREAM_NOTIFICATION, STREAM_SYSTEM, STREAM_VOICE_CALL

Kotlin Version

val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
when (audioManager.ringerMode) {
    AudioManager.RINGER_MODE_SILENT -> toast("Silent")
    AudioManager.RINGER_MODE_VIBRATE -> toast("Vibrate")
    AudioManager.RINGER_MODE_NORMAL -> toast("Normal")
}