Android-services

提供:Dev Guides
移動先:案内検索

Android-サービス

'_*サービス*は、ユーザーと対話することなく長時間実行される操作を実行するためにバックグラウンドで実行されるコンポーネントであり、アプリケーションが破壊されても動作します。 サービスは本質的に2つの状態を取ることができます-_

Sr.No. State & Description
1

Started

アクティビティなどのアプリケーションコンポーネントが_startService()_を呼び出してサービスを開始すると、サービスが*開始*されます。 開始されたサービスは、開始したコンポーネントが破壊された場合でも、バックグラウンドで無期限に実行できます。

2

Bound

アプリケーションコンポーネントが_bindService()_を呼び出してサービスにバインドすると、サービスは*バインド*されます。 バインドされたサービスは、コンポーネントがサービスと対話したり、要求を送信したり、結果を取得したり、プロセス間通信(IPC)を使用してプロセス間で実行したりできるようにするクライアントサーバーインターフェイスを提供します。

サービスには、サービスの状態の変化を監視するために実装できるライフサイクルコールバックメソッドがあり、適切な段階で作業を実行できます。 左の次の図は、startService()でサービスが作成されたときのライフサイクルを示し、右の図はbindService()で作成されたときのライフサイクルを示しています。(image courtesy:android.com)

Androidサービスライフサイクル

サービスを作成するには、Service基本クラスまたはその既存のサブクラスの1つを拡張するJavaクラスを作成します。 Service 基本クラスはさまざまなコールバックメソッドを定義し、最も重要なものを以下に示します。 すべてのコールバックメソッドを実装する必要はありません。 ただし、それぞれを理解し、アプリがユーザーの期待どおりに動作することを保証するものを実装することが重要です。

Sr.No. Callback & Description
1

onStartCommand()

システムは、アクティビティなどの別のコンポーネントが_startService()_を呼び出してサービスの開始を要求すると、このメソッドを呼び出します。 このメソッドを実装する場合、_stopSelf()_または_stopService()_メソッドを呼び出して、サービスが終了したらサービスを停止するのはユーザーの責任です。

2

onBind()

別のコンポーネントが_bindService()_を呼び出してサービスにバインドする場合、システムはこのメソッドを呼び出します。 このメソッドを実装する場合は、_IBinder_オブジェクトを返すことにより、クライアントがサービスとの通信に使用するインターフェイスを提供する必要があります。 このメソッドは常に実装する必要がありますが、バインディングを許可したくない場合は、_null_を返す必要があります。

3

onUnbind()

システムは、すべてのクライアントがサービスによって公開された特定のインターフェイスから切断されると、このメソッドを呼び出します。

4

onRebind()

システムは、_onUnbind(Intent)_ですべてが切断されたことを以前に通知された後、新しいクライアントがサービスに接続したときにこのメソッドを呼び出します。

5

onCreate()

システムは、_onStartCommand()_または_onBind()_を使用してサービスが最初に作成されたときにこのメソッドを呼び出します。 この呼び出しは、1回限りのセットアップを実行するために必要です。

6

onDestroy()

サービスが使用されなくなり、破棄されるときに、システムはこのメソッドを呼び出します。 サービスはこれを実装して、スレッド、登録済みリスナー、レシーバーなどのリソースをクリーンアップする必要があります。

次のスケルトンサービスは、各ライフサイクルメソッドを示しています-

package com.finddevguides;

import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;

public class HelloService extends Service {

  /* *indicates how to behave if the service is killed*/
   int mStartMode;

  /* *interface for clients that bind*/
   IBinder mBinder;

  /* *indicates whether onRebind should be used*/
   boolean mAllowRebind;

  /* *Called when the service is being created.*/
   @Override
   public void onCreate() {

   }

  /* *The service is starting, due to a call to startService()*/
   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      return mStartMode;
   }

  /* *A client is binding to the service with bindService()*/
   @Override
   public IBinder onBind(Intent intent) {
      return mBinder;
   }

  /* *Called when all clients have unbound with unbindService()*/
   @Override
   public boolean onUnbind(Intent intent) {
      return mAllowRebind;
   }

  /** Called when a client is binding to the service with bindService()*/
   @Override
   public void onRebind(Intent intent) {

   }

  /* *Called when The service is no longer used and is being destroyed*/
   @Override
   public void onDestroy() {

   }
}

