android講課第23天Service是Android四大組件中與Activity最_第1頁
android講課第23天Service是Android四大組件中與Activity最_第2頁
android講課第23天Service是Android四大組件中與Activity最_第3頁
android講課第23天Service是Android四大組件中與Activity最_第4頁
android講課第23天Service是Android四大組件中與Activity最_第5頁
免費(fèi)預(yù)覽已結(jié)束,剩余25頁可下載查看

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、Android講課 第23Service是Android四大組件中與Activity最相似的組件,它們都代表可執(zhí)行的程序,Service與Activity區(qū)別在于運(yùn)行,它沒有用戶界面,所以絕不會Android講課 第23Service是Android四大組件中與Activity最相似的組件,它們都代表可執(zhí)行的程序,Service與Activity區(qū)別在于運(yùn)行,它沒有用戶界面,所以絕不會到前臺來。一旦Service被啟動起來后,它就與Activity一樣。完全具有自己的生命周期如果某個(gè)程序組件需要在運(yùn)行時(shí)向用戶呈現(xiàn)某種界面,或者該程序需要與用戶交互,就需要使用Activity,否則應(yīng)該考慮使用S

2、ervice開發(fā)者開發(fā)Service步驟與開發(fā)Activity的步驟很像,開發(fā)Service組件需要先開發(fā)一個(gè)Service的子類,然后AndroidManifest.xml文件中配置該service,配置時(shí)可通過ent-filter./元素指它可被哪ent啟動Android系統(tǒng)本身提供了大量的Service組件,開發(fā)者可通過這些系統(tǒng)Service來操作Android系統(tǒng)本身Service組件也是可執(zhí)行的程序,它也有自己的生命周期就像開發(fā)Activity需要兩個(gè)步驟開發(fā)Activity定義一個(gè)繼承Service的子在AndroidManifest.xml文件中配置該()、getContentR

3、esolver()等方法與Activity相似的是,Service中也定義了系列生命周期方法,如下所示abstract IBinderent):該方法是Service子類必須實(shí)現(xiàn)的方法。該方法返回一個(gè)IBinder對象應(yīng)用程序可通過該對象與Service組件通信void onCreate():當(dāng)該Service第一次被創(chuàng)建后將立即回調(diào)該方法void onDestroy():當(dāng)該Service被關(guān)閉之前將會回調(diào)該方法startId):該方法的時(shí)期版本是void startId),每次客戶端調(diào)用ent)方法啟動該Service都會回調(diào)該方法ent):當(dāng)該Service上綁定的所有客戶端都斷開連接時(shí)

4、將會回調(diào)該方法Service開發(fā)完成之后,接下來就可以在程序中運(yùn)行這個(gè)Service,Android系統(tǒng)中運(yùn)行Service有如下兩種方式通過Cntt的tatc方法;通過該方法啟用c,了,c仍然運(yùn)行。通過Cntt的nc方法:使用該方法啟用c,出,c也就終止。者與Service之間沒有關(guān)聯(lián),即者退者一旦創(chuàng)建Android 23 1.?xm =1.0 encoding=utf-resou co1.?xm =1.0 encoding=utf-resou colo colo colo /resou resou !- Base applicatio theme -styl name=AppTheme !

5、- Customiz your them here -ite ite ite /resou 3activity RelativeLayou xmlns:android= android:layou width=matc parent android:layou height=matc parent cal android:paddingLeft=dimen/activit horizonta android:paddingRight=dimen/activit horizonta margin android:paddingTop=dimen/activit vertical margin a

6、ndroid:id=+id/bt startandroid:layou width=wra content android:layou height=wra content android:text=啟勸Service / android:id=+id/bt stopandroid:layou width=wra content android:layou height=wra content android:layou below=id/bt start android:text=停止Service /4. publi Servic extend Servic privat fina s i

