2010年10月8日 星期五

[Android] 開機自動啟動的service

程式架構
|-- AndroidManifext.xml     // --> 設定receiver, service, uses-permission
`-- src
    |-- DoService.java      // --> 實際執行的service
    `-- HelloReceiver.java  // --> 接受啟動訊息, 再啟動DoService

直接看扣,
HelloReceiver.java
package hello.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class HelloReceiver extends BroadcastReceiver {
  @Override
    public void onReceive(Context context, Intent intent) {
      context.startService(new Intent(context, DoService.class)); 
    }   
}

DoService.java
package hello.receiver;

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

public class DoService extends Service {
  private Handler handler = new Handler();
  private int delay_interval = 1000 * 60; // do every 60 seconds

  @Override
    public void onStart(Intent intent, int startId) {
      handler.postDelayed(doUpdate, delay_interval);
      super.onStart(intent, startId);
    }

  public Runnable doUpdate = new Runnable() {
    public void run() {
      handler.postDelayed(this, delay_interval);
    }
  };

  @Override
    public IBinder onBind(Intent arg0) {
      return null;
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="hello.receiver"
  android:versionCode="1"
  android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".HelloReceiver" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <receiver android:name="HelloReceiver">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.HOME" />
      </intent-filter>
    </receiver>
    <service android:name=".myThread">
      <intent-filter>
        <action android:name="hello.receiver.DoService" />
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </service>
   </application>
   <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
</manifest>

reference:
* Running code on phone boot
* Starting an Android service after boot

沒有留言: