Android

※前提条件:本情報はAndroid Studio 1.5.1を基づいて説明してる

概要

Serviceは、Activity、Broadcast receiver、他のServiceによって起動できる。

注意事項:
Service自身では、新しいスレッドで実行しないため、Serviceに複雑、時間がかかる処理を実装しないようにしてください。じゃないと、ANR問題が発生する可能性が高い(応答なし)

Service

特徴

  • 常時動作している処理を向いている
  • メインスレッドで動作している

メソッド呼び出し順

  1. onCreate
  2. onBind
  3. onServiceConnection
  4. onUnbind
  5. onDestroy

ソースサンプル

public class TestService extends Service {
    public TestService () {
    }

    //サービスが新規作成する場合のみ実行する
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    //サービスが起動される場合のみ実行する
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

AndroidManifest.xmlサンプル

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <service
        android:name=".TestService"
        android:enabled="true"
        android:exported="true"></service>
        
</application>

IntentService

特徴

  • マルチスレッドに向いてる
  • メインスレッドとの分離
  • 新しいスレッドでサービスを実行する
  • Intentをひとつずつ渡してくれるキューを作る
  • すべてのリクエストの処理が終わったら、サービスを終了する

ソースサンプル

public class TestService extends IntentService {
    public TestService () {
    }

    //サービスが新規作成する場合のみ実行する
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    //サービスが起動される場合のみ実行する
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

自動起動

パワーオンの時、自動的に起動する

public class BootBroadcast extends BroadcastReceiver {
       @Override
       public void onReceive(Context ctx, Intent intent) {
            ctx.startService(new Intent(ctx, TestService.class));
       }
}

Manifest.xml内での定義

<receiver android:name=".BootBroadcast">
    <intent-filter >
         <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>


中古車買取実績No.1ガリバー

コメント:



(画像の文字列を入力して下さい)

トップ   編集 凍結 差分 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2019/12/02 (月) 12:32:33 (1627d)

e[NȂECir Yahoo yV LINEf[^[Ōz500~`I
z[y[W ̃NWbgJ[h COiq@COsیI COze