7、c String TAG = Service( /Service必須實(shí)現(xiàn)的方publi IBinde ent / TODO Retur th communicatio channe to the thro new UnsupportedOperationException(No ye /Service被創(chuàng)建時(shí)回調(diào)該方法,只能被調(diào)用 次publi void onCreate( Log.i(TAG onCreate()/Service被啟動時(shí)回調(diào)該* /Service被創(chuàng)建時(shí)回調(diào)該方法,只能被調(diào)用 次publi void onCreate( Log.i(TAG onCreate()/Service

8、被啟動時(shí)回調(diào)該* * ent 就是ent)中* param *flags表示啟動服務(wù)的方式:默認(rèn)取值是Additiona dat abou this start request Currentl either 0 START FLAG REDELIVERY or START FLAG RETRYSTART FLAG REDELIVERY:如果你實(shí)現(xiàn)d()來安排異步工作或者在另 個(gè)線程中工作*發(fā)送 個(gè)*失*那么你可能需要使用START FLAG REDELIVERY來讓系統(tǒng)ent這樣如果你的服務(wù)在處理它的時(shí)候被Kill掉ent不會START FLAG RETRY:表示服務(wù)之前被設(shè)為START S

9、TICKY,則會被傳入這個(gè)標(biāo)記* para startI 對這個(gè)service請求的activity或其他實(shí)體,它是唯 * retur 這個(gè)整形可以有四個(gè)返回值:START STICKY、START NO STICKY、START 、START STICK COMPATIBILITY。 *START STICKY:“粘性的”。如果service進(jìn)程被kill掉,保留service的狀態(tài)為開始狀但不保留遞送ent對象*隨后系統(tǒng)會嘗試重新創(chuàng)建service,由于服務(wù)狀態(tài)為開始狀態(tài),所以創(chuàng)建服后 定會調(diào)用*。*)方法如果在此期間沒有任何啟動命令被傳遞到service,那么參ent將為這就是平常說粘性

10、服務(wù),返回這個(gè)值就是粘性服務(wù)*START NOT STICKY:“非粘性的”。使用這個(gè)返回值時(shí),如果在執(zhí)行完d服務(wù)被異常kill掉,系統(tǒng)不會自動重啟該服*START ENT:重ent。使用這個(gè)返回值時(shí),如果在執(zhí)行完d后,服務(wù)被異常kill掉,系統(tǒng)會自動重啟該服務(wù)*并ent的值傳入START STICKY COMPATIBILITY:STAR STICKY的兼容版本,但不保證服務(wù)被kill啟 startId) Log.i(TAG = ent + flags= + flags + startId= + startI /retur ent flags /返回這個(gè)值表示服務(wù)是粘return Servi

11、ce.STAR /Service停止時(shí)調(diào)用該方publi voi onDestroy( Log.i(TAG onDestroy()文件ent-conn:該參數(shù)是一個(gè)ServiceConnection對象,該對象用者與Service之間的連接情況當(dāng)者與Service之間連接成功時(shí)將回調(diào)ServiceConnection對象 當(dāng)象onServiceDisconnected(ComponentName name)方法該參數(shù)可指定0(不自動創(chuàng)建)或BIND AUTO CREATE(自動創(chuàng)建 ent)方法,在綁定本地Service情下,onBind( ent ent)方法所返回的IBinder對象將會傳

12、給ServiceConnection對 實(shí)際開發(fā)時(shí)通常會采用繼承Binder(IBinder的實(shí)現(xiàn)類)的方式實(shí)現(xiàn)自己的IBinder對象者就可通過1.?xm =1.0 encoding=utf-1.?xm =1.0 encoding=utf-name=colorPrimary#3F51B5#303F9F#FF4081!- Base application theme -styl name=AppTheme parent=Base.Theme.AppCo!- Customiz your them here -arkActionBarcolor/colorPrimarycolor/colorPri

13、maryDarkcolor/colorAccent3activityRelativeLayou xmlns:android= xmlns:tools=android:layou android:layouwidth=matcheight=match android:paddingBottom=dimcal android:paddingLeft=dimen/activity horizonta marginandroid:paddingRight=dimen/activity horizonta marginandroid:paddingTop=dimen/activity vertical

14、margintools:conteivityTextVieandroid:id=+id/tvandroid:layout width=wrap contentandroid:layout height=wrap contentandroid:text=stringo android:textColor=color/colorAccent android:textSize=30sp android:textStyle=bold /Buttoandroid:id=+id/btn android:layou android:layou android:layouwidth=wrap contenth

15、eight=wrap contentbelow=id/tvandroid:text=連接Service Buttoandroid:id=+id/btn android:layou android:layou android:layouwidth=wrap contentheight=wrap contentbelow=id/btn connandroid:text=獲取當(dāng)前的Count Buttoandroid:id=+id/btn android:layou android:layou android:layouwidth=wrap candroid:id=+id/btn android:l

16、ayou android:layou android:layouwidth=wrap contentheight=wrap contentbelow=id/btn android:text=斷開Service t4publi class BindService extend Servic fina ic String TAG = BindServicecount=0qui = true;/通過繼承Binder類來實(shí)現(xiàn)IBinder接class MyBinder extend Binder /返回count值,這個(gè)count值在外部類中定getCount() retur count/定義onBi

17、nder方法所的對publi MyBinder binde = new publi BindService() publi IBinder ent) TA, ent= ent + /返回binder對象,這個(gè)對象是通過繼承Binder類實(shí)現(xiàn)return binderpubli voi onCreate() superTA, onCreate()/啟動 條線程動態(tài)修改countnew Thread() publi void run() whil quit try catc erruptedException e) /count值增/觀察這個(gè)方法是否被回startId) TA, return en

18、t,flags, ent) ent= TA, ent + return true;publi voi onDestroy() thisqui ;TA, onDestroy()super/不要刪除5servicandroid:name=.BindService android:TA, onDestroy()super/不要刪除5servicandroid:name=.BindService android:enabled=true android:exported=trueent-filteraction android:name=com.phone.BindService ent-filter

19、4 MainActivitypubli class MainActivity ptivity privat TextView tprivat bt conn, btn disconn, bt countprivateBindService.MyBinder privat ServiceConnection conn = new ServiceConnection) * Activity與Service*name The concrete component name of the s been connected. 是ervice對象中onBind()方法的返回對象,通過這個(gè)對象可以實(shí)現(xiàn)Act

20、ivity與Servicepublic voi onServiceConnected(ComponentName name, IBinder service) /service是IBinder對象,因要的是BindService.MyBinder,所以強(qiáng)轉(zhuǎn) 下binde = (BindService.MyBinder) * Activity與Service之間異常斷開時(shí)調(diào)用,如果是調(diào)用unBindService()法* para name public voi onServiceDisconnected(ComponentName name) protecte voi onCreate(Bun

21、dle e) superactivit main conn = (Button) bt conndiscon = (Button) bt ncount = (Button) findViewById(R.id.btn countfinaent = com.phone.BindService .androi 23 02 bindservicebt conn.setOnClickListener(new View.OnClickListener() public void onClick(View v) ent service, ServiceConnection / service:該參數(shù)通en

22、t指定要啟動的 / flags:指定綁定時(shí)是否自動創(chuàng)建Service(如果Service還未創(chuàng)建)。 該參數(shù)可指定0(不自動創(chuàng)建或BIND AUTO CREATE(自動創(chuàng)建bindServiceent, conn Service.BIND AUTO CREATE)6 .mp3/item/string-string-.mp3/item/string-string-array name=arrayMusicDispNames曾經(jīng)的你愛情轉(zhuǎn)移今夜二十歲 (Live)/item路燈下的小姑娘時(shí)間都去哪兒了/string-string-array name=arrayMusicArtists王錚亮4.a

23、ctivity android:id=+id/tv android:layou android:layou android:layouwidth=wrap contentheight=wrap contentbelow=id/tv dispNameandroid:text=歌手. android:textColor=color/colorAccent android:textSize=20sp /LinearLayouandroid:layou android:layou android:layoutch height=wrap contentbelow=id/tv artistImageBu

24、ttoandroid:id=+id/play android:layout width=wrap contentandroid:layout height=wrap contentandroid:onClick=btnClick android:src=mipmap/play /ImageButtoandroid:id=+id/pause android:layout width=wrap contentandroid:layout height=wrap contentandroid:onClick=btnClick android:src=mipmap/pause /ImageButtoa

25、ndroid:id=+id/stop android:layout width=wrap contentandroid:layout height=wrap contentandroid:onClick=btnClick android:src=mipmap/stop /= arrayMusicNameslength itio = 0;/發(fā)送個(gè)廣播,通知Activity進(jìn)行界面更ent play ent = play com.phone.PlayMusic undle = new Bundle(); info是否下 首?); play ent.putExtras(bundle);/發(fā)送廣sen

26、dBroadcast(play /當(dāng)前是停止?fàn)頸sStoped = truprivat voi current ition) mediaPlayer tr /設(shè)mediaPlayer+ separato + arrayMusicNames /加mediaPlayerne MediaPlayer.OnPreparedListener() publi voi onPrepared(MediaPlayer mp) /發(fā)送廣播用于更新Activity界面信/取消循 false catc (IOException e) e.pr StackTrace();/發(fā)送廣播,用于更新界面信privat vo f

27、alse catc (IOException e) e.pr StackTrace();/發(fā)送廣播,用于更新界面信privat voi sendSongInfoBroad() ent play ent = new ent();play com.phone.PlayMusic.Info Bund undle = new Bundle();dispName arrayMusicDispNamescurren ition bundle.putString(artist, arrayMusicArtistscurren ition);play /發(fā)送廣 mand( ent startId) switc

28、 ( ent.getExtras().get (s e) case 1:if isStoped isStope = e else itioif mediaPlaye != nul & mediaPlayer mediaPlayerkcase if mediaPlaye != null & mediaPlayer kcase if mediaPlaye != null) mediaPlayer isStope = truekreturn START STICKpubli voi onDestroy() superif mediaPlaye!= null mediaPlayer mediaPlay

29、e = nullpubli class MainActivity p tivity privat MyReceiver myReceive = privat DisplaySongInfoReceiver songInfoReceive = privat TextView ame tv /用于更新界面信privat class DisplaySongInfoReceiver extend BroadcastReceiver publi voi onReceive(Context /顯示下 首曲ent) tv dispNametv artistdispName privat class MyRe

30、ceiver extend BroadcastReceiver publi voi onReceive(final Context context, fina publi voi onReceive(Context /顯示下 首曲ent) tv dispNametv artistdispName privat class MyReceiver extend BroadcastReceiver publi voi onReceive(final Context context, fina MyReceiver 我收到了廣播通知!);ent) fina AlertDialog.Builder bu

31、ilder = new AlertDialog.Builder(context); builder.setIcon(R.mipmap.ic launcherbuilder.setTitle(提示infobuilder.setNegativeButton(取消, nullitiveButton(確認(rèn), new erface.OnClickListener()publi voi /開啟服務(wù),傳遞erface which) e為ent ent = ent(context, undle = new e, /顯框protecte voi onCreate(Bundle e) tivit maitv di

32、spNam = (TextView) findViewById(R.id.tv dispNametv artist = (TextView) findViewById(R.id.tv artist);myReceive = new songInfoReceiver = new /動廣rprivat voi registerReceiver) /下 首是確框/更新界面信息廣播接收, com.phone.PlayMusicsongInfoReceiver com.phone.PlayMusic.Infopubli voi btnClick(View view) ent = this classun

33、dle = new switc (view.getId() case pla:breakcase R.id.pausee, breakcase stoe, breake, protecte voi onDestroy() this.duratio = duration this.siz = size;publi Strin getName( rethis.duratio = duration this.siz = size;publi Strin getName( retur namepubli voi setName(Strin name this.nam = namepubli Strin

34、 getAlbum( retur albumpubli voi setAlbum(Strin album this.albu = albumpubli Strin getArtist( return artistpubli void setArtist(Strin artist) this.artis = artist;publi Strin getPath( return pathpubli voi setPath(Strin path this.pat = pathgetDuration( return publi voi setDurationduration this.duratio

35、= durationgetSize( return publi void setSize(size this.siz = size;publi class MusicUtil publi s ic ListMusicBean getMusicList(Contex context) ListMusicBean list = new ArrayList() ContentResolve resolve = context.getContentResolver()Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNA CONTEN

36、T URI null nul, null, null)/迭代cursorwhil (cursor.moveToNext() Strin nam = Strin albu = ist = h = duratio = et StackTrace()publi voi playPrevMusic() if(StackTrace()publi voi playPrevMusic() if(mediaPlayer!=null)/先停止當(dāng)前mediaPlayer.stop()/再啟動新的preparePlayMusic();publi voi playNextMusic() if(mediaPlayer!

37、=null)/先停止當(dāng)前mediaPlayer.stop()/再啟動新的preparePlayMusic();/play方publi voi playMusic() if (isStoped /開始 preparePlayMusic() isStope = false els if (mediaPlayer != null & !mediaPlayer.isPlaying() /mediaPlayer不為空,同時(shí)沒有mediaPlayer.start()中/暫voi pauseMusic() (mediaPlayer != nul & mediaPlayer.isPlaying() media

38、Player.pause()/停voi stopMusic() (mediaPlayer != null mediaPlayer.stop() isStope = trueent) if (mediaPlayer != null mediaPlayer.release() mediaPlayer = nullreturn super.onUnbindpubli voi onDestroy() super.onDestroy()if (mediaPlayer != null mediaPlayer.release() mediaPlayer = nullpubli class MainActiv

39、it extend tivit privat Buttpubli class MainActivit extend tivit privat Butto prev play next stop; privat ListVie lv;privat ListMusicBean privat BindPlayMusi bindPlayMusic;/服務(wù)對privat BindPlayMusic.MyBinde binder;/Activity與Service通信的對象 privat TextVie tv emptycurren ition = 0;/當(dāng)?shù)男騪rivat Handle handle =

40、 new Handler( /更新publi voi handleMessage(Messag msg if (msg.wha = 0 x200) ListMap list = new ArrayListMap() for (MusicBea mb : musicList MapString String map = new HashMap() map.put(name mb.getName()map.put(album map.put(artist mb.getArtist() map.put(duration mb.getDuration( + ); SimpleAdapte adapte

41、 = new SimpleAdapter(MainActivity.this R.layout.son new Stringname album artist, R. R.id.album R.id.artist lv.setEmptyView(t privat ServiceConnectio conn = new ServiceConnection( publi voi ected(ComponentNam name IBinde service) binde = (BindPlayMusic.MyBinder /取得服務(wù)對bindPlayMusi = publi voi onServic

42、eDisconnected(ComponentNam name protecte voi onCreate(Bundl e) setContentView(R.layout.activit /初始化/綁定/加載列l(wèi)o /設(shè)定lv的點(diǎn)擊事lv.setOnItemClickListener(ne AdapterView.OnItemClickListener( public void onItemClick(AdapterView 0) Strin /幾按鈕控publi voi playControl(Vie view if (musicList.size( 0) Strin musicPath

43、switc (view.getId() case R.id.previf itio = 1) /下面是取地址musicPat = /下面是地址傳給 /調(diào)功能/把next開放 else case if .equals(play.getText().toString() /下面是取地址musicPat = /下面是地址傳給/調(diào)功能 else case R.id.nextif itio musicList.size( - 1) /下面是取地址musicPat = musicList.get(curren /下面是地址傳給/調(diào)功能/把prev給開放出 else case R.id.stopprivat

44、 voi layList( /通過SimpleAdapter進(jìn)行綁new Thread() public void run() /加載音樂列musicLis = /發(fā)通知,更新列privat voi Biprivat voi BindServie( en ent = ent(this ent conn BIN AUTO privat void initView( prev = (Button findViewById(R.id.prev) pla = (Button findViewById(R.id.play) next = (Button findViewById(R.id.next) s

45、to = (Button tv empt = (TextView findViewById(R.id.t empty) lv = (ListView findViewById(R.id.lv) :ii會惑 tiit務(wù)于 tiitoti的tiitotitiitotir。: enterce將會使用隊(duì)列來管理請求 ent,每當(dāng)客端代碼通過 ent請求啟動 enterce時(shí), enterce會將該 ent加入隊(duì)列中,然后開啟一條新的wk線程來 n 只處理一個(gè) ent。由于 enterce使用新的wk線程處理 ent請求,因此 enterce不會阻塞主線程,所以enterce自己就可以處理耗時(shí)任務(wù)歸納起

46、來, entService具有如下特征entService會創(chuàng)建單獨(dú)的worker線程來處理所有的 ententService會創(chuàng)建單獨(dú)的worker線程來處理onHandle ent()方法實(shí)現(xiàn)的代碼,因此開發(fā)者無須處理多線 從上面介紹可以看出,擴(kuò)展 entService實(shí)現(xiàn)Service無須重寫onBind uses-uses-uses-uses-uses-uses-.ERNET .WRIT EXTERNAL STORAGE .REA EXTERNAL STORAGE 1.colo colo !- Base applicatio theme -styl name=AppTheme !- C

47、ustomiz your them here -ite ite 3activity RelativeLayou xmlns:android= android:layou width=matc parent android:layou height=matc parent cal android:paddingLeft=dimen/activit horizonta android:paddingRight=dimen/activit horizonta android:paddingTop=dimen/activit vertical Buttoandroid:layou width=wra

48、content android:layou height=wra content android:text=點(diǎn)t 4publi class MainActivity ptivity privat MyReceiver rclass MyReceiver extends BroadcastReceiver publi voi onReceive(Context context, /收到廣播后的處ent) String info infofina String filePath filePath/創(chuàng)AlertDialog.Builder builder = new class MyReceiver

49、 extends BroadcastReceiver publi voi onReceive(Context context, /收到廣播后的處ent) String info infofina String filePath filePath/創(chuàng)AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.mipmap.ic launcher提builder.setNegativeButton(取消, lbuilder.set itiveButton(確定, new Dialog erfac

50、e.OnClickListener() publi voi onClick(Dialog erface which) ent play ent = ent.setAction( ent.ACTION VIEnew File(filePath), /開startActivity( /顯框?qū)rotecte voi onCreate(Bundle e) superactivit maimyReceive = new /, com.phonepubli voi btnClick(View view) ent = newthisstartService( protecte voi onDestroy() s

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論