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

AndroidでサービスをstartForeground()でフォアグラウンド起動する方法を解説


Androidにおけるサービスとは

実装例に入る前に、Androidの「サービス」について簡単におさらいしておきましょう。サービスとは、UIを表示せずにバックグラウンドで処理を実行するためのコンポーネントであり、アクティビティが破棄された後も動作を続けられるのが特徴です。

本記事では、サービスをフォアグラウンドで起動するstartForeground()の実装方法を、サンプルコードとともに段階的に解説します。

手順1:Android Studioで新規プロジェクトを作成する

まず、Android Studioを起動し、メニューから「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトを完成させてください。

手順2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xmlに以下のコードを追加します。

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "https://schemas.android.com/apk/res/android"
   xmlns:app = "https://schemas.android.com/apk/res-auto"
   xmlns:tools = "https://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
   <TextView
      android:id = "@+id/text"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:text = "Start Service"
      android:textSize = "25sp"
      app:layout_constraintBottom_toBottomOf = "parent"
      app:layout_constraintLeft_toLeftOf = "parent"
      app:layout_constraintRight_toRightOf = "parent"
      app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>

上記のコードでは、画面中央にTextViewを1つ配置しています。ユーザーがこのTextViewをタップすると、サービスのstartForeground()が呼び出される仕組みです。

手順3:MainActivity.javaを実装する

続いて、src/MainActivity.javaに以下のコードを追加します。

package com.example.andy.myapplication;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView text = findViewById(R.id.text);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMyServiceRunning(service.class)) {
                    text.setText("Stoped");
                    stopService(new Intent(MainActivity.this, service.class));
                } else {
                    text.setText("Started");
                    startService(new Intent(MainActivity.this, service.class));
                }
            }
        });
    }
    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}

上記のコードでは、IntentにContextとサービスクラスを渡すことで、サービスの開始と停止を行っています。また、isMyServiceRunning()メソッドでサービスがすでに起動中かどうかを判定し、状態に応じて処理を切り替えています。

次に、パッケージフォルダ内にserviceクラス(service.java)を作成し、以下のコードを追加してください。

package com.example.andy.myapplication;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class service extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @TargetApi(Build.VERSION_CODES.O)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Notification Service started by user.", Toast.LENGTH_LONG).show();
        String NOTIFICATION_CHANNEL_ID = "com.example.andy.myapplication";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        Notification notification = new Notification.Builder(this,NOTIFICATION_CHANNEL_ID)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("My Awesome App")
        .setContentIntent(pendingIntent).build();
        startForeground(1337, notification);
        return START_STICKY;
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
        Toast.makeText(this, "Notification Service destroyed by user.", Toast.LENGTH_LONG).show();
    }
}

上記のコードでは、Android 8.0(APIレベル26)以降で必須となった通知チャンネルを作成し、Notification.Builderを使って通知を構築しています。該当する部分を抜き出すと、以下の通りです。

String NOTIFICATION_CHANNEL_ID = "com.example.andy.myapplication";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(this,NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Awesome App")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);

フォアグラウンドでの起動と停止は、それぞれ以下のメソッドで行います。

startForeground(1337, notification);
stopForeground(true);

ポイント:Android 8.0以降では、フォアグラウンドサービスを開始する際に必ず通知を表示する必要があります。そのため、事前に通知チャンネルを作成しておくことが重要です。

手順4:manifest.xmlを編集する

最後に、manifest.xmlに以下のコードを追加します。

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
    package = "com.example.andy.myapplication">
    <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 = ".service"/>
    </application>
</manifest>

<service>タグによるサービスの宣言を忘れないようにしましょう。この宣言がないと、アプリ実行時にエラーが発生します。

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

それでは、アプリケーションを実行してみましょう。ここでは、実機のAndroidスマートフォンをパソコンに接続しているものとします。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。表示された選択肢から自分のモバイルデバイスを選ぶと、端末に以下のような初期画面が表示されます。

AndroidでサービスをstartForeground()でフォアグラウンド起動する方法を解説

上記がアプリの初期画面です。TextViewをタップすると、以下のように通知サービスが開始されます。

AndroidでサービスをstartForeground()でフォアグラウンド起動する方法を解説

上記の結果、サービスが起動しました。この状態でもう一度TextViewをタップすると、以下のように通知サービスが停止します。

AndroidでサービスをstartForeground()でフォアグラウンド起動する方法を解説

  1. 【Android開発】AlarmManagerを使ってサービスを起動する方法を徹底解説

    この記事では、AndroidアプリにおいてAlarmManager(アラームマネージャー)を使用してサービス(Service)を起動する方法を、サンプルコードとともにステップ形式で解説します。指定した時刻に処理を自動実行したい場合や、バックグラウンドでの定期処理を実装したい場合に役立つテクニックです。実装の全体像本チュートリアルで作成するアプリは、以下の構成になっています。「Start Service Alarm」ボタン:3秒後にサービスを起動するアラームをセット「Cancel Service」ボタン:セット済みのアラームをキャンセルそれでは、順番に実装していきましょう。ステップ1:新規プロジ

  2. Androidアプリで端末起動時にサービスを自動開始する方法【コード例付きで解説】

    はじめにAndroidアプリの中には、端末が再起動された後もバックグラウンド処理を継続したいケースがあります。本記事では、BroadcastReceiverとBOOT_COMPLETEDアクションを組み合わせて、端末の起動完了時にサービスを自動的に開始する方法を、実際のコード例とともにステップごとに解説します。この仕組みを実現するには、まずシステムから「起動完了」のブロードキャストを受け取るレシーバーを用意し、その中でActivityやServiceを起動します。以下の手順に従って実装していきましょう。Step 1:新規プロジェクトを作成するAndroid Studioを開き、「File」→「