一、首先了解Android中的服务,他可以长期保存在系统后天,等待系统或其他应用的调用。在系统启动时,开启了很多的系统,我们使用getSystemService(serviceName)获取到的XXXManager,其实是获取系统服务的接口,用XXXManager调用系统服务,系统服务调用时通过AIDL 机制 实现的。

二、service根据进程分为 本地service 和 远程service 。

       AIDL :Android interface Definition language 他是Android内部进程通讯的描述语言。通过他可以定义进程通讯的接口。而远程service 是通过AIDL 实现进程间通信的。调用系统服务也是用AIDL 实现的。

三、service 启动方式 

     1、startService  开启服务后 我们的上下文就和这个服务失去联系。使用该方式启动 调用者不可以访问 service里面的方法. 调用者如果被系统回收了或者调用了ondestroy方法, service还会继续存在 ,如果该service已经启动了,在调用startService 调用onStart();

      2、binderService 开启服务后上下文Context 会和 该服务建立一个连接,在建立连接中要 实现 ServiceConnection 接口,实现接口中方法

onServiceConnected(ComponentName name, IBinder service)onServiceDisconnected(ComponentName name)

方法 ,并获取到 binder 对象 ,通过binder对象访问 service。

 在 service端 的onBind() 返回值是个 IBinder 对象。 并在在该service中 写个内部类 继承 Binder 类。通过内部类的特性:内部对象有外部类的引用,可以访问外部类。所以 在 activity中获取到 binder对象后,就可以访问service中的方法了。

binderService只能绑定服务一次,意思是 只调用 onBinder一次。

    3、service的生命周期

   

四 、 startService和 binderService 实例

(1)mainactivity

public class MainActivity extends Activity {    Button startServiceButton;// 启动服务按钮    Button shutDownServiceButton;// 关闭服务按钮    Button startBindServiceButton;// 启动绑定服务按钮    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                getWidget();        regiestListener();    }    /** 获得组件 */    public void getWidget() {        startServiceButton = (Button) findViewById(R.id.startServerButton);        startBindServiceButton = (Button) findViewById(R.id.startBindServerButton);        shutDownServiceButton = (Button) findViewById(R.id.sutdownServerButton);    }    /** 为按钮添加监听 */    public void regiestListener() {        startServiceButton.setOnClickListener(startService);        shutDownServiceButton.setOnClickListener(shutdownService);        startBindServiceButton.setOnClickListener(startBinderService);    }            /** 启动服务的事件监听 */    public Button.OnClickListener startService = new Button.OnClickListener() {        public void onClick(View view) {            /** 单击按钮时启动服务 */            Intent intent = new Intent(MainActivity.this,                    CountService.class);            startService(intent);                        Log.v("MainStadyServics", "start Service");        }    };    /** 关闭服务 */    public Button.OnClickListener shutdownService = new Button.OnClickListener() {        public void onClick(View view) {            /** 单击按钮时启动服务 */            Intent intent = new Intent(MainActivity.this,                    CountService.class);            /** 退出Activity是,停止服务 */            stopService(intent);            Log.v("MainStadyServics", "shutDown serveice");        }    };    /** 打开绑定服务的Activity */    public Button.OnClickListener startBinderService = new Button.OnClickListener() {        public void onClick(View view) {            /** 单击按钮时启动服务 */            Intent intent = new Intent(MainActivity.this, UseBrider.class);            startActivity(intent);            Log.v("MainStadyServics", "start Binder Service");        }    };    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }

(2)service

package com.example.testservice;/**引入包*/import android.app.Service;// 服务的类import android.os.IBinder;import android.os.Binder;import android.content.Intent;import android.util.Log;/** 计数的服务 */public class CountService extends Service {    /** 创建参数 */    boolean threadDisable;    int count;    public IBinder onBind(Intent intent) {        return null;    }    public void onCreate() {        super.onCreate();        /** 创建一个线程,每秒计数器加一,并在控制台进行Log输出 */        new Thread(new Runnable() {            public void run() {                while (!threadDisable) {                    try {                        Thread.sleep(1000);                    } catch (InterruptedException e) {                    }                    count++;                    Log.v("CountService", "Count is" + count);                }            }        }).start();    }    public void onDestroy() {        super.onDestroy();        /** 服务停止时,终止计数进程 */        this.threadDisable = true;    }    public int getConunt() {        return count;    }//此方法是为了可以在Acitity中获得服务的实例
class ServiceBinder extends Binder {        public CountService getService() {            return CountService.this;        }    }}

(3)bindservice(一定要记着这个是要获得,链接的对象)

package com.example.testservice;/**引入包*/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;/** 通过bindService和unBindSerivce的方式启动和结束服务 */public class UseBrider extends Activity {    /** 参数设置 */    CountService countService;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(new UseBriderFace(this));                Intent intent = new Intent(UseBrider.this, CountService.class);        /** 进入Activity开始服务 */        bindService(intent, conn, Context.BIND_AUTO_CREATE);    }        private ServiceConnection conn = new ServiceConnection() {        /** 获取服务对象时的操作 */        public void onServiceConnected(ComponentName name, IBinder service) {            // TODO Auto-generated method stub            countService = ((CountService.ServiceBinder) service).getService();        }        /** 无法获取到服务对象时的操作 */        public void onServiceDisconnected(ComponentName name) {            // TODO Auto-generated method stub            countService = null;        }    };    protected void onDestroy() {        super.onDestroy();        this.unbindService(conn);        Log.v("MainStadyServics", "out");    }}

五、AIDL 实现
http://blog.csdn.net/liuhe688/article/details/6400385

六、其他相关问题优秀博客:

http://www.2cto.com/kf/201501/370478.html

更多相关文章

  1. Android面试必备——AsyncTask源码解析
  2. Android(安卓)客户端与服务器交互
  3. Android(安卓)startActivity源码详解
  4. 深入理解Android插件化技术
  5. Android开发之低调的Service
  6. Android学习日记----------Android(安卓)10调用摄像头闪退问题--
  7. Android使用xutils3框架实现应用程序内的检查更新下载服务器存放
  8. Android(安卓)开发艺术探索笔记-Activity启动方式
  9. Android(安卓)MediaPlayer的核心原理

随机推荐

  1. android 定时器(Handler Timer Thread Al
  2. 我见过的最好的DataBinding解析
  3. Android基础入门教程——7.5.1 WebView(
  4. 移动开发:Android升级ADT22后会报ClassNo
  5. AndroidManifest拾遗
  6. 从Google Analytics看国内Android开发人
  7. Android(安卓)异步更新UI的几种方式
  8. Android常用的几个命令
  9. Android线程优先级设置方法技巧
  10. Android中解析JSON(一)