| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
openkk
13年前发布

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);      }     } 

通过这个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 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1329280273124.html
Android开发 移动开发 Android