[android] 02_Service的生命周期和开启自启动Service

Android 4.0

Service的生命周期和开启自启动Service

1、Service的生命周期 void onCreate() 开启服务,只执行一次,服务开启后,不在调用此方法
int onStartCommand(Intent intent, int flags, int startId) 每次开启服务都会执行的方法
void onDestroy() 停止服务

注意:开启该服务Service的组件退出去,Service也不会停止,两种方式停止 
a) void onDestroy() 停止服务
b) 按下面的操作停止Service

 点击停止可以停止服务
2、开机自启动Service 
a) 使用BroadcastProvider
b)注册系统的开机的完成广播:android.intent.action.BOOT_COMPLETED
<receiver android:name="cn.zengfansheng.serviceLifecycle.MyBootCompleted" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>  
c) 需要用户权限 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>


结果:

核心代码:
/**
 * TODO:一、开机完成的广播--注册该广播(需要权限:android.permission.RECEIVE_BOOT_COMPLETED)
 * 
 * @author hacket
 * 
 */
public class MyBootCompleted extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("开机完成。。。");
        Intent intent2 = new Intent(context, MyService.class);
        context.startService(intent2);
    }
}

<!--TODO 二、xml中配置注册的广播  -->
<receiver android:name="cn.zengfansheng.serviceLifecycle.MyBootCompleted" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>