安卓service是安卓四大组件之一,是在后台运行的一个不可见的服务,比如后台检查是否有更新,后台进行一些下载任务等。
service和activity一样,都运行在主线程上,切忌service并不是一个异步线程额,所以如果需要在service里进行一些耗时操作,需要单开一个线程处理。
下面我们创建一个service。
public class MyService extends Service {
public MyService() {
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
}
manifest中
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
首次创建服务时,系统会调用onCreate方法,每次通过startService()方法启动Service时都会调用onStartCommand方法。
开启service方法:
Intent intent = new Intent(this, MyService.class);
startService(intent)
停止service方法:
Intent intent_stop = new Intent(this, MyService.class);
stopService(intent_stop);