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页
已阅读5页,还剩25页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Android讲课 第23Service是Android四大组件中与Activity最相似的组件,它们都代表可执行的程序,Service与Activity区别在于运行,它没有用户界面,所以绝不会Android讲课 第23Service是Android四大组件中与Activity最相似的组件,它们都代表可执行的程序,Service与Activity区别在于运行,它没有用户界面,所以绝不会到前台来。一旦Service被启动起来后,它就与Activity一样。完全具有自己的生命周期如果某个程序组件需要在运行时向用户呈现某种界面,或者该程序需要与用户交互,就需要使用Activity,否则应该考虑使用S

2、ervice开发者开发Service步骤与开发Activity的步骤很像,开发Service组件需要先开发一个Service的子类,然后AndroidManifest.xml文件中配置该service,配置时可通过ent-filter./元素指它可被哪ent启动Android系统本身提供了大量的Service组件,开发者可通过这些系统Service来操作Android系统本身Service组件也是可执行的程序,它也有自己的生命周期就像开发Activity需要两个步骤开发Activity定义一个继承Service的子在AndroidManifest.xml文件中配置该()、getContentR

3、esolver()等方法与Activity相似的是,Service中也定义了系列生命周期方法,如下所示abstract IBinderent):该方法是Service子类必须实现的方法。该方法返回一个IBinder对象应用程序可通过该对象与Service组件通信void onCreate():当该Service第一次被创建后将立即回调该方法void onDestroy():当该Service被关闭之前将会回调该方法startId):该方法的时期版本是void startId),每次客户端调用ent)方法启动该Service都会回调该方法ent):当该Service上绑定的所有客户端都断开连接时

