android實現開機啟動服務

openkk 12年前發布 | 109K 次閱讀 Android開發 移動開發 Android

開機啟動服務的關鍵點是,當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);
} 

} </pre>

通過這個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

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!