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

Androidで通知音・アラーム音・着信音を再生する方法【サンプルコード付き】

はじめに

この記事では、Androidアプリで着信音(リングトーン)・アラーム音・通知音を再生する方法を解説します。RingtoneManagerで端末のデフォルトの通知音URIを取得し、MediaPlayerで再生するシンプルな実装例を、ステップごとにわかりやすく紹介します。あわせて、通知チャンネルを作成してプッシュ通知を表示する方法も確認できます。

ステップ1:Android Studioで新規プロジェクトを作成する

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

ステップ2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xml に以下のコードを追加します。ここでは、画面中央に「Create notification(通知を作成)」というボタンを1つ配置しています。

<?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 alarmSound =
                    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                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());
            }
        });
    }
}

ステップ4:AndroidManifest.xmlを編集する

androidManifest.xml に以下のコードを追加します。通知時に振動を利用する場合は、VIBRATEパーミッションの宣言が必要です。

<?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で通知音・アラーム音・着信音を再生する方法【サンプルコード付き】

ボタンをタップすると、端末に設定されているデフォルトの通知音が鳴り、同時にテスト用のプッシュ通知が表示されます。これで、通知音の再生と通知の表示が正しく実装できていることを確認できます。

  1. Androidで線を引く方法とは?Canvasを使った描画手順をステップ解説

    この記事では、Androidアプリで線を描画する方法を、実際のサンプルコードとともにステップごとに解説します。BitmapとCanvasを組み合わせれば、ボタンをタップしたタイミングで画面上に線を簡単に描くことができます。 作成するアプリの概要 今回作成するのは、画面下部の「Draw Line」ボタンを押すと、中央のImageView上に赤い横線が表示されるシンプルなアプリです。レイアウトの定義、MainActivityへの処理の記述、マニフェストファイルの確認という流れで進めていきます。 ステップ1:新規プロジェクトを作成する Android Studioを起動し、「File」→「New P

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

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