Android 服務的基本用法

2021-09-25 07:39:28 字數 2815 閱讀 5834

在專案中定義乙個服務,新建乙個service專案 new - service - service。

生成**如下:myservice繼承自service類,onbind方法也別醒目,這個方法是service中唯一乙個抽象方法,所以必須要在子類中實現

public

class

myservice

extends

service

@override

public ibinder onbind

(intent intent)

}

其中還可重寫三個方法:

oncreate()方法是服務建立的時候呼叫,乙個服務建立結束後只呼叫一次該方法。

onstartcommand()方法會在每次服務啟動的時候呼叫,如果我們希望服務一旦啟動就立刻去執行某個動作,就可以將邏輯寫在其中。

ondestory()會在服務銷毀的時候呼叫,在其中**那些不再使用的資源。

@override

public

void

oncreate()

@override

public

intonstartcommand

(intent intent,

int flags,

int startid)

@override

public

void

ondestroy()

服務的啟動停止方法主要借助intent來實現

intent startintent =

newintent

(this

,myservice.

class);

startservice

(startintent)

;//啟動服務

intent stop =

newintent

(this

, myservice.

class);

stopservice

(stop)

;//停止服務

下面將利用服務實現乙個計數器的功能,並且程式退出到後台時仍然在計數

在onstartcommand()中新增**:

//myservice內的私有變數

private

boolean iswork =

true

;private

static

int time =

0;

new

thread

(new

runnable()

catch

(interruptedexception e)

intent intent =

newintent((

), mainactivity.

class);

pendingintent pi = pendingintent.

getactivity((

),0, intent,0)

;final notification notification =

newnotificationcompat.builder((

)).setcontenttitle

("標題").

setcontenttext

(time+"")

.setwhen

(system.

currenttimemillis()

).setsmallicon

(r.mipmap.ic_launcher)

.setlargeicon

(bitmapfactory.

decoderesource

(getresources()

, r.mipmap.ic_launcher)).

setcontentintent

(pi)

.build()

;startforeground(1

, notification)

; time++

; log.d(

"tag"

,"run: "

+ time);}

time=0;

}}).

start()

;

在ondestroy()方法中新增**

iswork =

false

;

停止執行緒的進行

在主方法中新增**:

button start =

findviewbyid

(r.id.start)

;button stop =

findviewbyid

(r.id.stop)

;//開啟服務

start.

setonclicklistener

(new

view.onclicklistener()

});//停止服務

stop.

setonclicklistener

(new

view.onclicklistener()});

Android 服務的基本用法

定義服務之後,我們會發現這個服務類是繼承於service類的,需要重寫service類中的一些方法,最常用的3個方法 oncreate 服務建立時呼叫 onstartcommand 服務啟動時呼叫 和ondestroy 服務銷毀時呼叫 這裡我們用按鈕來啟動和停止服務 核心 如下 case r.id....

Android基本用法

1 需改導航欄標題的背景 setcontentview r.layout.activity schoolnotice content final actionbar actionbar getactionbar actionbar.setdisplayhomeasupenabled true 給左上...

服務的基本用法

定義乙個服務 public class myservice extends service override public void oncreate override public int onstartcommand intent intent,int flags,int startid ove...