android自动启动服务

来源:互联网 发布:环境信息元数据规范 编辑:程序博客网 时间:2024/05/01 22:12

从下面参考文章上看,service配置可以让service起来, 网上很多文章xml配置都将导致service启动不来

<service android:name=".myservice" android:exported="false">
            <intent-filter>
                <action android:name="shenyh.cam.xxxxx.myservice"></action>
            </intent-filter>
        </service>

下面是参考网址及内容:http://www.open-open.com/lib/view/open1329280273124.html, 

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

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

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

01packagecom.easymorse;
02 
03import android.content.BroadcastReceiver;
04import android.content.Context;
05importandroid.content.Intent;
06 
07public class SmsServiceBootReceiver extendsBroadcastReceiver {
08 
09    @Override
10    public void onReceive(Context context, Intent intent) {
11        Intent myIntent = new Intent();
12        myIntent.setAction(“com.easymorse.SmsService”);
13        context.startService(myIntent);
14    }
15 
16}

通过这个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

0 0
原创粉丝点击