※前提条件:本情報はAndroid Studio 1.5.1を基づいて説明してる 概要 †Serviceは、Activity、Broadcast receiver、他のServiceによって起動できる。 注意事項: Service †特徴
メソッド呼び出し順
ソースサンプル 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 †特徴
ソースサンプル 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ガリバー コメント: |