この例では、簡単な手順で、独自のAndroidサービスを作成する方法を示します。 _Hello World Example_の章で作成したAndroidアプリケーションを変更するには、次の手順に従います-

Step Description
1 You will use Android StudioIDE to create an Android application and name it as My Application under a package com.example.finddevguides7.myapplication as explained in the Hello World Example chapter.
2 Modify main activity file MainActivity.java to add startService() and stopService() methods.
3 Create a new java file MyService.java under the package com.example.My Application. This file will have implementation of Android service related methods.
4 Define your service in AndroidManifest.xml file using <service…​/> tag. An application can have one or more services without any restrictions.
5 Modify the default content of res/layout/activity_main.xml file to include two buttons in linear layout.
6 No need to change any constants in res/values/strings.xml file. Android studio take care of string values
7 Run the application to launch Android emulator and verify the result of the changes done in the application.

以下は、変更されたメインアクティビティファイル MainActivity.java の内容です。 このファイルには、基本的なライフサイクルメソッドのそれぞれを含めることができます。 サービスを開始および停止する_startService()_および_stopService()_メソッドを追加しました。

package com.example.finddevguides7.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {
   String msg = "Android : ";

  /* *Called when the activity is first created.*/
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Log.d(msg, "The onCreate() event");
   }

   public void startService(View view) {
      startService(new Intent(getBaseContext(), MyService.class));
   }

  //Method to stop the service
   public void stopService(View view) {
      stopService(new Intent(getBaseContext(), MyService.class));
   }
}

以下は MyService.java の内容です。 このファイルには、要件に基づいてサービスに関連付けられた1つ以上のメソッドの実装を含めることができます。 今のところ、_onStartCommand()_と_onDestroy()_の2つのメソッドのみを実装します−

package com.example.finddevguides7.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

/**
   * Created by finddevguides7 on 8/23/2016.
*/

public class MyService extends Service {
   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
      return null;
   }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
     //Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }

   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}

以下は、_AndroidManifest.xml_ファイルの変更されたコンテンツです。 ここで、サービスを含めるために<service …​/>タグを追加しました-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.finddevguides7.myapplication">

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      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=".MyService"/>
   </application>

</manifest>

以下は、2つのボタンを含む res/layout/activity_main.xml ファイルの内容です-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Example of services"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp"/>

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_above="@+id/imageButton"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="40dp"/>

   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_centerVertical="true"
      android:layout_centerHorizontal="true"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/button2"
      android:text="Start Services"
      android:onClick="startService"
      android:layout_below="@+id/imageButton"
      android:layout_centerHorizontal="true"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Stop Services"
      android:id="@+id/button"
      android:onClick="stopService"
      android:layout_below="@+id/button2"
      android:layout_alignLeft="@+id/button2"
      android:layout_alignStart="@+id/button2"
      android:layout_alignRight="@+id/button2"
      android:layout_alignEnd="@+id/button2"/>

</RelativeLayout>

変更したばかりの* Hello World!アプリケーションを実行してみましょう。 環境設定中に *AVD を作成したと思います。 Androidスタジオからアプリを実行するには、プロジェクトのアクティビティファイルの1つを開き、ツールバーの[画像:/android/images/eclipse_run.jpg [Android StudioRunアイコン]の実行]アイコンをクリックします。 Android StudioはAVDにアプリをインストールして起動し、セットアップとアプリケーションで問題がなければ、次のエミュレータウィンドウが表示されます-

Android Service Demo

サービスを開始するには、*サービスの開始*ボタンをクリックします。これによりサービスが開始され、_onStartCommand()_メソッドのプログラミングに従って、メッセージ_Service Started_がシミュレータの下部に次のように表示されます-

Androidサービス開始

サービスを停止するには、[サービスの停止]ボタンをクリックします。