Androidでシングルトンパターンを使って通知を表示する方法
シングルトンデザインパターンとは?
具体的な手順に入る前に、まず「シングルトンデザインパターン」について簡単におさらいしておきましょう。シングルトンとは、あるクラスのインスタンス生成をアプリケーション全体で1つだけに制限するデザインパターンのことです。代表的な用途としては、同時実行(並行処理)の制御や、データストアへのアクセスを一元化するための中央アクセスポイントの構築などが挙げられます。
この記事では、Androidでシングルトンクラスを経由して通知を表示する実装方法を、サンプルコードとともに解説していきます。
手順1:新規プロジェクトの作成
まずはAndroid Studioで新しいプロジェクトを作成します。メニューバーからFile → New Projectを選択し、必要事項を入力してプロジェクトを作成してください。
手順2:レイアウトファイルの作成(activity_main.xml)
res/layout/activity_main.xmlに以下のコードを記述します。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical"> <Button android:id="@+id/show" android:text="Show notification from singleTone" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
このコードではボタンを1つだけ配置しています。ユーザーがこのボタンをタップすると、シングルトンクラスを経由して通知が表示される仕組みです。
手順3:MainActivity.javaの実装
src/MainActivity.javaに以下のコードを記述します。
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button show;
singleTonExample singletonexample;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = findViewById(R.id.show);
singletonexample = singleTonExample.getInstance();
singletonexample.init(getApplicationContext());
show.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onClick(View v) {
singletonexample.notification(MainActivity.this);
}
});
}
}ここでは、先ほど配置したボタンにクリックリスナーを設定し、タップされたタイミングでシングルトンクラスのnotification()メソッドを呼び出しています。
手順4:シングルトンクラス(singleTonExample.java)の作成
上記コード内では、singleTonExampleをシングルトンクラスとして扱っています。そこで新規クラスsingleTonExample.javaを作成し、以下のコードを追加しましょう。
package com.example.andy.myapplication;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.support.annotation.RequiresApi;
import android.widget.Toast;
public class singleTonExample {
public static final String ANDROID_CHANNEL_ID = "com.example.andy.myapplication";
private static singleTonExample ourInstance = new singleTonExample();
private Context appContext;
private singleTonExample() { }
public static Context get() {
return getInstance().getContext();
}
public static synchronized singleTonExample getInstance() {
return ourInstance;
}
public void init(Context context) {
if (appContext == null) {
this.appContext = context;
}
}
private Context getContext() {
return appContext;
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void notification(final MainActivity mainActivity) {
NotificationManager notif =(NotificationManager)mainActivity.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel androidChannel = new NotificationChannel(ANDROID_CHANNEL_ID,
"Notification Channel", NotificationManager.IMPORTANCE_DEFAULT);
androidChannel.enableLights(true);
androidChannel.enableVibration(true);
androidChannel.setLightColor(Color.GREEN);
androidChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notif.createNotificationChannel(androidChannel);
Notification notify = null;
notify = new Notification.Builder(mainActivity,ANDROID_CHANNEL_ID).setContentTitle("Notification").setContentText("Sample Text").
setContentTitle("Sample Subject").setSmallIcon(R.mipmap.ic_launcher).build();
notif.notify(0, notify);
}
}このクラスでは、privateなコンストラクタと静的なgetInstance()メソッドによってインスタンスの唯一性を保証しています。さらに、init()メソッドでアプリケーションコンテキストを保持し、notification()メソッド内で通知チャンネルの作成と通知の表示を行う構成になっています。
アプリの実行と動作確認
それではアプリケーションを実行してみましょう。ここでは、実際のAndroid端末がパソコンに接続されているものとして説明します。Android Studioからアプリを起動するには、プロジェクト内の任意のアクティビティファイルを開き、ツールバーのRunアイコンをクリックします。デバイス選択ダイアログで自分のスマートフォンを選択すると、端末に以下のような初期画面が表示されます。

次に、画面上のボタンをタップしてみてください。シングルトンクラスから発行された通知が、以下のように表示されます。

-
【Android】InboxStyle(受信トレイ形式)の通知を実装する方法をステップ解説
はじめに この記事では、AndroidアプリでInboxStyle(受信トレイ形式)の通知を実装する方法を、実際のコード例とともにわかりやすく解説します。InboxStyleは、Gmailのように複数行のテキストをまとめて表示できる通知スタイルで、メッセージや更新情報の一覧を通知領域に見せたい場合に非常に便利です。 手順1:新しいプロジェクトを作成する まず、Android Studioを開き、「File」→「New Project」を選択して、必要事項を入力し、新しいプロジェクトを作成しましょう。 手順2:レイアウトファイル(activity_main.xml)を編集する res/lay
-
【Android】Notification.deleteIntentの使い方を徹底解説!通知削除を検知する方法
Androidアプリ開発において、Notification.deleteIntentは「ユーザーが通知を削除(スワイプして消去)した瞬間」を検知できる非常に便利な仕組みです。本記事では、deleteIntentを実際に使ったサンプルアプリを通じて、その実装手順をステップごとにわかりやすく解説します。deleteIntentとは?deleteIntentにPendingIntentを設定しておくと、ユーザーが通知を消去した際にシステムがそのPendingIntentを発行してくれます。これにより、「通知を閉じたらデータをクリアする」「削除されたことをログに記録する」といった処理を実現できます。そ