Android 中 Service 全面解析与使用

一、概念:
 Service(服务)是Android中四大组件之一。是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。另外,一个组件能够绑定到一个service与之交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。
 运行种类分类:

类别区别优点缺点应用
本地服务(Local)该服务依附在主进程上服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外Local服务因为是在同一进程因此不需要IPC,也不需要AIDL。相应bindService会方便很多主进程被kill后,服务便会终止非常常见的应用如:HTC音乐播放服务,天天动听音乐播放服务
远程服务(Remote)该服务是独立的进程 服务为独立的进程,对应进程名格式为所在包名加上你指定的android:process字符串。由于是独立的进程,因此在Activity所在进程被kill的时候,该服务依然在运行,不受其他进程影响,有利于为多个进程提供服务具有较高的灵活性该服务是独立的进程,会占用一定资源,并且使用AIDL进行IPC,稍微麻烦一点一些提供系统服务的Service,这种Service是常驻的

其实remote服务还是很少见的,并且一般都是系统服务


 
运行类型分类:

类别区别应用
前台服务会在通知一栏显示ONGOING的Notification当服务被终止的时候,通知一栏Notification也会消失,这样对于用户有一定的通知作用。常见的如音乐播放服务
后台服务默认的服务即为后台服务,即不会在通知一栏显示ONGOING的Notification当服务被终止的时候,用户是看不到效果的。某些不需要运行或终止提示的服务,如天气更新,日期同步,邮件同步等

前台服务会调用startForeground(Android2.0以前的版本为setForeground)使服务成为前台


 
启动方式分类

类别区别
startService启动主要用于启动一个服务执行后台任务,不进行通信,停止服务使用stopService
bindService启动该方法启动的服务要进行通信。停止服务使用unbindService
startService同时也gindService启动停止服务同时使用stopService与unbindService

二、生命周期:
 首先看下周期运行图
 
 1:Context.startService()启动的流程
  启动的时候:Context.startService() ---> onCreate() ---> onStartCommand()(android2.0以前版本为onStart())
  销毁的时候:ontext.stopService() ---> onDestroy()
  如果Service没运行,则此时会先调用onCreate()方法,然后再调用onStartCommand();
  如果Service已经在运行,则只调用onStartCommand()

 2:Context.bindService()启动的流程
  启动的时候:Context.bindService() ---> onCreate() ---> onBind()
  销毁的时候:onUnibind() ---> onDestroy()
  onBind()将会給客户端返回一个IBind接口的实例,此时客户端可以去调用服务的方法,不过此时Activity与Service算是绑定在一起了,即bindService不存在(如Activity被finish()的时候),那么此时的Service也会退出
 3:退出条件(注意)
  startService(一直运行,不管对应程序的Activity是否在运行):
   A、调用stopService
   B、调用自身的stopSelf方法
   C、当系统资源不足,可能被Android系统结束掉
  bindService:
   A、调用Context.unbindService断开连接(建议)
   B、调用bindService的Context不存在了(如Activity被finish的时候、屏幕旋转时,Activity重新创建,之前的Context不存在了),系统会自动停止Service,对应onDestroy将被调用
  startService与bindService:
   A、同时满足上面两个退出条件,与顺序无关
  服务退出后,onDestroy方法将会被调用,在这里应该做一些清除工作,如停止在Service中创建并运行的线程等

