Skip to content

Instantly share code, notes, and snippets.

@yukpiz
Created February 10, 2014 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yukpiz/3c750bdc833af128e3be to your computer and use it in GitHub Desktop.
Save yukpiz/3c750bdc833af128e3be to your computer and use it in GitHub Desktop.

Android service.

  • Activityを持ったアプリケーションを作成し、端末起動時に同包されたサービスを起動する
  • Serviceの作成
  • BroadcastReceiverの作成
  • Permissionの登録
  • ServiceとBroadcastReceiverの登録

Serviceの作成


まずは常駐するサービスをクラスとして作成する。


  • BootupService.java
package service.boot;

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

public class BootupService extends Service {

   @Override
   public void onCreate() {
      Log.d("Service", "onCreate");
      super.onCreate();
   }

   @Override
   public void onStart(Intent intent, int startId) {
      Log.d("Service Lifecycle", "onStart");
      super.onStart(intent, startId);
   }

   @Override
   public IBinder onBind(Intent intent) {
      Log.d("Service Lifecycle", "onBind");
      return null;
   }

   @Override
   public boolean onUnbind(Intent intent) {
      Log.d("Service Lifecycle", "onUnbind");
      super.onUnbind(intent);
      return true;
   }

   @Override
   public void onRebind(Intent intent) {
      Log.d("Service Lifecycle", "onRebind");
      super.onRebind(intent);
   }

   @Override
   public void onDestroy() {
      Log.d("Service Lifecycle", "onDestroy");
      super.onDestroy();
   }
}

BroadcastReceiverの作成


端末起動時に呼び出されるReceiverを作成する。


  • BootReceiver.java
package service.boot;

import android.content.BroadcastReceiver;
import android.content.Contextl;
import android.content.Intent;

public class BootReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent arg1) {
      Intent intent = new Intent(context, BootupService.class);
      context.startService(intent);
   }
}

Permissionの登録


AndroidManifestにPermissionを登録する。


  • AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

ServiceとBroadcastReceiverの登録


AndroidManifestにServiceとBroadcastReceiverを登録する。


<application>
   <activity
      android:name="service.boot.MainActivity"
      android:label="@string/app_name" >
      <intent-filter>
         <action android:name="android.intent.action.MAIN" />
         <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
   </activity>
   <service android:name="BootupService">
   </service>
   <receiver android:name="BootReceiver">
      <intent-filter>
         <action android:name="android.intent.action.BOOT_COMPLETED" />
      </intent-filter>
   </receiver>
</application>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment