この記事は最終更新日から1年以上経過しています。
Androidでは、端末の起動時に発行されるandroid.intent.action.BOOT_COMPLETED
というブロードキャストインテントを受け取り、処理を実行させることができます。
これを利用し、バックグラウンドで常駐するアプリを作成することが可能です。
ここでは例として位置情報を取得し、位置情報が更新されたらトーストでメッセージを表示するサービスをバックグラウンドで常駐させるように作成しています。
AndroidManifest.xml
のapplication
タグ内に以下を記述
1 | < service android:name = "ExampleService" ></ service > |
3 | android:name = ".BootReceiver" |
4 | android:enabled = "true" > |
7 | < action android:name = "android.intent.action.BOOT_COMPLETED" /> |
8 | < category android:name = "android.intent.category.DEFAULT" /> |
起動時にブロードキャストインテントを受け取れるようにパーミッションの設定を記述します。
1 | < uses-permission android:name = "android.permission.RECEIVE_BOOT_COMPLETED" /> |
ブロードキャストインテントを受け取るブロードキャストレシーバーを作成します。
onReceive
にて、常駐させたいサービスを起動させます。
BootReceiver.java
1 | import android.content.BroadcastReceiver; |
2 | import android.content.Context; |
3 | import android.content.Intent; |
4 | import android.widget.Toast; |
6 | public class BootReceiver extends BroadcastReceiver { |
9 | public void onReceive(Context context, Intent intent) { |
10 | String action = intent.getAction(); |
11 | if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { |
12 | Toast.makeText(context, "BOOT_COMPLETED" , Toast.LENGTH_LONG).show(); |
13 | context.startService( new Intent(context, ExampleService. class )); |
実際に常駐するサービスを作成します。
ExampleService.java
1 | import android.app.Service; |
2 | import android.content.Intent; |
3 | import android.location.Location; |
4 | import android.location.LocationListener; |
5 | import android.location.LocationManager; |
6 | import android.os.Bundle; |
7 | import android.os.IBinder; |
8 | import android.util.Log; |
9 | import android.widget.Toast; |
11 | public class ExampleService extends Service implements LocationListener { |
13 | static final String TAG = "ExampleService" ; |
14 | private LocationManager mLocationManager; |
17 | public void onCreate() { |
18 | Toast.makeText( this , "バックグラウンドサービスを開始しました。" , Toast.LENGTH_SHORT).show(); |
19 | mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); |
23 | public int onStartCommand(Intent intent, int flags, int startId) { |
24 | Log.i(TAG, "onStartCommand Received start id " + startId + ": " + intent); |
25 | mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 , 0 , this ); |
31 | public void onDestroy() { |
32 | Log.i(TAG, "onDestroy" ); |
33 | mLocationManager.removeUpdates( this ); |
37 | public IBinder onBind(Intent intent) { |
42 | public void onLocationChanged(Location location) { |
43 | Toast.makeText( this , "位置情報を更新" , Toast.LENGTH_LONG).show(); |
47 | public void onProviderDisabled(String provider) { |
52 | public void onProviderEnabled(String provider) { |
56 | public void onStatusChanged(String provider, int status, Bundle extras) { |
作成したアプリをインストールし、一度再起動した端末にて、
[設定]-[アプリケーション]-[実行中のサービス]で作成したアプリのところを確認します。
「1件のプロセスと1件のサービス」と表示されていれば成功です。
位置情報が更新された時に、正常にメッセージが表示されるか確認しましょう。