Service是android四大组件之一,与Activity类似,有着自己的生命周期,但是其没有界面,始终运行在后台。
一、配置、创建Service
与开发Activity类似,也需要两个步骤。
1、定义一个继承Service的子类
public class MyService extends Service {
private static final String TAG="MyService";
//必须实现的方法,返回一个IBinder对象,应用程序可过该对象与Service组件通信
@Override
public IBinder onBind(Intent intent) {
return null;
}
//Service第一次创建的时候回调该方法
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG,"Service-onCreate");
}
//当service被摧毁,即关闭之前回调该方法
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service-onDestroy");
}
//每当客户端调用startService(Intent intent)方法时回调该方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service-onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
//当该Service上绑定的所有客户端都断开连接时回调该方法
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "Service-onUnbind");
return super.onUnbind(intent);
}
//系统内存不足,所有后台程序(background的进程,不是指后台运行的进程)都被杀死时,系统会调用该方法
@Override
public void onLowMemory() {
super.onLowMemory();
Log.i(TAG, "Service-onLowMemory");
}
}
2、在AndroidManifest.xml文件中配置该Sercice
<service android:name=".Service.MyService">
<intent-filter>
<action android:name=".Service.MyService"/>
</intent-filter>
</service>
Android中运行Service有两种方式:
1、通过Context的startService()方法–>访问者与Service之间没有关联,即使访问者退出了,Service仍然运行
2、通过Context分bindService()方法–>访问者与Service绑定在一起,访问者一经退出,Service也就终止
未完待续。。。。