android实现开机启动服务

openkk 12年前

开机启动服务的关键点是,当android启动完毕后,android会广播一次android.intent.action.BOOT_COMPLETED。如果想在启动后执行自己的代码,需要编写一个广播的接收者,并且注册接收者到这个广播intent上。

这里以android中使用定时任务代码为例,将它的服务改为开机启动。

首先,需要编写一个intent的receiver,比如SmsServiceBootReceiver:

package com.easymorse;     import android.content.BroadcastReceiver;  import android.content.Context;  import android.content.Intent;     public class SmsServiceBootReceiver extends BroadcastReceiver {         @Override      public void onReceive(Context context, Intent intent) {          Intent myIntent = new Intent();          myIntent.setAction(“com.easymorse.SmsService”);          context.startService(myIntent);      }     } 

通过这个Receiver,启动SmsService。那么怎么让这个Receiver工作呢,需要把它注册到android系统上,去监听广播的BOOT_COMPLETED intent。在AndroidManifest.xml中:

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
    package=”com.easymorse” android:versionCode=”1″ android:versionName=”1.0″>
    <application android:icon=”@drawable/icon” android:label=”@string/app_name”>
        <activity android:name=”.SmsServiceOptions” 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=”.SmsService”>
            <intent-filter>
                <action android:name=”com.easymorse.SmsService”></action>
            </intent-filter>
        </service>
        <receiver android:name=”SmsServiceBootReceiver”>
            <intent-filter>
                <action android:name=”android.intent.action.BOOT_COMPLETED”></action>
            </intent-filter>
        </receiver>
    </application>
    <uses-sdk android:minSdkVersion=”3″ />
</manifest>

增加黑体字部分的内容即可。

这样重新开机,服务在开机android系统启动完毕后就会加载。再启动Activity绑定(binding)服务,就可以操作SmsService服务,如果Activity解除绑定,也不会shutdown服务了。

是不是Service会有一个引用计数呢?当计数是0的时候就会shutdown。还要再找时间研究。

源代码见:

http://easymorse.googlecode.com/svn/tags/android.service.start.after.boot.demo