這篇博文來介紹Android另外一個十分重要的組件,Service。Service和Activity很相似,區別在於它運行在後臺,不可見且沒有界面。Service的優先級高於Activity,當系統負載過大時,會優先殺死Activty,但Service很難被系統清除。須要注意的是,Service一樣運行在主線程中,不能直接進行耗時操做,而是須要在服務中新開一個線程,在該線程中作耗時操做。Service主要分爲本地服務和遠程服務。咱們先來學習本地服務。android
Service的啓動方式主要有兩種:Start方式和Bind方式,咱們先來看這兩種方式的特色ide
Start方式:學習
1.服務跟啓動源沒有任何聯繫this
2.沒法獲得服務對象spa
Bind方式:線程
1.經過Ibinder接口實例,返回一個ServiceConnection對象給啓動源code
2.經過ServiceConnection對象的相關方法能夠獲得Service對象對象
咱們這篇博文,先來介紹Start方式啓動服務blog
和啓動Activity很相似,Service也是經過Intent來啓動和中止,具體代碼以下:繼承
switch (view.getId()) { case R.id.start_bt: startintent=new Intent(MainActivity.this,StartService.class); startService(startintent); break; case R.id.stop_bt: stopService(startintent); break; }
啓動,自定義的StartService類繼承於Service類:
public class StartService extends Service { @Override public void onCreate() { Toast.makeText(getApplicationContext(),"start_service",Toast.LENGTH_SHORT).show(); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(getApplicationContext(),"startcommand_service",Toast.LENGTH_SHORT).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Toast.makeText(getApplicationContext(),"stop_service",Toast.LENGTH_SHORT).show(); super.onDestroy(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
須要注意的是,onCreate方法,只會在Service第一次被建立時調用,在Service未被中止以前,屢次StartService只會調用onStartCommand方法。
最後別忘了在Manifest文件中註冊Service:
<service android:name=".StartService"></service>