チュートリアル : フォアグラウンドサービスの使用方法
バックグラウンド で実行しているときに、フォアグラウンドサービスを使用して位置情報の更新を取得する方法を以下に示します。 フォアグラウンドサービスは、 Android の通知メカニズムを使用して、バックグラウンドアクティビティについてユーザーに通知します。 また、ユーザーがサービスと対話することもできます。
注
完全な実装は、GitHub にあるPositioningWithBackgroundUpdatesサンプルアプリ で確認できます。
ステップ 1 : サービスのサブクラスの作成
Service
クラスを拡張し、必要なメソッドをオーバーライドします。 このチュートリアルでは、クラスForegroundService
を呼び出しました。このクラスの完全な実装は、 GitHub にあります。
public class ForegroundService extends Service {
private static final String CHANNEL_ID = "ForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
ステップ 2 : 通知チャネルを作成
通知チャネルを作成するには 、次のコードをクラス ForegroundService
に追加します。
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
ステップ 3 : 位置情報の処理を挿入
ユーザーの同意を処理するに は、 GitHub または「位置情報を探す」セクションに表示されているように、追加のコードを挿入する必要があります。 バックグラウンドでの更新を有効にしない場合でも、この部分は常に必須です。
また、位置情報の更新を受信するための startLocating()
や、アプリが破棄されたときの stopLocating()
などのメソッドを必ず実装する必要があります。バックグラウンドでの更新を有効にしない場合でも、これらのメソッドは常に必要です。 このコードは 、 GitHub または[ 場所を検索 ] セクションにあります。
同様 に、位置の更新を処理するには、 LocationListener を実装する必要があります。 このために、バックグラウンドでない更新と同じコードを使用できます。
ステップ 4 : アクティビティからフォアグラウンドサービスを開始
バックグラウンドでの更新を取得できるようにするには、startService()
を呼び出します。 サービスは、専用のボタンなどを使用してstopService()
をコールすることで停止できます。 Activity
は、次の 2 つの方法を追加できます。
public void startService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android");
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
stopService(serviceIntent);
}
ステップ 5 : サービスを宣言し、権限を追加
AndroidManifest
で 、Service
クラスの名前を追加する必要があります。
注 ACCESS_BACKGROUND_LOCATION
: アクセス許可を追加することで、ユーザーにバックグラウンドでの更新を許可するよう明示的に要求する必要があります。 さらに、 FOREGROUND_SERVICE
および POST_NOTIFICATIONS
権限が必要です。
以下に、 HERE Positioning で必要とされるその他のすべての権限と組み合わせた例を示します。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.foregroundservice">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<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=".ForegroundService"
android:enabled="true"
android:exported="true"></service>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
これで、アプリ はバックグラウンドで完全に動作可能になり、デバイスがロックされていても位置情報イベントを受信できます。 バックグラウンドでの位置情報の更新処理は機密性の高いトピックになることがあります。そのため、この機能が必要な理由をユーザーに通知してください。また、 Android OS は、ロック画面でアプリ が実行中でアクティブであることをユーザーに通知します。 場所の更新頻度を減らして、不要なときにバッテリの消耗を避けることを検討 してください。たとえば、LocationAccuracy
の頻度を低く設定します ( 例 : HUNDREDS_OF_METERS
) 。