ImageVerifierCode 换一换
格式:DOC , 页数:13 ,大小:75KB ,
资源ID:8986887      下载积分:10 金币
快捷注册下载
登录下载
邮箱/手机:
温馨提示:
快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。 如填写123,账号就是123,密码也是123。
特别说明:
请自助下载,系统不会自动发送文件的哦; 如果您已付费,想二次下载,请登录后访问:我的下载记录
支付方式: 支付宝    微信支付   
验证码:   换一换

开通VIP
 

温馨提示:由于个人手机设置不同,如果发现不能下载,请复制以下地址【https://www.zixin.com.cn/docdown/8986887.html】到电脑端继续下载(重复下载【60天内】不扣币)。

已注册用户请登录:
账号:
密码:
验证码:   换一换
  忘记密码?
三方登录: 微信登录   QQ登录  

开通VIP折扣优惠下载文档

            查看会员权益                  [ 下载后找不到文档?]

填表反馈(24小时):  下载求助     关注领币    退款申请

开具发票请登录PC端进行申请

   平台协调中心        【在线客服】        免费申请共赢上传

权利声明

1、咨信平台为文档C2C交易模式,即用户上传的文档直接被用户下载,收益归上传人(含作者)所有;本站仅是提供信息存储空间和展示预览,仅对用户上传内容的表现方式做保护处理,对上载内容不做任何修改或编辑。所展示的作品文档包括内容和图片全部来源于网络用户和作者上传投稿,我们不确定上传用户享有完全著作权,根据《信息网络传播权保护条例》,如果侵犯了您的版权、权益或隐私,请联系我们,核实后会尽快下架及时删除,并可随时和客服了解处理情况,尊重保护知识产权我们共同努力。
2、文档的总页数、文档格式和文档大小以系统显示为准(内容中显示的页数不一定正确),网站客服只以系统显示的页数、文件格式、文档大小作为仲裁依据,个别因单元格分列造成显示页码不一将协商解决,平台无法对文档的真实性、完整性、权威性、准确性、专业性及其观点立场做任何保证或承诺,下载前须认真查看,确认无误后再购买,务必慎重购买;若有违法违纪将进行移交司法处理,若涉侵权平台将进行基本处罚并下架。
3、本站所有内容均由用户上传,付费前请自行鉴别,如您付费,意味着您已接受本站规则且自行承担风险,本站不进行额外附加服务,虚拟产品一经售出概不退款(未进行购买下载可退充值款),文档一经付费(服务费)、不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
4、如你看到网页展示的文档有www.zixin.com.cn水印,是因预览和防盗链等技术需要对页面进行转换压缩成图而已,我们并不对上传的文档进行任何编辑或修改,文档下载后都不会有水印标识(原文档上传前个别存留的除外),下载后原文更清晰;试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓;PPT和DOC文档可被视为“模板”,允许上传人保留章节、目录结构的情况下删减部份的内容;PDF文档不管是原文档转换或图片扫描而得,本站不作要求视为允许,下载前可先查看【教您几个在下载文档中可以更好的避免被坑】。
5、本文档所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用;网站提供的党政主题相关内容(国旗、国徽、党徽--等)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
6、文档遇到问题,请及时联系平台进行协调解决,联系【微信客服】、【QQ客服】,若有其他问题请点击或扫码反馈【服务填表】;文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“【版权申诉】”,意见反馈和侵权处理邮箱:1219186828@qq.com;也可以拔打客服电话:0574-28810668;投诉电话:18658249818。

注意事项

本文(android-service详解(实用).doc)为本站上传会员【pc****0】主动上传,咨信网仅是提供信息存储空间和展示预览,仅对用户上传内容的表现方式做保护处理,对上载内容不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知咨信网(发送邮件至1219186828@qq.com、拔打电话4009-655-100或【 微信客服】、【 QQ客服】),核实后会尽快下架及时删除,并可随时和客服了解处理情况,尊重保护知识产权我们共同努力。
温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载【60天内】不扣币。 服务填表

android-service详解(实用).doc

