这里主要介绍Service组件的使用。

1、定义一个继承Service的子类

如下:

package com.service;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class defaultService extends Service {    int mStartMode;       // indicates how to behave if the service is killed    IBinder mBinder;      // interface for clients that bind    boolean mAllowRebind; // indicates whether onRebind should be used    @Override    public void onCreate() {        // The service is being created    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        // The service is starting, due to a call to startService()        return mStartMode;    }    @Override    public IBinder onBind(Intent intent) {        // A client is binding to the service with bindService()        return mBinder;    }    @Override    public boolean onUnbind(Intent intent) {        // All clients have unbound with unbindService()        return mAllowRebind;    }    @Override    public void onRebind(Intent intent) {        // A client is binding to the service with bindService(),        // after onUnbind() has already been called    }    @Override    public void onDestroy() {        // The service is no longer used and is being destroyed    }}

2、在AndroidManifest.xml中使用<service>标签配置该Service

<service android:name="com.service.defaultService">             <intent-filter>                         <action android:name="com.service.dService" />             </intent-filter> </service>

注意:第一个name是service的位置,包括完整的包名和service名。如果包名就是你定义的程序包名,也就是和gen目录下那个包的名字一样的话,直接".service名"就可以了。第二个name是调用service时intent.setAction();中的参数,这个可以随便。

3、Service中定义了如下的生命周期方法:

[1] IBinder onBind(Intent intent):该方法是Service子类必须实现的方法,该方法返回一个IBinder对象,应用程序可通过该对象与Service组件通信 ;

[2] void onCreate():当Service组件第一次被创建后立即回调该方法;

[3]void onDestroy():当Service关闭之前回调该方法;

[4]void onStartCommand(Intent intent,int flags,int startId):该方法的早期版本是onStart(Intent intent,int startId),每次客户端调用startService()方法启动Service时都会回调该方法;

[5]boolean onUnbind(Intent intent):当该Service上绑定的所有客户端断开连接时将会调用该方法

当其它组件通过Context.startService()方法启动Service时,系统会创建一个Service对象,并顺序调用onCreate()方法和onStartCommand()方法,在调用Context.stopService()或stopSelf()之前,Service一直处于运行的状态。如果多次调用startService()方法,系统只会多次调用onStartCommand()方法,不会重复调用onCreate()方法。无论调用了多少次startService()方法,只需调用一次stopService()方法就可以停止该Service。Service对象在销毁之前,onDestroy()方法会被调用,因此与资源释放相关的工作应该在此方法中完成。

3、Service的启动停止

[1]方式一:

当程序通过startService()方法和stopService()方法启动、停止Service()时,Service与访问者之间基本上不存在太多的关联,因此Service和访问者之间也无法进行通信和数据交换。

[2]方式二:

通过bindService()与unbindService()方法启动、停止Service()。

4、方式二详解

bindService(Intent serivce,ServiceConnection connection,int flags)方法启动:

[1]第一个参数通过Intent指定要启动的Service;

[2]第二个参数用于监听访问者与Service之间的连接情况;

该ServiceConnection对象用于监听访问者与Service之间的连接情况,当访问者与Service之间连接成功时,将会回调ServiceConnection对象的onServiceConnected(ComponentName name,IBinder service)方法;当Service所在的进程异常终止或由于其它原因终止时,导致该Service与访问者之间断开连接时,将会回调ServiceConnection对象的onServiceDisconnected(ComponentName name)方法(当主动调用unbindService()方法断开与Service的连接时,不会调用该回调方法)。

注意到ServiceConnection对象的onServiceConnected(ComponentName name,IBinder service)方法中有一个IBinder对象,该对象即实现与被绑定Service之间的通信。

[3]第三个参数指定绑定时是否自动创建Service(如果Service还未创建)。该参数可指定为0(不自动创建)或BIND_AUTO_CREATE(自动创建)。

5、开发Service类时必须提供IBinder onBind(Intent intent)方法

在绑定本地Service的情况下,onBind(Intent intent)方法所返回的IBinder对象将会传给ServiceConnection对象里的onServiceConnected(ComponentName name,IBinder service)方法的service参数,以实现与Service进行通信。

实际上开发时常会采用继承Binder(IBinder的实现类)的方式实现自己的IBinder对象。

package com.service;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;public class BindService extends Service{    private int count;  //标识Service的运行状态    private boolean quit;  //标志Service是否被关闭    //定义onBind()方法所返回的对象    private defaultBinder binder = new defaultBinder();    public class defaultBinder extends Binder    {        public int getCount()        {            //获取Service的运行状态:count            return count;         }    }    @Override    public IBinder onBind(Intent intent)    {        System.out.println("Service is Binded!");        return binder;    }    //Service被创建时回调该方法    @Override    public void onCreate()    {        super.onCreate();        System.out.println("Serivce is Created!");        //启动一条新线程,动态改变count值        new Thread()        {            @Override            public void run()            {                while(!quit)                {                      try{                        Thread.sleep(1000);                    }                    catch (InterruptedException e){                        e.printStackTrace();                    }                    count++;                }            }        }.start();    }        //Service被关闭之前回调该方法    @Override    public void onDestroy()    {        super.onDestroy();        this.quit=true;        System.out.println("Service is Destroyed!");    }    //Service断开连接时回调该方法    @Override    public boolean onUnbind(Intent intent)    {        System.out.println("Service is Unbinder");        return true;    }}

6、接下来在一个Activity中绑定该Service,并在Activity中通过defaultBinder对象访问Service的内部状态。

[1]布局文件如下

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"     android:orientation="vertical"     tools:context=".MainActivity" >    <Button         android:id="@+id/bind"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="绑定Service" />     <Button         android:id="@+id/unbind"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="解除绑定" />     <Button         android:id="@+id/status"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="获取Service状态" /></LinearLayout>

[2]Activity如下:

package com.myandroid;import com.service.BindService;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class ServiceActivity extends Activity{    private Button bind,unbind,status;    BindService.defaultBinder binder;  //保持所启动的Service的IBinder对象         //定义一个ServiceConnection对象    private ServiceConnection conn=new ServiceConnection()    {        @Override        public void onServiceConnected(ComponentName name, IBinder service)        {            System.out.println("Service connected!");            //获取Service的onBind()方法所返回的MyBinder对象            binder=(BindService.defaultBinder) service;        }        @Override        public void onServiceDisconnected(ComponentName name)        {            System.out.println("Service disconnected!");           }      };    @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.service);        //获取界面按钮        bind=(Button)findViewById(R.id.bind);        unbind=(Button)findViewById(R.id.unbind);        status=(Button)findViewById(R.id.status);        //创建启动Service的Intent        final Intent intent=new Intent();

//第一个参数为context,第二个参数为类名(需指定包名) intent.setClassName(this, "com.service.BindService"); bind.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //绑定指定Service bindService(intent,conn,BIND_AUTO_CREATE); } }); unbind.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //解除绑定Service unbindService(conn); } }); status.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //获取Service状态信息 Toast.makeText(ServiceActivity.this,"Service的count值为:"+binder.getCount(),Toast.LENGTH_LONG).show(); } }); }}

更多相关文章

  1. Android(安卓)四大组件之一 :BroadCastReceiver 广播接收器详解
  2. 【学习Android(安卓)NDK开发】native code通过JNI调用Java方法
  3. Android适配器之-----SimpleAdapter
  4. Java和Javascript互调的例子 ---------(Android(安卓)WebView 中)
  5. Android(安卓)AsyncTask
  6. android 中添加一个服务
  7. Android(安卓)之WebView
  8. Android(安卓)视频播放器
  9. android兼容2.2及以前版本的退出方法

随机推荐

  1. Android 应用集成百度地图开发和注意事项
  2. Android开发——纯JAVA代码方式界面设计
  3. Android 日志保存到本地---CscSDK
  4. android 之 百度地图
  5. android从啥都不会到能瞎捣鼓之弄界面(一
  6. Android任务、进程、线程详解
  7. android 方法数越界问题 65536/64k(方法数
  8. Android(安卓)Include标签
  9. android 开发零起步学习笔记(九):android
  10. android图形系统详解一:Canvas