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

【Android】通知を受信したときにカスタムアラートやビューを表示する方法

この記事では、Androidアプリで通知を受信した際にカスタムアラートやビューを表示する方法を、実際のコード例とともに解説します。通知チャンネルの作成からマニフェストの設定まで、ステップごとに丁寧に説明していきます。

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

まずはAndroid Studioを開き、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトのセットアップを完了させてください。

ステップ2:res/layout/activity_main.xml にコードを追加する

次に、メインレイアウトファイルに以下のコードを追加します。ここでは、画面中央に「Create notification(通知を作成)」ボタンを配置しています。

<?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="createNotification"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:text="Create notification" />

</RelativeLayout>

ステップ3:src/MainActivity にコードを追加する

続いて、MainActivityに通知を作成・表示するためのロジックを実装します。Android 8.0(APIレベル26)以降では通知チャンネルが必須となるため、OSバージョンを判定してチャンネルを作成している点に注目してください。

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

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);
        onNewIntent(getIntent());
    }

    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());

        Toast.makeText(MainActivity.this, "Custom Alert View",
                Toast.LENGTH_SHORT).show();
    }
}

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

</manifest>

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

それでは、アプリを実行してみましょう。ここでは、実際のAndroid端末をパソコンに接続していることを前提としています。Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。表示された選択肢から接続中のモバイルデバイスを選択すると、端末にアプリの初期画面が表示されます。

ボタンをタップすると通知が生成され、カスタムアラートとしてToastメッセージが画面に表示されます。これで、通知受信時にカスタムアラートやビューを表示する基本的な仕組みを実装できました。

  1. 【Android】カスタムAlertDialogビューを実装する完全ガイド

    この記事では、AndroidアプリでカスタムAlertDialog(ダイアログ)を実装する方法を、サンプルコード付きで段階的に解説します。標準的なダイアログではなく、独自のレイアウトを持つダイアログを表示したい場合に役立つ内容です。 ステップ1:新規プロジェクトの作成 まず、Android Studioを起動し、「File」⇒「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトの雛形を生成しましょう。 ステップ2:activity_main.xml にコードを追加 res/layout/activity_main.xml に以下のコードを記

  2. Androidで通知履歴を表示・復元する方法|うっかり消した通知を確認する2つのテクニック

    スマホには毎日、数え切れないほどの通知が届きます。しかし、うっかり素早くスワイプして消してしまい、後になって「重要な通知だったのに…」と後悔した経験はありませんか?実はAndroidでは、一度消した通知も必要に応じて後から確認できるのです。この記事では、Androidで通知履歴を表示する方法を詳しく解説します。 一度削除した通知も、完全に失われたわけではありません。見逃したメッセージやメール、ゲームやイベントの更新情報などは、すべてAndroid端末の中に残っています。あとは、その情報にアクセスする方法を知るだけです。 注意:後述する機能を有効にする前に受信した通知にはアクセスできません