当前位置: 代码迷 >> Android >> Android-41-Service简介
  详细解决方案

Android-41-Service简介

热度:7   发布时间:2016-04-28 00:54:18.0
Android---41---Service简介


Service  是Android四大组件中与Activity最相似的组件。

Service与Activity的区别是:Service一直在后台运行,它没有用户界面。

我们所见的与用户进行交互的界面属于Activity,而Activity要实现的功能就要靠背后默默工作的Service。

比如说,发送短信的功能,让我们输入对方手机号以及要发送的内容,这些就属于Activity,而真正的
去发送短信的还是靠SmsManager。


创建、配置Service:
定义一个继承Service的子类。
在配置文件中配置该Service。


Service中的方法:


@Overridepublic IBinder onBind(Intent intent) {		return null;}

这是Service子类必须实现的方法,返回一个IBinder,应用程序通过该对象与Service组件进行通信。



@Overridepublic void onCreate() {		super.onCreate();}

第一次创建将立即回调该方法。


@Overridepublic void onDestroy() {		super.onDestroy();}

当Service被关闭之前将会回调该方法


@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {		return super.onStartCommand(intent, flags, startId);}

每次客户端调用srartService(Intent) 方法启动该Service的时候都会回调该方法。



@Overridepublic boolean onUnbind(Intent intent) {		return super.onUnbind(intent);}
当该Service上绑定的所有客户端都断开连接时 将会回调该方法。



public class MainActivity extends Service {	/*	 * (non-Javadoc)	 * 	 * @see android.app.Service#onBind(android.content.Intent)	 * 	 * 必须实现的方法	 */	@Override	public IBinder onBind(Intent intent) {		// TODO Auto-generated method stub		return null;	}	/*	 * (non-Javadoc)	 * 	 * @see android.app.Service#onCreate()	 * 	 * 	 * 被创建的时候回调	 */	@Override	public void onCreate() {		// TODO Auto-generated method stub		super.onCreate();	}	/*	 * (non-Javadoc)	 * 	 * @see android.app.Service#onDestroy() 被关闭之前回调	 */	@Override	public void onDestroy() {		// TODO Auto-generated method stub		super.onDestroy();	}	/*	 * (non-Javadoc)	 * 	 * @see android.app.Service#onStartCommand(android.content.Intent, int, int)	 * 被启动的时候回调	 */	@Override	public int onStartCommand(Intent intent, int flags, int startId) {		// TODO Auto-generated method stub		return super.onStartCommand(intent, flags, startId);	}	/*	 * (non-Javadoc)	 * 	 * @see android.app.Service#onUnbind(android.content.Intent) 所有客户端都断开连接的时候回调	 */	@Override	public boolean onUnbind(Intent intent) {		// TODO Auto-generated method stub		return super.onUnbind(intent);	}}


Service的配置与Activity几乎一样。


<service android:name=".MainActivity" >    <intent-filter>	<action android:name="com.example.servicedemo" />    </intent-filter></service>



运行Service:


运行Service有两种方式:

运行Service有两种方式:

1.通过Contex的startService ()方法:
通过该方法启动Service,访问者与Service之间没有关联,计时访问者退出了,Service仍然运行

2.通过Contex的bindService()方法:
使用该方法启动Service,访问者与Service绑定在了一起,访问者一旦退出,Service也就终止。








  相关解决方案