本地服务编写比较简单。首先,要创建一个Service类,该类继承android的Service类。这里写了一个计数服务的类,每秒钟为计数器加一。在服务类的内部,还创建了一个线程,用于实现后台执行上述业务逻辑。
package com.easymorse; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class CountService extends Service { private boolean threadDisable; private int count; @Override public IBinder onBind(Intent intent) { return null ; } @Override public void onCreate() { super .onCreate(); new Thread( new Runnable() { @Override public void run() { while ( ! threadDisable) { try { Thread.sleep( 1000 ); } catch (InterruptedException e) { } count ++ ; Log.v( " CountService " , " Count is " + count); } } }).start(); } @Override public void onDestroy() { super .onDestroy(); this .threadDisable = true ; Log.v( " CountService " , " on destroy " ); } public int getCount() { return count; } }
需要将该服务注册到配置文件AndroidManifest.xml中,否则无法找到:
<? xml version="1.0" encoding="utf-8" ?> < manifest xmlns:android ="http://schemas.android.com/apk/res/android" package ="com.easymorse" android:versionCode ="1" android:versionName ="1.0" > < application android:icon ="@drawable/icon" android:label ="@string/app_name" > < activity android:name =".LocalServiceDemoActivity" android:label ="@string/app_name" > < intent-filter > < action android:name ="android.intent.action.MAIN" /> < category android:name ="android.intent.category.LAUNCHER" /> </ intent-filter > </ activity > < service android:name ="CountService" /> </ application > < uses-sdk android:minSdkVersion ="3" /> </ manifest >
在Activity中启动和关闭本地服务。
package com.easymorse; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class LocalServiceDemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.startService(new Intent(this, CountService.class)); } @Override protected void onDestroy() { super.onDestroy(); this.stopService(new Intent(this, CountService.class)); } }
注意以下几点:
1.可以不stopservice,这时候activity如果退出了,不会影响service,service继续执行,但是如果在任务列表里杀死了app,默认情况下(onstartcommand返回默认值),service会重新启动(重新调用oncreate,count回0),还有一些情况会重启service,比如系统清理进程等,重启servcie会打印类似如下日志:
Scheduling restart of crashed service com.qf.zhouyi.servicetest/.CountService in 5000ms
2.startservice可以执行多次,只有首次执行才会调用oncreate,后面每次执行只会调用onstartcommand,多次start只需要一次stop就能停止service
3.onstartcommand不同返回值的意义:
- START_STICKY(常量值:1):sticky的意思是“粘性的”。使用这个返回值时,我们启动的服务跟应用程序"粘"在一起,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务。当再次启动服务时,传入的第一个参数将为null;
- START_NOT_STICKY(常量值:2):“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。
- START_REDELIVER_INTENT(常量值:3):重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。