Android
 Computer >> コンピューター >  >> プログラミング >> Android

Androidアプリで着信音・アラーム・通知音を再生する方法を徹底解説

はじめに

本記事では、Androidアプリ内で着信音・アラーム音・通知音を再生する実装方法を、サンプルコードとともに段階的に解説します。通知と連動させて効果音を鳴らしたい場合などに役立つテクニックです。

今回のサンプルでは、RingtoneManagerでシステム標準の通知音のURIを取得し、MediaPlayerを使って再生します。さらに通知チャンネルを作成してプッシュ通知も同時に表示させます。

手順1:プロジェクトの新規作成

まずはAndroid Studioで新しいプロジェクトを作成しましょう。メニューから「File」⇒「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。

手順2:レイアウトファイル(activity_main.xml)の編集

次に、res/layout/activity_main.xmlに以下のコードを追加します。画面中央に「Create notification(通知を作成)」ボタンを配置するシンプルな構成です。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="Create notification"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

手順3:MainActivity.javaの実装

続いて、src/MainActivity.javaに以下のコードを記述します。

ボタンがタップされると、RingtoneManager.getDefaultUri()でデフォルトの通知音のURIを取得し、MediaPlayer.create()で音声を生成・再生します。その後、NotificationCompat.Builderを使って通知を作成し、NotificationManager経由で表示しています。

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.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private final static String default_notification_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(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // デフォルトの通知音URIを取得
                Uri alarmSound =
                    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                // MediaPlayerで通知音を再生
                MediaPlayer mp = MediaPlayer.create(getApplicationContext(), alarmSound);
                mp.start();

                // 通知の作成
                NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(MainActivity.this,
                        default_notification_channel_id)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentTitle("Test")
                        .setContentText("Hello! This is my first push notification");

                NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify((int) System.currentTimeMillis(),
                    mBuilder.build());
            }
        });
    }
}

ポイント解説

  • TYPE_NOTIFICATION:通知音を取得する定数です。TYPE_RINGTONE(着信音)やTYPE_ALARM(アラーム音)に変更することで、目的に応じたサウンドを再生できます。
  • MediaPlayer:短い効果音の再生に適しています。再生が終わったリソースは適宜release()で解放するとよいでしょう。
  • 通知ID:System.currentTimeMillis()を使うことで、毎回異なるIDが発行され、通知が上書きされずに表示されます。

手順4:AndroidManifest.xmlの編集

最後に、androidManifest.xmlに以下のコードを追加します。バイブレーション用のパーミッションや、Firebase Messagingサービスの宣言を含んでいます。

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

        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

    </application>
</manifest>

アプリの実行と動作確認

それでは実際にアプリを起動してみましょう。実機のAndroidスマートフォンをパソコンに接続していることを前提としています。Android Studioからプロジェクトのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。

表示される選択肢の中から自分のモバイル端末を選択すると、実機にアプリがインストールされます。アプリを起動してボタンをタップすると、以下のようにデフォルト画面に通知が表示され、同時に通知音が再生されます。

Androidアプリで着信音・アラーム・通知音を再生する方法を徹底解説

まとめ

このように、RingtoneManagerMediaPlayerを組み合わせることで、Androidアプリに簡単に着信音・アラーム音・通知音の再生機能を実装できます。通知機能と組み合わせれば、ユーザーに確実に気づいてもらえるUXを提供できるでしょう。ぜひ自分のプロジェクトにも取り入れてみてください。

  1. Androidでカスタム通知レイアウトとテキストの色を作成する方法を徹底解説

    このチュートリアルでは、Androidアプリにおいて標準的な通知と、RemoteViewsを使ったカスタム通知レイアウトの両方を作成する方法を、サンプルコード付きでわかりやすく解説します。カスタムレイアウトを活用すれば、通知のデザインやテキストの色などを自由にコントロールできるようになります。 全体の流れ 本記事の手順は以下の通りです。 Android Studioで新規プロジェクトを作成する メイン画面のレイアウト(activity_main.xml)を用意する MainActivity.javaに通知の生成処理を実装する 通知・カスタム通知・通知内容表示用のレイアウトXMLを作成する A

  2. 【Android】Snapchatの通知音を変更する4つの方法を徹底解説

    Snapchatは、Z世代を中心に絶大な人気を誇るSNSアプリです。カメラ撮影や写真フィルター、音声通話、ビデオ通話、チャットといった多彩な機能をひとつのアプリで完結できることから、「オールインワン」と呼ばれるほど多くのユーザーに愛用されています。さらに「スナップストリーク(Streak)」機能を利用すれば、毎日写真や動画を送り合うことで友だちとのつながりを楽しく維持できます。ただし、スナップが届くたびに通知バーから音が鳴るため、ストリークを続けている方の中には「通知音が何度も鳴って気になる」「デフォルトの音に飽きた」と感じている方も多いのではないでしょうか。そこで本記事では、Androidス