アプリを閉じた後もAndroidの通知を受け取る方法【サンプルコード付き】
このチュートリアルでは、アプリが閉じられた(終了・バックグラウンド)状態でもAndroidの通知を受け取る方法を解説します。ServiceとTimerを組み合わせて、一定間隔で自動的に通知を表示するシンプルなサンプルアプリを構築していきます。
手順1:新しいプロジェクトを作成する
Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目を入力して、新しいプロジェクトを作成しましょう。
手順2:レイアウトファイル(activity_main.xml)を編集する
res/layout/activity_main.xml に以下のコードを追加します。ここでは、アプリを閉じて通知を確認するためのボタンを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:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="closeApp"
android:text="close App for notification" />
</RelativeLayout>
手順3:MainActivity を実装する
src/MainActivity に以下のコードを追加します。ポイントは onStop() メソッドです。画面が非表示になったタイミングで NotificationService を起動することで、アプリを閉じた後も通知処理が継続されます。
package app.tutorialspoint.com.notifyme;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStop() {
super.onStop();
// 画面が非表示になったらサービスを起動
startService(new Intent(this, NotificationService.class));
}
public void closeApp(View view) {
finish();
}
}
手順4:NotificationService を実装する
src/NotificationService に以下のコードを追加します。このサービスは Timer を使って5秒ごとに通知を生成します。Android 8.0(API 26)以降では通知チャンネルの作成が必須となるため、OSバージョンを判定してチャンネルを登録しています。
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
public class NotificationService extends Service {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
Timer timer;
TimerTask timerTask;
String TAG = "Timers";
int Your_X_SECS = 5;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
@Override
public void onCreate() {
Log.e(TAG, "onCreate");
}
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
stopTimerTask();
super.onDestroy();
}
// TimerTask 内の処理をHandler経由で実行する
final Handler handler = new Handler();
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 5000, Your_X_SECS * 1000);
}
public void stopTimerTask() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
createNotification();
}
});
}
};
}
private void createNotification() {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), 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());
}
}
手順5:AndroidManifest.xml を編集する
AndroidManifest.xml に以下のコードを追加します。振動を使用するための VIBRATE 権限と、NotificationService の宣言を忘れずに行いましょう。
<?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=".NotificationService"
android:label="@string/app_name">
<intent-filter>
<action
android:name="app.tutorialspoint.com.notifyme.NotificationService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
</application>
</manifest>
アプリを実行して動作を確認しよう
それでは、実際にアプリを実行してみましょう。ここでは実機のAndroid端末をPCに接続しているものとします。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。実行デバイスとして自分のモバイル端末を選択すると、端末にアプリの初期画面が表示されます。
ボタンをタップしてアプリを閉じると、約5秒後に通知が届くことが確認できます。その後も5秒間隔で通知が繰り返し表示されます。
補足:最新のAndroidでの注意点
本記事のコードは従来型のバックグラウンドServiceを使用していますが、Android 8.0以降はバッテリー最適化の観点からバックグラウンドサービスに制限がかかる場合があります。実運用では、フォアグラウンドサービス、WorkManager、あるいはプッシュ通知配信のFCM(Firebase Cloud Messaging)の利用を検討するとより安定した実装になります。
-
Androidで写真撮影中の通知をブロックする方法|MacroDroid活用術
スマートフォンのカメラ性能はここ数年で飛躍的に向上し、誰でも手軽に高品質な写真を撮れるようになりました。しかし、いざシャッターを切ろうという瞬間に通知が画面に割り込んでくると、せっかくのベストショットを逃してしまうことがあります。 「何でもアプリで解決できる」という言葉通り、写真撮影中に通知が邪魔をしないよう制御してくれるアプリも存在します。今回は無料で使いやすい自動化アプリ「MacroDroid」を使って、カメラ使用時に通知をブロックする方法をご紹介します。 カメラアプリ使用時に通知をブロックする手順 友人全員を集めてやっと記念写真を撮ろうとした瞬間に、通知が画面に表示される——こんな経験
-
Windows 10でAndroidの通知をPCで受け取る方法|連携手順を徹底解説
Androidは世界で最も多く利用されているオペレーティングシステムの一つであり、膨大なユーザー数を誇ります。Android搭載スマートフォンの性能が年々向上するにつれ、Windows 10のPC上でAndroidの通知を受け取ることが可能になりました。仕事中やスマートフォンが手元にないときでも、わざわざ端末を取りに行かずに通知を確認できるのは大きなメリットです。Windows 10では、この通知同期機能が標準機能として組み込まれていますが、事前にいくつかの設定を行う必要があります。設定を始める前に、必要なアップデートが適用された正規版のWindows 10を使用していることを確認しておきまし