三、使用方法:
 1:使用startService启动服务
  不管Local还是Remote,启动与停止方法都是一样。在Androidmanifest.xml中注册service;
  下面给出Service中的代码框架:

			import android.app.Service;
			import android.content.Intent;
			import android.os.IBinder;

			public class ExampleService extends Service {

				/**
				 * Service的虚方法,不得不实现
				 * 返回null,
				 */
				@Override
				public IBinder onBind(Intent intent) {
					// TODO Auto-generated method stub
					return null;
				}
				
				public void onCreate() {
					super.onCreate();
				}
				
				public int onStartCommand (Intent intent, int flags, int startId) {
					return super.onStartCommand(intent, flags, startId);
				}
				
				public void onDestroy () {
					super.onDestroy();
				}
			}

  启动:startService(new Intent(this, ExampleService.class));
  启动:stopService(new Intent(this, ExampleService.class));
 2:使用bindService启动服务
  A、Local服务绑定:首先在Service中实现Service的抽象方法断断onBind,并返回一个实现IBinder接口的对象
   下面为Service的代码:

			import android.app.Service;
			import android.content.Intent;
			import android.os.Binder;
			import android.os.IBinder;

			public class LocalService extends Service {

				/**
				 * 直接继承Binder而不是IBinder,因为Binder实现了IBnder接口,这样可以少做很多工作
				 */
				public class ExampleBinder extends Binder {
					public LocalService getService() {
						return LocalService.this;
					}
					
					public int addTest (int a, int b) {
						return a + b;
					}
				}
				
				public ExampleBinder eBinder = null;
				
				@Override
				public IBinder onBind(Intent intent) {
					// TODO Auto-generated method stub
					return eBinder;
				}
				
				public void onCreate() {
					super.onCreate();
					
					eBinder = new ExampleBinder();
				}
			}

   上面方法主要在于onBind(Intent)返回了一个实现了IBinder接口的对象,这个对象将用于Activity与Local Service通信。
   下面为Activity中的代码:

			import android.app.Activity;
			import android.content.ComponentName;
			import android.content.Context;
			import android.content.Intent;
			import android.content.ServiceConnection;
			import android.os.Bundle;
			import android.os.IBinder;
			import android.util.Log;
			import android.view.View;
			import android.view.View.OnClickListener;

			public class MainActivity extends Activity {

				private ServiceConnection sc = null;
				private boolean isBind = false;
				
				@Override
				protected void onCreate(Bundle savedInstanceState) {
					super.onCreate(savedInstanceState);
					setContentView(R.layout.activity_main);
					
					sc = new ServiceConnection() {
						@Override
						public void onServiceConnected(ComponentName name, IBinder service) {
							// TODO Auto-generated method stub
							LocalService.ExampleBinder mBinder = (LocalService.ExampleBinder) service;
							
							Log.d("test", "5 + 8 = " + mBinder.addTest(5, 8));
						}

						@Override
						public void onServiceDisconnected(ComponentName arg0) {
							// TODO Auto-generated method stub
							
						}
					};
					
					findViewById(R.id.bt_bind).setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							bindService(new Intent(MainActivity.this, LocalService.class), sc, Context.BIND_AUTO_CREATE);
							isBind = true;
						}
					});
					findViewById(R.id.bt_unbind).setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							if(isBind) {
								unbindService(sc);
								isBind = false;
							}
						}
					});
				}
			}

   通过ServiceConnection接口来取得建立连接与连接意外丢失的回调。Service.onBind如果返回null,则调用bindService会启动Service,但不会连接上Service,因此ServiceConnection.onServiceConnected不会被调用,但仍然需要使用unbindService函数断开它
  B、Remote服务绑定:Remote服务绑定由于服务是在另外一个进程,因此需要用到Android的IPC机制。
   在AndroidManifest.xml中

				<service android:enabled="true" android:name=".TestService" android:process=":remote"/>

   下面为ITestService.aidl的代码:

				package com.iceskysl.TestServiceHolder; 

				interface ITestService
				{
					int getCount();
				}

   下面为Service的代码:

				package com.iceskysl.TestServiceHolder; 

				import android.app.Notification;
				import android.app.NotificationManager;
				import android.app.PendingIntent;
				import android.app.Service;
				import android.content.Intent;
				import android.os.IBinder;
				import android.os.RemoteException;
				import android.util.Log;

				public class TestService extends Service {

					private static final String TAG = "TestService";
					private NotificationManager _nm;
					private boolean threadEnable = true;
					private int i = 0;

					private ITestService.Stub serviceBinder = new ITestService.Stub() {
						@Override
						public int getCount() throws RemoteException {
							// TODO Auto-generated method stub
							return i;
						}
					};

					@Override
					public IBinder onBind(Intent i) {
						Log.e(TAG, "============> TestService.onBind");
						return serviceBinder;
					}

					@Override
					public boolean onUnbind(Intent i) {
						Log.e(TAG, "============> TestService.onUnbind");
						return false;
					}

					@Override
					public void onRebind(Intent i) {
						Log.e(TAG, "============> TestService.onRebind");
					}

					@Override
					public void onCreate() {
						Log.e(TAG, "============> TestService.onCreate");
						_nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
						showNotification();

						new Thread() {
							public void run() {
								try {
									while (threadEnable) {
										sleep(1000);
										Log.d(TAG, "Count = " + (++i));
									}
								} catch (InterruptedException e) {
									e.printStackTrace();
								}

							}
						}.start();
					}

					@Override
					public void onStart(Intent intent, int startId) {
						Log.e(TAG, "============> TestService.onStart");
					}

					@Override
					public void onDestroy() {
						_nm.cancel(R.string.service_started);
						threadEnable = false;
						Log.e(TAG, "============> TestService.onDestroy");
					}

					private void showNotification() {
						Notification notification = new Notification(R.drawable.face_1,
								"Service started", System.currentTimeMillis());
						PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
								new Intent(this, TestServiceHolder.class), 0);
						// must set this for content view, or will throw a exception
						notification.setLatestEventInfo(this, "Test Service",
								"Service started", contentIntent);

						_nm.notify(R.string.service_started, notification);
					}

					public int getCount() {
						return i;
					}
				}

   下面为Activity代码:

				package com.iceskysl.TestServiceHolder; 

				import android.app.Activity;
				import android.content.ComponentName;
				import android.content.Context;
				import android.content.Intent;
				import android.content.ServiceConnection;
				import android.os.Bundle;
				import android.os.IBinder;
				import android.os.RemoteException;
				import android.util.Log;
				import android.view.View;
				import android.view.View.OnClickListener;
				import android.widget.Button;
				import android.widget.Toast;

				public class TestServiceHolder extends Activity {
					private boolean _isBound;
					private ITestService _boundService = null;

					private static final String TAG = "TestServiceHolder";

					private IBinder _service;

					/** Called when the activity is first created. */
					@Override
					public void onCreate(Bundle savedInstanceState) {
						super.onCreate(savedInstanceState);
						setContentView(R.layout.main);
						setTitle("Service Test");
						initButtons();

					}

					private ServiceConnection _connection = new ServiceConnection() {
						public void onServiceConnected(ComponentName className, IBinder service) {
							_boundService = ITestService.Stub.asInterface(service);
							Toast.makeText(TestServiceHolder.this, "Service connected",
									Toast.LENGTH_SHORT).show();
							Log.e(TAG, "=====>onServiceConnected()");
						}

						public void onServiceDisconnected(ComponentName className) {
							// unexpectedly disconnected,we should never see this happen.
							_boundService = null;
							Toast.makeText(TestServiceHolder.this, "Service connected",
									Toast.LENGTH_SHORT).show();
							Log.e(TAG, "<=====onServiceDisconnected()");
						}
					};

					private void initButtons() {
						Button buttonStart = (Button) findViewById(R.id.start_service);
						buttonStart.setOnClickListener(new OnClickListener() {
							public void onClick(View arg0) {
								startService();
							}
						});

						Button buttonStop = (Button) findViewById(R.id.stop_service);
						buttonStop.setOnClickListener(new OnClickListener() {
							public void onClick(View arg0) {
								stopService();
							}
						});

						Button buttonBind = (Button) findViewById(R.id.bind_service);
						buttonBind.setOnClickListener(new OnClickListener() {
							public void onClick(View arg0) {
								bindService();
							}
						});

						Button buttonUnbind = (Button) findViewById(R.id.unbind_service);
						buttonUnbind.setOnClickListener(new OnClickListener() {
							public void onClick(View arg0) {
								unbindService();
							}
						});
					}

					private void startService() {
						Intent i = new Intent(this, TestService.class);
						this.startService(i);
					}

					private void stopService() {
						Intent i = new Intent(this, TestService.class);
						this.stopService(i);
					}

					private void bindService() {
						Intent i = new Intent(this, TestService.class);
						bindService(i, _connection, Context.BIND_AUTO_CREATE);
						_isBound = true;

					}

					private void unbindService() {
						if (_boundService != null) {
							try {
								Log.e(TAG,"_boundService.getCount() = "+ _boundService.getCount());
							} catch (RemoteException e) {
								e.printStackTrace();
							}
						}

						if (_isBound) {
							unbindService(_connection);
							_isBound = false;
						}
					}
				}

