---
title: "android开机启动服务v1.0"
author: "veryEdu"
date: "2011-07-05T09:17:01Z"
tags: []
categories: ["移动开发"]
slug: "android-v1-0"
draft: false
lastmod: "2011-07-05T09:17:01Z"
id: 1114543
url: "https://veryedu.iteye.com/blog/1114543"
---

这是个很简单的过程，这个不像pc机得开机启动，要有精确的内存地址，这里所谓的简单是跟pc机得开机启动相比。android系统的宗旨说的是，不要来找我，我会来找你。 
  Activity好像是应用程序的眼睛，用眼神与用户交流而用户则用手指头告诉Activity我想要什么。BroadcastReceiver好比android程序的耳朵，接受来自各方的Intent。Service好比android应用程序的手，正确完成耳朵接收到得消息，最后，我 来 组 成 头 部。虽然本人只对Activity是眼睛这句话有深刻的理解，剩下两句没有第一句感觉那么精辟，但是直觉三句话都很精辟所以从书上抄下来了。 
  过程是这样的，当所有的android系统服务启动完成以后，会像发传单一样像外面散布消息，这个过程就是广播，我们需要做的就是去捕捉这个系统启动完成的消息，捕捉到这个消息以后，该启动Activity就启动Activity，该启动服务就启动服务，最好的办法就是实践。 
  为了更好的理解这个过程，先按部就班的开始，以后玩熟练了想横着玩就横着玩想竖着玩就竖着玩。 
  创建好了工程项目之后，定义一个广播类，继承自BroadcastReceiver，这个类得作用就是捕捉到系统发出的消息以后做的事情代码都写在这个类里面，捕捉系统消息只需只需在AndroidManifest.xml文件中添加两个元素就可以。 

```xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"      
    package="com.fly" android:versionCode="1" android:versionName="1.0">      
    <application android:icon="@drawable/icon" android:label="@string/app_name">      
        <activity android:name=".BootSayHello" 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=".BootReceiver">      
            <intent-filter>      
                <action android:name="android.intent.action.BOOT_COMPLETED" />      
            </intent-filter>      
        </receiver>      
    </application>      
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>      
    <uses-sdk android:minSdkVersion="7" />      
</manifest>

```
   

这是全部的xml文件，intent-filter用于过滤需要捕捉什么类型的系统消息，<receiver android:name=".BootReceiver">  这句是自己定义的广播类得类名，最后，还要取得权限允许捕捉系统消息<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission> 这句话就这个意思。 
  再回到刚才定义的继承自BroadcastReceiver类： 

```java
 public class BootBroadcastReceiver extends BroadcastReceiver {      
   public static final String ACTION = "android.intent.action.BOOT_COMPLETED";   
       
    @Override      
    public void onReceive(Context context, Intent intent) {   
           
        // TODO Auto-generated method stub      
        if (intent.getAction().equals(ACTION)) {    
            Log.d("TAG","ok");   
             
        }      
    }      
}     

```


if条件里面：如果接收到的消息是我们刚才在xml文件中定义的消息，那么就打印"ok"，这两个步骤做完了，就可以启动模拟器测试了。这里为了便于扩展，所以只打印“ok”。