4、将会回调该方法Service开发完成之后,接下来就可以在程序中运行这个Service,Android系统中运行Service有如下两种方式通过Cntt的tatc方法;通过该方法启用c,了,c仍然运行。通过Cntt的nc方法:使用该方法启用c,出,c也就终止。者与Service之间没有关联,即者退者一旦创建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必须实现的方publi IBinde ent / TODO Retur th communicatio channe to the thro new UnsupportedOperationException(No ye /Service被创建时回调该方法,只能被调用 次publi void onCreate( Log.i(TAG onCreate()/Service被启动时回调该* /Service被创建时回调该方法,只能被调用 次publi void onCreate( Log.i(TAG onCreate()/Service

8、被启动时回调该* * ent 就是ent)中* param *flags表示启动服务的方式:默认取值是Additiona dat abou this start request Currentl either 0 START FLAG REDELIVERY or START FLAG RETRYSTART FLAG REDELIVERY:如果你实现d()来安排异步工作或者在另 个线程中工作*发送 个*失*那么你可能需要使用START FLAG REDELIVERY来让系统ent这样如果你的服务在处理它的时候被Kill掉ent不会START FLAG RETRY:表示服务之前被设为START S

9、TICKY,则会被传入这个标记* para startI 对这个service请求的activity或其他实体,它是唯 * retur 这个整形可以有四个返回值:START STICKY、START NO STICKY、START 、START STICK COMPATIBILITY。 *START STICKY:“粘性的”。如果service进程被kill掉,保留service的状态为开始状但不保留递送ent对象*随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服后 定会调用*。*)方法如果在此期间没有任何启动命令被传递到service,那么参ent将为这就是平常说粘性

10、服务,返回这个值就是粘性服务*START NOT STICKY:“非粘性的”。使用这个返回值时,如果在执行完d服务被异常kill掉,系统不会自动重启该服*START ENT:重ent。使用这个返回值时,如果在执行完d后,服务被异常kill掉,系统会自动重启该服务*并ent的值传入START STICKY COMPATIBILITY:STAR STICKY的兼容版本,但不保证服务被kill启 startId) Log.i(TAG = ent + flags= + flags + startId= + startI /retur ent flags /返回这个值表示服务是粘return Servi

11、ce.STAR /Service停止时调用该方publi voi onDestroy( Log.i(TAG onDestroy()文件ent-conn:该参数是一个ServiceConnection对象,该对象用者与Service之间的连接情况当者与Service之间连接成功时将回调ServiceConnection对象 当象onServiceDisconnected(ComponentName name)方法该参数可指定0(不自动创建)或BIND AUTO CREATE(自动创建 ent)方法,在绑定本地Service情下,onBind( ent ent)方法所返回的IBinder对象将会传

12、给ServiceConnection对 实际开发时通常会采用继承Binder(IBinder的实现类)的方式实现自己的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=获取当前的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类来实现IBinder接class MyBinder extend Binder /返回count值,这个count值在外部类中定getCount() retur count/定义onBi

17、nder方法所的对publi MyBinder binde = new publi BindService() publi IBinder ent) TA, ent= ent + /返回binder对象,这个对象是通过继承Binder类实现return binderpubli voi onCreate() superTA, onCreate()/启动 条线程动态修改countnew Thread() publi void run() whil quit try catc erruptedException e) /count值增/观察这个方法是否被回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()方法的返回对象,通过这个对象可以实现Act

20、ivity与Servicepublic voi onServiceConnected(ComponentName name, IBinder service) /service是IBinder对象,因要的是BindService.MyBinder,所以强转 下binde = (BindService.MyBinder) * Activity与Service之间异常断开时调用,如果是调用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:该参数通en

22、t指定要启动的 / flags:指定绑定时是否自动创建Service(如果Service还未创建)。 该参数可指定0(不自动创建或BIND AUTO CREATE(自动创建bindServiceent, conn Service.BIND AUTO CREATE)6 .mp3/item/string-string-.mp3/item/string-string-array name=arrayMusicDispNames曾经的你爱情转移今夜二十岁 (Live)/item路灯下的小姑娘时间都去哪儿了/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;/发送个广播,通知Activity进行界面更ent play ent = play com.phone.PlayMusic undle = new Bundle(); info是否下 首?); play ent.putExtras(bundle);/发送广sen

26、dBroadcast(play /当前是停止状isStoped = truprivat voi current ition) mediaPlayer tr /设mediaPlayer+ separato + arrayMusicNames /加mediaPlayerne MediaPlayer.OnPreparedListener() publi voi onPrepared(MediaPlayer mp) /发送广播用于更新Activity界面信/取消循 false catc (IOException e) e.pr StackTrace();/发送广播,用于更新界面信privat vo f

27、alse catc (IOException e) e.pr StackTrace();/发送广播,用于更新界面信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 /发送广 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(确认, new erface.OnClickListener()publi voi /开启服务,传递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)/先停止当前mediaPlayer.stop()/再启动新的preparePlayMusic();publi voi playNextMusic() if(mediaPlayer!

37、=null)/先停止当前mediaPlayer.stop()/再启动新的preparePlayMusic();/play方publi voi playMusic() if (isStoped /开始 preparePlayMusic() isStope = false els if (mediaPlayer != null & !mediaPlayer.isPlaying() /mediaPlayer不为空,同时没有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;/服务对privat BindPlayMusic.MyBinde binder;/Activity与Service通信的对象 privat TextVie tv emptycurren ition = 0;/当的序privat 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 /取得服务对bindPlayMusi = publi voi onServic

42、eDisconnected(ComponentNam name protecte voi onCreate(Bundl e) setContentView(R.layout.activit /初始化/绑定/加载列lo /设定lv的点击事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 = /下面是地址传给 /调功能/把next开放 else case if .equals(play.getText().toString() /下面是取地址musicPat = /下面是地址传给/调功能 else case R.id.nextif itio musicList.size( - 1) /下面是取地址musicPat = musicList.get(curren /下面是地址传给/调功能/把prev给开放出 else case R.id.stopprivat

44、 voi layList( /通过SimpleAdapter进行绑new Thread() public void run() /加载音乐列musicLis = /发通知,更新列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务于 tiitoti的tiitotitiitotir。: enterce将会使用队列来管理请求 ent,每当客端代码通过 ent请求启动 enterce时, enterce会将该 ent加入队列中,然后开启一条新的wk线程来 n 只处理一个 ent。由于 enterce使用新的wk线程处理 ent请求,因此 enterce不会阻塞主线程,所以enterce自己就可以处理耗时任务归纳起

46、来, entService具有如下特征entService会创建单独的worker线程来处理所有的 ententService会创建单独的worker线程来处理onHandle ent()方法实现的代码,因此开发者无须处理多线 从上面介绍可以看出,扩展 entService实现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=点t 4publi class MainActivity ptivity privat MyReceiver rclass MyReceiver extends BroadcastReceiver publi voi onReceive(Context context, /收到广播后的处ent) String info infofina String filePath filePath/创AlertDialog.Builder builder = new class MyReceiver

49、 extends BroadcastReceiver publi voi onReceive(Context context, /收到广播后的处ent) String info infofina String filePath filePath/创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( /显框对protecte 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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论