Android Service

来源:互联网 发布:淘宝售前客服工作概要 编辑:程序博客网 时间:2024/06/06 18:21


  一.Service

服务是运行在后台的一段代码。它可以运行在它自己的进程,也可以运行在其他应用程序进程的上下文(context)里面,这取决于自身的需要。其它的组件可以绑定到一个服务Service)上面,通过远程过程调用(RPC)来调用这个方法。例如媒体播放器的服务,当用户退出媒体选择用户界面,仍然希望音乐依然可以继续播放,这时就是由服务 service)来保证当用户界面关闭时音乐继续播放的。

 

它跟Activity的级别差不多,但是他不能自己运行,需要通过某一个Activity或者其他Context对象来调用, Context.startService()Context.bindService()

两种启动Service的方式有所不同。这里要说明一下的是如果你在ServiceonCreate或者onStart做一些很耗时间的事情,最好在Service里启动一个线程来完成,因为Service是跑在主线程中,会影响到你的UI操作或者阻塞主线程中的其他事情。

什么时候需要Service呢?比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息位置的改变等等。

  二.使用Service

private String MY_ACTION = "com.demo.MyService";
启动Service

Intent intent = new Intent();intent.setAction(MY_ACTION);startService(intent);

停止Service

Intent intent = new Intent();intent.setAction(MY_ACTION);stopService(intent);

绑定Service

Intent intent = new Intent();intent.setAction(MY_ACTION);unbindService(conn);

解除绑定Service

Intent intent = new Intent();intent.setAction(MY_ACTION);bindService(intent, conn, Service.BIND_AUTO_CREATE);
private ServiceConnection conn = new ServiceConnection(){public void onServiceConnected(ComponentName name, IBinder service) {System.out.println("连接成功!");showMessage("连接成功!");}public void onServiceDisconnected(ComponentName name) {System.out.println("断开连接!");showMessage("断开连接!");}};

Service类代码:

package com.demo;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class MyService extends Service {public IBinder onBind(Intent intent) {System.out.println("Service onBind");return null;}public void onCreate() {System.out.println("Service onCreate");super.onCreate();}public void onStart(Intent intent, int startId) {System.out.println("Service onStart");super.onStart(intent, startId);}public void onDestroy() {System.out.println("Service onDestory");super.onDestroy();}}

AndroidManifest.xml

        <service android:name="MyService">        <intent-filter>        <action android:name="com.demo.MyService"/>        </intent-filter>        </service>

原创粉丝点击