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

バイブレーション・サウンド・アクション・ビッグビュースタイル対応のAndroid通知(Notification)実装例


本記事では、バイブレーションサウンドアクションボタン、そしてビッグビュースタイル(Big View Style)を組み合わせたAndroid通知の実装方法を、ステップごとに解説します。

通知はアプリとユーザーをつなぐ重要な接点です。テキスト表示だけでなく、振動や効果音で注意を引きつけ、タップできる操作を添え、長文を見やすく展開表示できれば、ユーザー体験(UX)は大きく向上します。

手順1:Android Studioで新規プロジェクトを作成

Android Studioを起動し、メニューから「File」⇒「New Project」を選択します。プロジェクト名やパッケージ名などの必要事項を入力して、新しいプロジェクトを作成してください。

手順2:レイアウトファイル(res/layout/activity_main.xml)

まずは、通知を作成するためのボタンを1つ配置したシンプルなレイアウトを用意します。以下のコードをactivity_main.xmlに記述してください。

<?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に記述します。NotificationCompat.Builderを使い、タイトル・本文・アクションボタン・BigTextStyleを設定しています。

package app.tutorialspoint.com.notifyme;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
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) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                final PendingIntent resultPendingIntent =
                    PendingIntent.getActivity(
                        MainActivity.this,
                        0,
                        intent,
                        PendingIntent.FLAG_CANCEL_CURRENT
                    );
                NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(MainActivity.this,
                    default_notification_channel_id)
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setContentTitle("Test")
                    .addAction(R.drawable.ic_launcher_foreground, "Add", resultPendingIntent)
                    .setContentIntent(resultPendingIntent)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText("Big View Styles"))
                    .setContentText("Hello! This is my first push notification");
                NotificationManager mNotificationManager = (NotificationManager)
                    getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
            }
        });
    }
}

実装のポイント:

  • PendingIntentを設定することで、通知をタップした際にアプリが起動します。
  • addAction()を使うと、通知上に直接操作できる「Add」ボタンが表示されます。
  • setStyle()BigTextStyleを指定すると、通知を展開したときに長文テキストを見やすく表示できます。
  • Android 8.0(API 26)以降では、すべての通知に通知チャンネルが必要です。実際の開発ではcreateNotificationChannel()でチャンネルを事前に登録しておきましょう。バイブレーションやサウンドもチャンネル設定から制御できます。

手順4:AndroidManifest.xmlへの権限追加

バイブレーション機能を使用するため、VIBRATE権限を宣言します。以下のコードを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>
        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
    </application>
</manifest>

アプリの実行と動作確認

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

画面中央の「Create notification」ボタンをタップすると、ステータスバーに通知が届きます。通知を展開すれば、BigTextStyleによる拡張表示や「Add」アクションボタンの動作を確認できます。

バイブレーション・サウンド・アクション・ビッグビュースタイル対応のAndroid通知(Notification)実装例

  1. もう見逃さない!Androidの通知をマスターする11のアプリとテクニック

    スマートフォンの登場以来、通知は私たちの生活に欠かせない存在になりました。友人からのメッセージ也好、上司からのメール也好、最新情報をキャッチする手段として活躍しています。しかし一方で、通知は企業が自社コンテンツを積極的に宣伝する媒体にもなっています。通知はあなたの時間を奪い合い、度を越えてしまうことも少なくありません。だからこそ、通知を適切に管理する方法を知ることが、今まで以上に重要になっています。ここでは、Androidの通知を最大限に活用する方法をご紹介します。1. 通知履歴Androidの通知システムは高く評価されていますが、消えてしまった通知を復元する標準機能はまだありません。うっかり

  2. Androidのストレスを一挙解決!快適さが劇的に向上するおすすめアプリ10選

    数ヶ月ごとに、最先端のプロセッサと大容量RAMを搭載した新しいフラッグシップスマートフォンが登場します。しかし残念ながら、時間が経てばどんなハイスペック機でも動作が重くなり始めるもの。実は、最高峰のAndroidスマートフォンにも、やはり不満点は存在するのです。 どのAndroidスマートフォンを使っていても、デバイスを快適に使い続けるための最良の方法は、スマートフォンの管理をシンプルにしてくれるユーザーフレンドリーなアプリを導入することです。 ここで紹介するAndroidアプリは、あなたの最大のストレスを解消し、毎日のスマートフォンライフをぐっと快適にしてくれます。 1. Nova Laun