细说android service
来源:互联网 发布:剑三成男脸型数据下载 编辑:程序博客网 时间:2024/06/05 07:01
基础内容
Service是在一段不定的时间运行在后台,不和用户交互应用组件。也就是说你不可能像activity一样可以目测的,但它确确实实存活在android系统中的。和其他组件一样,service是运行在主线程中的,也就是说当你需要耗时很多的操作或者阻塞操作时,你需要在其子线程中进行。
按类型分两种模式
1、本地服务 Local Service
用于应用程序内部,以调用Context.startService()启动,而以调用Context.stopService()结束。它可以调用Service.stopSelf() 或Service.stopSelfResult()来自己停止。不论调用了多少次startService()方法,你只需要调用一次stopService()来停止服务。用于实现应用程序自己的一些耗时任务,比如查询升级信息,并不占用应用程序比如Activity所属线程,而是单开线程后台执行,这样用户体验比较好。
2、远程服务 Remote Service
用于android系统内部的应用程序之间。它可以通过自己定义并暴露出来的接口进行程序操作。客户端建立一个到服务对象的连接,并通过那个连接来调用服务。连接以调用Context.bindService()方法建立,以调用 Context.unbindService()关闭。多个客户端可以绑定至同一个服务。如果服务此时还没有加载,bindService()会先加载它。可被其他应用程序复用,比如天气预报服务,其他应用程序不需要再写这样的服务,调用已有的即可。
生命周期
Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当我们第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法。
1. 使用startService()方法启用服务,调用者与服务之间没有关连,即使调用者退出了,服务仍然运行。
如果打算采用Context.startService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。
如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。
采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。
onBind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,多次 调 用Context.bindService()方法并不会导致该方法被多次调用。采用Context.bindService()方法启动服务时只能调用onUnbind()方法解除调用者 与服 务解除,服务结束时会调用onDestroy()方法。
一个service可以同时start并且bind,在这样的情况,系统会一直保持service的运行状态如果service已经start了或者BIND_AUTO_CREATE标志被设置。如果没有一个条件满足,那么系统将会调用onDestory方法来终止service.所有的清理工作(终止线程,反注册接收器)都在onDestory中完成。
2. 如果当前service已经被启动(start),拥有它的进程则比那些用户可见的进程优先级低一些,但是比那些不可见的进程更重要,这就意味着service一般不会被killed.
3. 如果客户端已经连接到service (bindService),那么拥有Service的进程则拥有最高的优先级,可以认为service是可见的。
4. 如果service可以使用startForeground(int, Notification)方法来将service设置为前台状态,那么系统就认为是对用户可见的,并不会在内存不足时killed。
public class 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 public void onDestroy() { Log.i(TAG, "onDestroy"); super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { Log.i(TAG, "onStart"); super.onStart(intent, startId); } }
(2)在Mainifest注册Service
<service android:name=".LocalService"> <intent-filter> <action android:name="命名一个不重复的名称,如:com.service.demo" /> <category android:name="android.intent.category.default" /> </intent-filter> </service>
( 3 ) 建一个activity
public class ServiceActivity extends Activity { @Override protected 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-generated 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("com.demo.SERVICE_DEMO")); } }); } }布局文件代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/startLocalService" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="startLocalService" /> <Button android:id="@+id/stopLocalService" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/startLocalService" android:text="stopLocalService" /></RelativeLayout>
/** * This is an example of implementing an application service that runs locally * in the same process as the application. The {@link LocalServiceController} * and {@link LocalServiceBinding} classes show how to interact with the * service. * * <p>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 such 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. */ public 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. 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 START_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 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 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_sample, 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 notification 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); } }
未完待续...............................
- 细说android service
- Android 细说intent api
- Android 细说进度条
- Android 细说searchView
- 【Android】细说visibility属性
- 细说Android BroadcastReceive
- 细说Android drawable
- Android细说binder机制
- 细说Android事件传递
- Android 事件分发细说
- Android 性能优化细说
- [android]service中再启service
- android自动适应屏幕.一、细说layout_weight
- 细说Android开发环境的搭建
- 细说单例在android中的应用
- android service
- Android Service
- android service
- 函数要多小才够好——谈小函数之道
- MySQL客户端/服务器协议
- servlet基础篇
- (转)JQuery操作checkbox、radio等示例
- C#点滴--几个基本概念
- 细说android service
- 一个tomcat部署多个SSH应用
- JavaScript学习:BOM和DOM的区别和关联
- 为国内开源做点贡献 编译glib
- Protobuf数据编码规则
- GWT 准备开发环境
- Android 重新编译资源文件
- linux下主机名目录
- SQL2008没有使用自己的实例