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

Androidで通知を受信したときにカスタムサウンドを再生する方法【実装手順を解説】

この記事では、Androidアプリで通知を受信した際にカスタムサウンド(独自の通知音)を再生する方法を解説します。RingtoneManagerを使ってユーザーが端末に登録されている着信音の中から好きな通知音を選択できるようにし、そのサウンドで通知を表示するまでの一連の手順を、コード例とともに紹介します。

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

Android Studioを起動し、メニューから「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目を入力してプロジェクトの作成を完了させてください。

ステップ2:レイアウトファイル(res/layout/activity_main.xml)

res/layout/activity_main.xmlに以下のコードを追加します。このレイアウトには、「着信音を設定」ボタンと「通知を作成」ボタンの2つを配置しています。

<?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"
    tools:context=".MainActivity">

    <Button
        android:onClick="setRingtone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp"
        android:text="着信音を設定" />

    <Button
        android:onClick="createNotification"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:text="通知を作成" />

</RelativeLayout>

ステップ3:MainActivity.java

src/MainActivity.javaに以下のコードを追加します。処理のポイントは次の3点です。

  • setRingtone():RingtoneManagerのACTION_RINGTONE_PICKERを使い、端末に登録された通知音を選択するピッカー画面を起動します。
  • onActivityResult():ピッカーで選択された着信音のURIを受け取り、変数chosenRingtoneに保存します。
  • createNotification():NotificationCompat.Builderで通知を生成し、Android 8.0(Oreo)以降ではNotificationChannelを作成してから通知を表示します。
package app.tutorialspoint.com.notifyme;

import android.app.Activity;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";
    String chosenRingtone;

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

    // 着信音選択ピッカーを起動
    public void setRingtone(View view) {
        Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null);
        this.startActivityForResult(intent, 5);
    }

    // 通知を作成して表示
    public void createNotification(View view) {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
        mBuilder.setContentTitle("Notify Me");
        mBuilder.setContentText("Something important!");
        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        mBuilder.setAutoCancel(true);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel);
        }
        assert mNotificationManager != null;
        mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
    }

    // 選択された着信音のURIを受け取る
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 5) {
            Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
            if (uri != null) {
                this.chosenRingtone = uri.toString();
            } else {
                this.chosenRingtone = null;
            }
        }
    }
}

ステップ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>
    </application>

</manifest>

アプリを実行して動作を確認する

それではアプリを実行してみましょう。実機のAndroidスマートフォンをPCに接続していることを前提に説明します。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーのRunアイコンをクリックしてください。デバイス選択ダイアログで接続したスマートフォンを指定すると、端末上にアプリの初期画面が表示されます。

まず「着信音を設定」ボタンをタップして好みの通知音を選択し、次に「通知を作成」ボタンをタップします。選択したカスタムサウンドで通知が端末に表示されれば成功です。

補足:選択したサウンドを通知チャンネルに適用する

Android 8.0(APIレベル26)以降では、通知音はNotificationChannelごとに管理されます。ピッカーで選択した着信音を実際に通知音として鳴らしたい場合は、チャンネル作成時にsetSound()でURIを渡します。

NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
channel.setSound(Uri.parse(chosenRingtone), null);

なお、本記事のコードで使用しているサポートライブラリ(support-v4)は現在非推奨です。新規開発ではAndroidX(NotificationCompatなど)への移行を推奨します。

  1. Windows 10でカスタム通知音を設定する方法【初心者向け解説】

    Windows 10では、Microsoftが通知サウンドを一新しました。PCにトースト通知が届くと、デフォルトの通知音が鳴り、アラートの存在を知らせてくれます。しかし、初期設定のチャイム音に馴染めず、自分好みの音に変更したいと感じるユーザーも少なくありません。そこで本記事では、Windows 10のPCでカスタム通知音を設定する手順を詳しく解説します。 方法はシンプルです。.wav形式(Waveform Audio File Format)のサウンドファイルを、Windowsがデフォルトのサウンドを読み込むフォルダに配置し、システムのサウンド設定から既定の通知音を選択した音に変更するだけです

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

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