星期一, 3月 27, 2017

[ Android ] 使用Service (一) startService / stopService




使用service的方法有兩種,
一種是start方式,另一種是bind的方式。
這裡講解start方式如何使用。







































左邊是用start的流程,
先從左邊來說。

從一開始我們先建個servie的class,

public class StartServices extends Service {}

而我在activity裡會去start這個service,

Intent it = new Intent();
it.setClass(MainActivity.this, StartServices.class);
startService(it);
stopService(it);


說明:

onCreate() :
在使用startService()來開始一個service時,
如果這個service目前沒有在運行,
那他就會調用onCreate(),來建造一個service起來,
如果有在運行了,不管你調用幾次startService(),
他都不會再建立service了,
所以onCreate()只會在第一次建立service時被使用。
一些service初始化的動作可以在這裡完成。


onStartCommand() :
使用startService()後,那一定會跑到這裡來,
和onCreate()不一樣的是,
不管你執行幾次startService()他就會跑幾次onStartCommand(),
用於下載東西或者音樂播放用途。


onDestroy() :
如果使用了startService(),那這個service就會無限期的跑下去,
除非使用stopService()來停止,
而stopService()就會調用到onDestroy()來停止這個service。

Note:
onDestroy()是被stopService()所調用的,
那我在service裡要自己殺掉自己這個service呢?

stopSelf();

那就要使用stopSelf()了。
這個function會自己跑到onDestroy()裡面去殺掉自己!!

要記得寫好service後要把service加到AndroidManifest.xml裡面去。

.....
</activity>
<service android:name=".StartServices"></service>
.....



所以簡化一下最上面的圖。




















































SourceCode


Ref 1
Ref 2
Ref 3

沒有留言: