Bài viết này trình bày cùng chủ đề với bài trước: sử dụng RingtoneManager để lấy URI âm thanh hệ thống (ringtone, alarm, notification) và phát qua MediaPlayer hoặc gán vào Notification.
Code hoàn chỉnh (src/MainActivity.java)
package app.tutorialspoint.com.notifyme;
import android.app.NotificationManager;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import androidx.core.app.NotificationCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static final String DEFAULT_CHANNEL_ID = "default";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
btnCreateNotification.setOnClickListener(v -> {
// Lấy URI âm thanh notification mặc định
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Phát qua MediaPlayer
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), alarmSound);
mp.start();
mp.setOnCompletionListener(MediaPlayer::release);
// Tạo notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Test")
.setContentText("Hello! This is my first push notification")
.setAutoCancel(true);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.notify((int) System.currentTimeMillis(), builder.build());
}
});
}
}
Giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/btnCreateNotification"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Tạo thông báo + phát âm thanh"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.notifyme">
<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>
Mở rộng: Chọn âm thanh tùy chỉnh từ thiết bị
Nếu muốn cho user tự chọn âm thanh, dùng RingtoneManager mở picker:
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Chọn âm thanh thông báo"); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentUri); startActivityForResult(intent, REQUEST_CODE_RINGTONE);
Nhận kết quả trong onActivityResult (hoặc ActivityResultLauncher):
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RINGTONE && resultCode == RESULT_OK) {
Uri selectedUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
// Lưu selectedUri vào SharedPreferences để dùng cho NotificationChannel sau này
}
}
Tóm tắt
- Dùng
RingtoneManager.getDefaultUri(TYPE_NOTIFICATION)cho âm thanh thông báo chuẩn. - Dùng
MediaPlayer.create(context, uri).start()để phát ngay lập tức. - Trên Android 8+, âm thanh notification do NotificationChannel kiểm soát, không phải Builder.
- Cho user tùy chỉnh: dùng
RingtoneManager.ACTION_RINGTONE_PICKER.