四、创建前台服务
 代码:

		import java.lang.reflect.Method;

		import android.app.Notification;
		import android.app.NotificationManager;
		import android.app.PendingIntent;
		import android.app.Service;
		import android.content.Context;
		import android.content.Intent;
		import android.os.IBinder;

		public class ForegroundService extends Service {

			private static final Class[] mStartForegroundSignature = new Class[] {
				int.class, Notification.class };
			private static final Class[] mStopForegroundSignature = new Class[] {
				boolean.class };
			private NotificationManager mNM = null;
			private Method mStartForeground = null;
			private Method mStopForeground = null;
			private Object[] mStartForegroundArgs = new Object[2];
			private Object[] mStopForegroundArgs = new Object[1];
			
			@Override
			public IBinder onBind(Intent intent) {
				// TODO Auto-generated method stub
				return null;
			}

			public void onCreate() {
				super.onCreate();
				mNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				try {
					mStartForeground = ForegroundService.class.getMethod("startForeground", mStartForegroundSignature);
					mStopForeground = ForegroundService.class.getMethod("stopForeground", mStopForegroundSignature);
				} catch(NoSuchMethodException e) {
					mStartForeground = mStopForeground = null;
				}
				
				// 我们并不需要为notification.flags 设置FLAG_ONGOING_EVENT,因为前台服务的notification.flags总是默认包含了那个标志位
				Notification notification = new Notification(R.drawable.icon, "Foreground Service Started.", System.currentTimeMillis());
				PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
				notification.setLatestEventInfo(this, "Foreground Service", "Foreground Service Started.", contentIntent);
				
				// 注意使用startForeground, id 为0将不会显示notification 
				startForegroundCompat(1, notification);
			}
			
			public void onDestroy() {
				super.onDestroy();
				stopForegroundCompat(1);
			}
			
			private void startForegroundCompat(int id, Notification n) {
				if(mStartForeground != null) {
					mStartForegroundArgs[0] = id;
					mStartForegroundArgs[1] = n;
					try {
						mStartForeground.invoke(this, mStartForegroundArgs);
					} catch(Exception e) {
						e.printStackTrace();
					}
					return;
				}
				// API Level >= 5
				startForeground(id, n);
				// API Level < 5
				/*startForeground();
				mNM.notify(id, n);*/
			}
			
			private void stopForegroundCompat(int id) {
				if(mStopForeground != null) {
					mStopForegroundArgs[0] = Boolean.TRUE;
					try {
						mStopForeground.invoke(this, mStopForegroundArgs);
					} catch(Exception e) {
						e.printStackTrace();
					}
					return;
				}
				
				// API Level >= 5
				stopForeground(true);
				// API Level < 5
				// 在setForeground之前调用cancel,因为我们有可能在取消前台服务之后的那一瞬间被kill掉。这个时候notification便永远不会从通知一栏移除mNM.cancel(id);
				/*mNM.cancel(id);
				setForeground(false);*/
			}
		}