1、Android开发四大组件---Service详解   service可以在和多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息位置的改变等等,总之服务嘛,总是藏在后头的。   Service是在一段不定的时间运行在后台,不和用户交互应用组件。每个Service必须在manifest中 通过来声明。可以通过contect.startservice和contect.bindserverice来启动。   Service和其他的应用组件一样,运行在进程的主线程中。这就

2、是说如果service需要很多耗时或者阻塞的操作,需要在其子线程中实现。   service的两种模式(startService()/bindService()不是完全分离的):   本地服务 Local Service 用于应用程序内部。   它可以启动并运行,直至有人停止了它或它自己停止。在这种方式下,它以调用Context.startService()启动,而以调用Context.stopService()结束。它可以调用Service.stopSelf() 或 Service.stopSelfResult()来自己停止。不论调用了多少次startService()方法,你只需要调

3、用一次stopService()来停止服务。   用于实现应用程序自己的一些耗时任务,比如查询升级信息,并不占用应用程序比如Activity所属线程,而是单开线程后台执行,这样用户体验比较好。   远程服务 Remote Service 用于android系统内部的应用程序之间。   它可以通过自己定义并暴露出来的接口进行程序操作。客户端建立一个到服务对象的连接,并通过那个连接来调用服务。连接以调用Context.bindService()方法建立,以调用 Context.unbindService()关闭。多个客户端可以绑定至同一个服务。如果服务此时还没有加载,bindService(

4、)会先加载它。   可被其他应用程序复用,比如天气预报服务,其他应用程序不需要再写这样的服务,调用已有的即可。   生命周期   使用context.startService() 启动Service是会会经历:   context.startService() ->onCreate()- >onStart()->Service running   context.stopService() | ->onDestroy() ->Service stop   如果Service还没有运行,则android先调用onCreate()然后调用onStart();如果Service已经运行,

5、则只调用onStart(),所以一个Service的onStart方法可能会重复调用多次。   stopService的时候直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行。该Service的调用者再启动起来后可以通过stopService关闭Service。   所以调用startService的生命周期为:onCreate --> onStart(可多次调用) --> onDestroy   使用使用context.bindService()启动Service会经历:   context.bindService()

6、>onCreate()->onBind()->Service running   onUnbind() -> onDestroy() ->Service stop   onBind将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,Srevice就会调用onUnbind->onDestroy相应退出。   所以调用bindService的生命周期为:onCreate --> onBind(只一次,不可多次绑定) -

7、> onUnbind --> onDestory。   在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。   而启动service,根据onStartCommand的返回值不同,有两个附加的模式:   1. START_STICKY 用于显示启动和停止service。   2. START_NOT_STICKY或START_REDELIVER_INTENT用于有命令需要处理时才运行的模式。   服务不能自己运行,需要

8、通过调用Context.startService()或Context.bindService()方法启动服务。这两个方法都可以启动Service,但是它们的使用场合有所不同。   1. 使用startService()方法启用服务,调用者与服务之间没有关连,即使调用者退出了,服务仍然运行。   如果打算采用Context.startService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。   如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导

9、致多次调用onStart()方法。   采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。   2. 使用bindService()方法启用服务,调用者与服务绑定在了一起,调用者一旦退出,服务也就终止,大有“不求同时生,必须同时死”的特点。   onBind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,多次调用Context.bindService()方法并不会导致该方法被多次调用。  

10、 采用Context.bindService()方法启动服务时只能调用onUnbind()方法解除调用者与服务解除,服务结束时会调用onDestroy()方法。   看看官方给出的比较流程示意图:   官方文档告诉我们,一个service可以同时start并且bind,在这样的情况,系统会一直保持service的运行状态如果service已经start了或者BIND_AUTO_CREATE标志被设置。如果没有一个条件满足,那么系统将会调用onDestory方法来终止service.所有的清理工作(终止线程,反注册接收器)都在onDestory中完成。   拥有service的进程具有较高

