Service是Android四大组件之一,它可以在后台执行长时间运行操作而没有用户界面的应用组件。
Service的启动方式有两种:startService启动和bindService启动,今天先讲讲startService。
先讲讲启动模式:分为显示启动及隐式启动
显式启动
- Intent intentStart = new Intent(ServiceActivity.this, StartService.class);
- startService(intentStart);
隐式启动:需要设置一个Action,可以把Action设置成Service的全路径名字,在这种情况下android:exported默认为true
- Intent serviceIntent=new Intent();
- serviceIntent.setAction("com.android.StartService");
- startService(serviceIntent);
两种启动方法都可以在同一个应用中使用,对于不同的应用,只能使用隐式方法。
本篇文章主要讲显示启动,而且是使用startService的方式。如上面显式启动一样,使用Intent来启动service,通过该方式启动的Service,调用者与Service之间没有关联,即使调用者退出了,Serviec仍然运行,必须显式调用stopService来停止,并且需要将启动Service的Intent传递给stopService()方法。
stopService(intent);
在使用结果没有手动调用 stopService,就会造成内存泄漏,因此要记得关闭Service。
下面看看通过startService启动的生命周期。
onCreate():当Service第一次被创建时,由系统调用。
onStart():当调用startService方法启动Service时,该方法被调用。
onDestory():当调用stopService或者被系统回收时,该方法被调用。
onCreate跟onDestory只能被调用一次,onStart可以被调用多次。比如第一次调用startService时,这时Service还没有被创建,会调用onCreate方法,然后再调用onStart方法;此时在其他调用再一次用startService启动Service时,只会调用onStart方法,而不会调用onCreate已经存在了,也就是说Service只能有一个,不能创建出两个一摸一样的来,onDestory也是同样的道理,Service已经被销毁了,onDestory就不会再被调用了。
下面是例子:
创建MyService.java,继承Service
- public class MyService extends Service {
- @Override
- public void onCreate() {
- super.onCreate();
- MLog.e(getClass().getName(), "onCreate");
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- MLog.e(getClass().getName(), "onStartCommand");
- return super.onStartCommand(intent, flags, startId);
- }
- @Override
- public void onDestroy() {
- MLog.e(getClass().getName(), "onDestroy");
- super.onDestroy();
- }
-
- @Nullable
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- }
AndroidManifest.xml中声明该Service
".service.MyService"/>
Activity或Fragment中去启动该Service,或者去关闭该Service,两个按钮,一个启动,一个关闭。
- Intent intentStart = new Intent(ServiceActivity.this, StartService.class);
- findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- startService(intentStart);
- }
- });
- findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- stopService(intentStart);
- }
- });