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

Android Oreo以降でカスタム通知音を実装する方法【コード例で解説】

Android Oreo以降のカスタム通知音とは

この記事では、Android 8.0(Oreo)以降の端末で、独自のカスタム通知音を設定する方法を具体的なコード例とともに解説します。Android Oreoからは「通知チャンネル(Notification Channel)」の仕組みが導入され、通知音はチャンネルごとに設定する必要があります。従来のようにsetSound()だけではOreo以降で通知音が反映されないため、注意が必要です。

実装手順

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

Android Studioを開き、「File」→「New Project」を選択して、必要な情報を入力し、新しいプロジェクトを作成します。

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

以下のコードをres/layout/activity_main.xmlに追加します。ここでは、通知を作成するためのボタンを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:rawフォルダにサウンドファイルを追加する

プロジェクトのres/rawフォルダに、通知音として使用したい音声ファイル(例:quite_impressed.mp3)を配置します。rawフォルダが存在しない場合は、resディレクトリ上で右クリックして新規作成してください。

Android Oreo以降でカスタム通知音を実装する方法【コード例で解説】

ステップ4:MainActivity.javaにコードを追加する

次に、src/MainActivity.javaに以下のコードを記述します。ポイントは、Android Oreo(APIレベル26)以降の場合に分岐処理を入れ、NotificationChannelに対してsetSound()でカスタム音声とAudioAttributesを設定している点です。

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioAttributes;
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 {

    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    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 sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/quite_impressed.mp3");
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentTitle("Test")
                        .setSound(sound)
                        .setContentText("Hello! This is my first push notification");
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    AudioAttributes audioAttributes = new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setUsage(AudioAttributes.USAGE_ALARM)
                            .build();
                    int importance = NotificationManager.IMPORTANCE_HIGH;
                    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
                    notificationChannel.enableLights(true);
                    notificationChannel.setLightColor(Color.RED);
                    notificationChannel.enableVibration(true);
                    notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                    notificationChannel.setSound(sound, audioAttributes);
                    mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
                    assert mNotificationManager != null;
                    mNotificationManager.createNotificationChannel(notificationChannel);
                }
                assert mNotificationManager != null;
                mNotificationManager.notify((int) System.currentTimeMillis(),
                        mBuilder.build());
            }
        });
    }
}

ステップ5:AndroidManifest.xmlを確認する

最後に、androidManifest.xmlが以下のようになっていることを確認します。

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

    <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スマートフォンをパソコンに接続しているものとして説明します。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続したモバイルデバイスを選択して実行すると、端末にアプリの画面が表示されます。

Android Oreo以降でカスタム通知音を実装する方法【コード例で解説】

画面上の「Create notification」ボタンをタップすると、指定したrawフォルダ内の音声ファイルが通知音として再生されるカスタム通知が表示されます。Oreo以降の端末では、通知チャンネルに設定された音・ライト・バイブレーションの挙動を確認できます。

まとめ

Android Oreo以降でカスタム通知音を使うには、NotificationChannelを作成し、そのチャンネルに対してsetSound()で音声リソースのURIとAudioAttributesを渡すのが正しい実装方法です。OSバージョンによる分岐を忘れずに行うことで、旧バージョンから最新のAndroidまで一貫した通知体験を提供できます。

  1. Android Marshmallow・LollipopにおすすめのカスタムROM10選【2021年版】

    Androidスマートフォンの平均的な寿命は2年程度と言われています。残念ながら、多くの端末は使い込むうちに何らかの不具合を抱えるようになります。その原因の一つが、電子機器の中核となるROMの劣化です。システムをカスタムROMでアップグレードすれば、常に最新で安定したソフトウェア環境を保てるだけでなく、斬新なデザインや魅力的な機能を自由に楽しめるようになります。だからこそ、自分のスマートフォンには最も安全で信頼性の高いAndroid ROMを選ぶことが重要なのです。では、なぜ「ベスト」なROMを選ぶ必要があるのでしょうか。 優れたカスタムROMには、活発な開発者コミュニティによるサポートと、幅

  2. Windows 10・8・7対応!おすすめAndroidエミュレーター15選

    ソフトウェアの開発には、さまざまなテスト段階が存在します。アプリ開発者も同様に、コードや文字列を確定させるまでに幾夜も眠れない日々を過ごすことがあります。そんなときに欠かせないのがAndroidエミュレーターです。エミュレーターがあれば、アプリがAndroidスマートフォン上でどのように動作するかを事前に確認でき、不具合が見つかればすぐに修正できます。 Windowsに最適なAndroidエミュレーターを選ぶのは難しく感じるかもしれませんが、ご安心ください。この記事でしっかり解説します。現在、市場にはそれぞれ異なる独自機能を備えたエミュレーターが数多く登場しています。 Windows PC向け