11、的优先级   官方文档告诉我们,Android系统会尽量保持拥有service的进程运行,只要在该service已经被启动(start)或者客户端连接(bindService)到它。当内存不足时,需要保持,拥有service的进程具有较高的优先级。   1. 如果service正在调用onCreate,onStartCommand或者onDestory方法,那么用于当前service的进程则变为前台进程以避免被killed。   2. 如果当前service已经被启动(start),拥有它的进程则比那些用户可见的进程优先级低一些,但是比那些不可见的进程更重要,这就意味着service一般

12、不会被killed.   3. 如果客户端已经连接到service (bindService),那么拥有Service的进程则拥有最高的优先级,可以认为service是可见的。   4. 如果service可以使用startForeground(int, Notification)方法来将service设置为前台状态,那么系统就认为是对用户可见的,并不会在内存不足时killed。   如果有其他的应用组件作为Service,Activity等运行在相同的进程中,那么将会增加该进程的重要性。   本地service   1.不需和Activity交互的本地服务   public cl

13、ass LocalService extends Service {   private static final String TAG = "LocalService";   @Override   public IBinder onBind(Intent intent) {   Log.i(TAG, "onBind");   return null;   }   @Override   public void onCreate() {   Log.i(TAG, "onCreate");   super.onCreate();   }   @Override   p

14、ublic void onDestroy() {   Log.i(TAG, "onDestroy");   super.onDestroy();   }   @Override   public void onStart(Intent intent, int startId) {   Log.i(TAG, "onStart");   super.onStart(intent, startId);   }   }   Activity:   public class ServiceActivity extends Activity {   @Override   pro

15、tected void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.servicedemo);   ((Button) findViewById(R.id.startLocalService)).setOnClickListener(   new View.OnClickListener(){   @Override   public void onClick(View view) {   // TODO Auto-gen

16、erated method stub   startService(new Intent("com.demo.SERVICE_DEMO"));   }   });   ((Button) findViewById(R.id.stopLocalService)).setOnClickListener(   new View.OnClickListener(){   @Override   public void onClick(View view) {   // TODO Auto-generated method stub   stopService(new Intent("

17、com.demo.SERVICE_DEMO"));   }   });   }   }   在AndroidManifest.xml添加:                     否则启动服务时会提示new

18、 Intent找不到"com.demo.SERVICE_DEMO"。   对于这类不需和Activity交互的本地服务,是使用startService/stopService的最好例子。   运行时可以发现第一次startService时,会调用onCreate和onStart,在没有stopService前,无论点击多少次startService,都只会调用onStart。而stopService时调用onDestroy。再次点击stopService,会发现不会进入service的生命周期的,即不会再调用onCreate,onStart和onDestroy。   而onBind在st

19、artService/stopService中没有调用。   2.本地服务和Activity交互   对于这种case,官方的sample(APIDemo\app.LocalService)是最好的例子:   /**   * This is an example of implementing an application service that runs locally   * in the same process as the application. The {@link LocalServiceController}   * and {@link LocalServic

20、eBinding} classes show how to interact with the   * service.   *   *

Notice the use of the {@link NotificationManager} when interesting things   * happen in the service. This is generally how background services should   * interact with the user, rather than doing something more disruptive s

21、uch as   * calling startActivity().   */   public class LocalService extends Service {   private NotificationManager mNM;   /**   * Class for clients to access. Because we know this service always   * runs in the same process as its clients, we don't need to deal with   * IPC.   */   publi

22、c class LocalBinder extends Binder {   LocalService getService() {   return LocalService.this;   }   }   @Override   public void onCreate() {   mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);   // Display a notification about us starting. We put an icon in the status bar.

23、   showNotification();   }   @Override   public int onStartCommand(Intent intent, int flags, int startId) {   Log.i("LocalService", "Received start id " + startId + ": " + intent);   // We want this service to continue running until it is explicitly   // stopped, so return sticky.   return ST

24、ART_STICKY;   }   @Override   public void onDestroy() {   // Cancel the persistent notification.   mNM.cancel(R.string.local_service_started);   // Tell the user we stopped.   Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();   }   @Override   public IBinder

25、onBind(Intent intent) {   return mBinder;   }   // This is the object that receives interactions from clients. See   // RemoteService for a more complete example.   private final IBinder mBinder = new LocalBinder();   /**   * Show a notification while this service is running.   */   private

26、 void showNotification() {   // In this sample, we'll use the same text for the ticker and the expanded notification   CharSequence text = getText(R.string.local_service_started);   // Set the icon, scrolling text and timestamp   Notification notification = new Notification(R.drawable.stat_sampl

27、e, text,   System.currentTimeMillis());   // The PendingIntent to launch our activity if the user selects this notification   PendingIntent contentIntent = PendingIntent.getActivity(this, 0,   new Intent(this, LocalServiceController.class), 0);   // Set the info for the views that show in the n

28、otification panel.   notification.setLatestEventInfo(this, getText(R.string.local_service_label),   text, contentIntent);   // Send the notification.   // We use a layout id because it is a unique number. We use it later to cancel.   mNM.notify(R.string.local_service_started, notification);   

29、}   }   这里可以发现onBind需要返回一个IBinder对象。也就是说和上一例子LocalService不同的是,   1. 添加了一个public内部类继承Binder,并添加getService方法来返回当前的Service对象;   2. 新建一个IBinder对象--new那个Binder内部类;   3. onBind方法返还那个IBinder对象。   Activity:   /**   *

Example of binding and unbinding to the {@link LocalService}.   * This demonstr

30、ates the implementation of a service which the client will   * bind to, receiving an object through which it can communicate with the service.

  */   public class LocalServiceBinding extends Activity {   private boolean mIsBound;   private LocalService mBoundService;   @Override   protect

31、ed void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.local_service_binding);   // Watch for button clicks.   Button button = (Button)findViewById(R.id.bind);   button.setOnClickListener(mBindListener);   button = (Button)findViewById(R.i

32、d.unbind);   button.setOnClickListener(mUnbindListener);   }   private ServiceConnection mConnection = new ServiceConnection() {   public void onServiceConnected(ComponentName className, IBinder service) {   // This is called when the connection with the service has been   // established, givi

33、ng us the service object we can use to   // interact with the service. Because we have bound to a explicit   // service that we know is running in our own process, we can   // cast its IBinder to a concrete class and directly access it.   mBoundService = ((LocalService.LocalBinder)service).getSe

34、rvice();   // Tell the user about this for our demo.   Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,   Toast.LENGTH_SHORT).show();   }   public void onServiceDisconnected(ComponentName className) {   // This is called when the connection with the service has been

35、  // unexpectedly disconnected -- that is, its process crashed.   // Because it is running in our same process, we should never   // see this happen.   mBoundService = null;   Toast.makeText(LocalServiceBinding.this, R.string.local_service_disconnected,   Toast.LENGTH_SHORT).show();   }   };

36、   private OnClickListener mBindListener = new OnClickListener() {   public void onClick(View v) {   // Establish a connection with the service. We use an explicit   // class name because we want a specific service implementation that   // we know will be running in our own process (and thus won

37、't be   // supporting component replacement by other applications).   bindService(new Intent(LocalServiceBinding.this,   LocalService.class), mConnection, Context.BIND_AUTO_CREATE);   mIsBound = true;   }   };   private OnClickListener mUnbindListener = new OnClickListener() {   public void

38、onClick(View v) {   if (mIsBound) {   // Detach our existing connection.   unbindService(mConnection);   mIsBound = false;   }   }   };   }   明显看出这里面添加了一个名为ServiceConnection类,并实现了onServiceConnected(从IBinder获取Service对象)和onServiceDisconnected(set Service to null)。   而bindService和unbindServic

39、e方法都是操作这个ServiceConnection对象的。   AndroidManifest.xml里添加:      这里没什么特别的,因为service没有需要什么特别的action,所以只是声明service而已,而activity和普通的没差别。   运行时,发现调用次序是这样的:   bindService:   1.LocalService : onCreate   2.LocalService : onBind   3.Activity: onServiceConnected   unbindService: 只是调用onDestroy   可见,onStart是不会被调用的,而onServiceDisconnected没有调用的原因在上面代码的注释有说明。

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2026 宁波自信网络信息技术有限公司  版权所有

客服电话:0574-28810668  投诉电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服