五、使用情景
 1:如果你只是想要启动一个后台服务长期进行某项任务那么使用 startService 便可以了。
 2:如果你想要与正在运行的 Service 取得联系
  A、使用 broadcast,缺点是如果交流较为频繁,容易造成性能上的问题,并且 BroadcastReceiver 本身执行代码的时间是很短的(也许执行到一半,后面的代码便不会执行)
  B、使用 bindService,没有上面的问题,因此选择使用 bindService(这个时候便同时在使用 startService 和 bindService 了,这在 Activity 中更新 Service 的某些运行状态是相当有用的)
 3:如果你的服务只是公开一个远程接口,供连接上的客服端(android 的 Service 是C/S架构)远程调用执行方法。这个时候你可以不让服务一开始就运行,而只用 bindService ,这样在第一次 bindService 的时候才会创建服务的实例运行它,这会节约很多系统资源,特别是如果你的服务是Remote Service,那么该效果会越明显(当然在 Service 创建的时候会花去一定时间,你应当注意到这点)。
六、Service 元素的常见选项
 android:name:服务类名
 android:label:服务的名字,如果此项不设置,那么默认显示的服务名则为类名
 android:icon:服务的图标
 android:permission:申明此服务的权限,这意味着只有提供了该权限的应用才能控制或连接此服务
 android:process:表示该服务是否运行在另外一个进程,如果设置了此项,那么将会在包名后面加上这段字符串表示另一进程的名字
 android:enabled:如果此项设置为 true,那么 Service 将会默认被系统启动,不设置默认此项为 false
 android:exported:表示该服务是否能够被其他应用程序所控制或连接,不设置默认此项为 false

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值