Androidでローカル通知を作成する方法をサンプルコード付きで解説
このチュートリアルでは、Androidアプリでローカル通知(Local Notification)を作成する方法を、サンプルコードとともにステップごとに解説します。ボタンをタップすると通知が表示される、シンプルなデモアプリを一緒に作ってみましょう。
手順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"?>
<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"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/btnCreateNotification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:text="Create Notification" />
</RelativeLayout>
手順3:MainActivity.java に通知のロジックを実装する
src/MainActivity.java に以下のコードを追加します。Android 8.0(APIレベル26)以降では、通知を表示するために必ず通知チャンネル(NotificationChannel)を作成する必要があるため、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;
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);
}
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("My Notification");
mBuilder.setContentText("Notification Listener Service Example");
mBuilder.setTicker("Notification Listener Service Example");
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());
}
}
コードのポイント
- setContentTitle / setContentText:通知のタイトルと本文を設定します。
- setSmallIcon:ステータスバーに表示される小さなアイコンを指定します。未設定の場合、通知が正しく表示されないことがあります。
- setAutoCancel(true):通知をタップすると自動的に削除されます。
- createNotificationChannel():Android 8.0以降で必須となる通知チャンネルを作成します。重要度をIMPORTANCE_HIGHに設定すると、ヘッドアップ通知として画面上部に表示されます。
手順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 13以降で通知を表示するには
Android 13(APIレベル33)以降では、通知の表示に加えて POST_NOTIFICATIONS パーミッションの宣言と、実行時のユーザー許可が必要になります。また、本記事のコードは旧サポートライブラリ(android.support)を使用していますが、新規開発ではAndroidX(androidx.core.app.NotificationCompat など)の利用を推奨します。
アプリを実行して動作を確認しよう
それでは、作成したアプリを実際に動かしてみましょう。Android端末をPCに接続し、Android Studioでプロジェクト内のアクティビティファイルを開いた状態で、ツールバーの「Run」アイコンをクリックします。実行デバイスとして自分のスマートフォンを選択すると、端末に以下のような画面が表示されます。


-
FacebookでAndroidアプリを作成する方法|開発者サイトでの設定手順を徹底解説
この記事では、FacebookでAndroidアプリを作成する方法について詳しく解説します。AndroidアプリとFacebookを連携させるには、Facebook開発者サイトでFacebookアプリを作成し、Facebook App IDを取得する必要があります。以下の手順に従って、順番に進めていきましょう。 準備:Facebook開発者サイトで新しいアプリを追加する まず、https://developers.facebook.com/ にアクセスし、「新しいアプリを追加」をクリックしてアプリの作成を開始します。 ステップ1:アプリ名とメールアドレスを入力する 指定されたフィールドに、作
-
Android 8で通知をスヌーズする方法
多くの人にとって、一日の最後のタスクは翌日のためにアラームをセットすることでしょう。しかし実際には、スヌーズボタンを何度も押した末に、ようやく温かい布団から這い出すというのが現実ではないでしょうか。意外にも、スヌーズとスヌーズの間のわずかな時間こそ、一番深い眠りが得られる瞬間だったりします。つまり、スヌーズ機能は私たちの生活に欠かせない大切な機能なのです。そこで本記事では、Android 8の新機能「通知のスヌーズ(Snooze Notifications)」について詳しく解説します。この機能を使えば、必要なときにスマートフォンの通知を一時的に非表示にできるようになります。通知をスヌーズするメ