服务(Service)是Android四大组件之一,主要用于后台运行和跨服务进程访问。Service并没有UI部分,而是一直在Android系统的后台运行。应用程序一般使用service做一些后台运行的工作,例如,下载文件。
Service也是有生命周期的,但Service的生命周期很简单,只有3个阶段:
创建服务;
开始服务;
销毁服务;
一个服务只会创建一次,销毁一次,但可以开始多次
public class MyService extends Service{
@Override
public IBinder onBind(Intent intent) {
return null;
}
//当服务第一次创建时调用
@Override
public void onCreate() {
Log.d("MyService","onCreate");
super.onCreate();
}
//当服务销毁时调用
@Override
public void onDestroy() {
Log.d("MyService","onDestroy");
super.onDestroy();
}
//开始服务是调用
@Override
public void onStart(Intent intent, int startId) {
Log.d("MyService","onStart");
super.onStart(intent, startId);
}
}
Service也需要去AndroidManifest.xml文件中配置
<service android:enabled="true" android:name=".MyService"/>
android:enabled属性的值为true,表示MyService服务处于激活状态。虽然是激活的但是系统不会启动,想要启动必须显示地调用startService。停止也是一样stopService。
当然我们可以弄开机启动Service,类似Broadcast Receiver(我上一篇博客有讲)。
public class StartupReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context,MyService.class);
//启动Service
context.startService(serviceIntent);
Log.d("start_service","OK!");
}
}
配置文件
<uses-permission android:name="ANDROID.PERMISSION.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService"/>
<receiver android:name=".StartupReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
运行,然后重启模拟器,看看LogCat试图中是否输出了相应的日志信息。