Androidで通知からサービスを開始するには?基本の手順とサンプルコードを解説
この記事では、Androidアプリで通知からサービス(Service)を開始する方法を、サンプルコードとともにわかりやすく解説します。AlarmManagerとPendingIntentを組み合わせることで、毎日決まった時刻にサービスを自動起動し、通知を表示する仕組みを実装できます。
実装の全体像
今回作成するアプリは、ボタンをタップすると翌日の午前0時にサービスが起動されるようスケジュールされ、サービス側で通知チャンネルを作成して通知を表示します。手順は以下の5ステップです。
- Android Studioで新規プロジェクトを作成する
- activity_main.xmlにボタンを配置する
- MainActivityにアラームのスケジュール処理を実装する
- NotifyServiceで通知を生成・表示する
- AndroidManifest.xmlに権限とサービスを登録する
ステップ1:新規プロジェクトを作成する
Android Studioを開き、メニューから「File」→「New Project」を選択します。必要な項目を入力して、新しいプロジェクトを作成しましょう。
ステップ2:res/layout/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:onClick="createNotification"
android:text="create notification"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
ステップ3:src/MainActivity を編集する
次に、src/MainActivity.java に以下のコードを追加します。ボタンがタップされると createNotification() メソッドが呼び出され、AlarmManagerを使って「翌日午前0時を起点に24時間ごと」にNotifyServiceが起動される繰り返しアラームを登録します。
package app.tutorialspoint.com.notifyme;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void createNotification(View view) {
Intent myIntent = new Intent(getApplicationContext(), NotifyService.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
calendar.add(Calendar.DAY_OF_MONTH, 1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 60 * 24, pendingIntent);
}
}
ステップ4:src/NotifyService を編集する
続いて、通知を実際に表示する NotifyService クラスを作成します。Android 8.0(API 26)以降では通知チャンネルの作成が必須となるため、OSバージョンを判定してチャンネルを生成している点がポイントです。
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
public class NotifyService extends Service {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
public NotifyService() {
}
@Override
public IBinder onBind(Intent intent) {
Intent notificationIntent = new Intent(getApplicationContext(),
MainActivity.class);
notificationIntent.putExtra("fromNotification", true);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext(), default_notification_channel_id);
mBuilder.setContentTitle("My Notification");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setContentText("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());
throw new UnsupportedOperationException("Not yet implemented");
}
}
ステップ5:AndroidManifest.xml を編集する
最後に、AndroidManifest.xml にVIBRATE権限・RECEIVE_BOOT_COMPLETED権限、そしてNotifyServiceの宣言を追加します。サービスを外部から起動できるよう exported="true" を設定している点にも注目してください。
<?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"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<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">
<service
android:name=".NotifyService"
android:enabled="true"
android:exported="true">
</service>
<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」アイコンをクリックします。デバイス選択ダイアログで自分のモバイル端末を選ぶと、端末にアプリの初期画面が表示されます。

補足:最新環境で試す場合の注意点
本記事のサンプルはサポートライブラリ(android.support)を使用したコードベースのため、現在のAndroid Studioで新規プロジェクトを作成する場合は、以下の点に注意してください。
- AndroidXへの移行: AppCompatActivity は androidx.appcompat.app.AppCompatActivity、NotificationCompat は androidx.core.app.NotificationCompat をインポートします。
- 通知権限の追加: Android 13(API 33)以降では、AndroidManifest.xml への POST_NOTIFICATIONS 権限の追加と、実行時の権限リクエストが必要です。
- PendingIntentのフラグ指定: Android 12(API 31)以降では、PendingIntent生成時に FLAG_IMMUTABLE または FLAG_MUTABLE の指定が必須となっています。
-
Androidアプリで端末起動時にサービスを自動開始する方法【コード例付きで解説】
はじめにAndroidアプリの中には、端末が再起動された後もバックグラウンド処理を継続したいケースがあります。本記事では、BroadcastReceiverとBOOT_COMPLETEDアクションを組み合わせて、端末の起動完了時にサービスを自動的に開始する方法を、実際のコード例とともにステップごとに解説します。この仕組みを実現するには、まずシステムから「起動完了」のブロードキャストを受け取るレシーバーを用意し、その中でActivityやServiceを起動します。以下の手順に従って実装していきましょう。Step 1:新規プロジェクトを作成するAndroid Studioを開き、「File」→「
-
Androidからマルウェアを削除する方法|感染の兆候と予防策を徹底解説
現代社会において、スマートフォンは生活に欠かせない存在となっています。銀行アプリ、ナビゲーションアプリ、各種ユーティリティアプリなど、個人の重要な情報や機能がほぼすべて詰まっています。だからこそ、プライバシーを守るためにも、スマートフォンをしっかりと保護することが何よりも重要です。パソコンと同様に、Androidスマートフォンもウイルス、トロイの木馬、スパイウェア、アドウェアなどの悪意あるプログラム(マルウェア)に感染する可能性があります。Androidマルウェアの主な目的は、機密情報の窃取、無関係な広告の表示によるユーザーの誤誘導、悪質なサイトへのリダイレクトなどです。マルウェアはさまざまな