1服务可以通过startservice的方法 开启。通过stopservice的方法 停止。

服务有一个特点: 只会一次onCreate()方法一旦被创建出来,以后oncreate() 就不会再被执行了,
以后再去开启服务 只会执行onstart()方法,当服务被停止的时候 onDestroy();

2 服务通过bindservice的方法开启
首先 如果服务不存在 就会执行 oncreate() ->onbind()方法
一旦服务绑定成功 以后再去执行 bindsercie() 就不会在重新创建 或者绑定服务了();

如果我们现实的调用unbindservice()的方法 ,首先 on unbind()方法 -> ondestroy() ;
服务只能被解除绑定一次 多次解除绑定服务 程序会出异常.

开启服务 (startservice)
服务一旦开启与调用者没有任何的关系 , 调用着的activity 即便是退出了 也不会影响
后台的service的运行.
在activity里面 不能去调用服务里面的方法 (因为Service是框架new出来的,activity无法获取到该Service的引用).

通过绑定方式开启服务(bindservice)
服务跟调用者不求同生 ,但求同死.
如果调用者(activity)退出了 那他绑定的服务呢 也会跟着退出.

我们可以在activity里面调用服务里面的方法.

利用 serviceSonnection 接口 返回一个ibinder对象 , 拿着ibinder对象获取到服务里面方法的引用(自定义了一个接口信息) 调用服务里面的方法。

一个应用程序 一个进程里面 定义一个IService 的接口来描述方法

如果我们要调用另外一个进程 服务里面的方法 aidl(android interface defination language)

总结流程:

1.要想访问 一个服务里面的方法 我们需要用到 bindservice();
一 创建一个服务 这个服务里面有一个要被调用的方法.
二 定义一个接口IService , 接口里面的抽象方法 就是去调用service里面的方法。 
三 定义一个mybinder对象 extends IBinder对象 实现 我们声明的接口IService, 在onbind
方法里面把mybinder返回回去。
四 在activity里面 通过bindservice的方法开启服务。 
五 创建出来一个我们MyConn 实现 ServiceConnection接口 onserviceConnected的方法。
这个方法会有一个参数 这个参数就是 MyBinder的对象。 
六 把mybinder强制类型转化成 IServcie。
七 调用IService里面的方法。

范例:开启、停止、绑定、解除绑定、调用服务里面的方法。

  1. public interface IService {
  2. public void callMethodInService();
  3. }
  1. import android.app.Activity;
  2. import android.content.ComponentName;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.content.ServiceConnection;
  6. import android.os.Bundle;
  7. import android.os.IBinder;
  8. import android.view.View;
  9. import android.view.View.OnClickListener;
  10. import android.widget.Button;
  11. /**
  12. * 通过startservice开启服务的生命周期。
  13. * 利用bindservice调用服务里面的方法。
  14. * @author dr
  15. */
  16. public class DemoActivity extends Activity implements OnClickListener {
  17. Button bt_start, bt_stop;
  18. // 绑定服务 解除绑定服务
  19. Button bt_bind_service, bt_unbind_service;
  20. Button bt_call_service;
  21. Intent intent;
  22. MyConn conn;
  23. IService iService;
  24. @Override
  25. public void onCreate(Bundle savedInstanceState) {
  26. super.onCreate(savedInstanceState);
  27. setContentView(R.layout.main);
  28. bt_start = (Button) this.findViewById(R.id.button1);
  29. bt_stop = (Button) this.findViewById(R.id.button2);
  30. bt_bind_service = (Button) this.findViewById(R.id.button3);
  31. bt_unbind_service = (Button) this.findViewById(R.id.button4);
  32. bt_call_service = (Button) this.findViewById(R.id.button5);
  33. bt_start.setOnClickListener(this);
  34. bt_stop.setOnClickListener(this);
  35. bt_bind_service.setOnClickListener(this);
  36. bt_unbind_service.setOnClickListener(this);
  37. bt_call_service.setOnClickListener(this);
  38. intent = new Intent(this, MyService.class);
  39. conn = new MyConn();
  40. }
  41. @Override
  42. public void onClick(View v) {
  43. switch (v.getId()) {
  44. case R.id.button1: // 开启服务
  45. startService(intent);
  46. break;
  47. case R.id.button2: // 停止服务
  48. stopService(intent);
  49. break;
  50. case R.id.button3: // 绑定服务
  51. bindService(intent, conn, Context.BIND_AUTO_CREATE);
  52. break;
  53. case R.id.button4: // 解除绑定服务
  54. unbindService(conn);
  55. break;
  56. // 绑定开启
  57. case R.id.button5: // 调用服务里面的方法
  58. iService.callMethodInService();
  59. break;
  60. }
  61. }
  62. private class MyConn implements ServiceConnection {
  63. // 绑定一个服务成功的时候 调用 onServiceConnected
  64. @Override
  65. public void onServiceConnected(ComponentName name, IBinder service) {
  66. // 绑定成功后,会返回这个IBinder对象(MyService中的onBind返回的)。
  67. iService = (IService) service;
  68. }
  69. @Override
  70. public void onServiceDisconnected(ComponentName name) {
  71. }
  72. }
  73. @Override
  74. protected void onDestroy() {
  75. unbindService(conn);
  76. super.onDestroy();
  77. }
  78. }
  1. import android.app.Service;
  2. import android.content.Intent;
  3. import android.os.Binder;
  4. import android.os.IBinder;
  5. public class MyService extends Service {
  6. @Override
  7. public IBinder onBind(Intent intent) {
  8. System.out.println("on bind");
  9. return new MyBinder();
  10. }
  11. public class MyBinder extends Binder implements IService {
  12. @Override
  13. public void callMethodInService() {
  14. sayHelloInService();
  15. }
  16. }
  17. /**
  18. * 服务里面的一个方法
  19. */
  20. public void sayHelloInService() {
  21. System.out.println("hello in service");
  22. }
  23. @Override
  24. public boolean onUnbind(Intent intent) {
  25. System.out.println("on unbind");
  26. return super.onUnbind(intent);
  27. }
  28. @Override
  29. public void onCreate() {
  30. System.out.println("oncreate");
  31. super.onCreate();
  32. }
  33. @Override
  34. public void onStart(Intent intent, int startId) {
  35. System.out.println("onstart");
  36. super.onStart(intent, startId);
  37. }
  38. @Override
  39. public void onDestroy() {
  40. System.out.println("ondestroy");
  41. super.onDestroy();
  42. }
  43. }

2.要想访问一个远程服务里的方法 需要用到aidl
一 创建一个服务 这个服务里面有一个要被调用的方法.
二 定义一个接口IService , 接口里面的抽象方法 就是去调用service里面的方法。 
把.java的后缀名改成aidl 把接口里面定义的访问权限的修饰符都给删除。
三 定义一个mybinder对象 extends IService.Stub, 在onbind方法里面把mybinder返回回去。
四 在activity里面 通过bindservice的方法开启服务。
五 创建出来一个我们MyConn 实现 ServiceConnection接口 onserviceConnected的方法,这个方法会有一个参数 这个参数就是MyBinder的对象。
六 IService = IService.Stub.asInterface(myBinder)。
七 调用IService的方法。

范例:采用aidl访问远程服务里面的方法

  1. import android.app.Service;
  2. import android.content.Intent;
  3. import android.os.IBinder;
  4. import android.os.RemoteException;
  5. /**
  6. * 采用aidl访问远程服务里面的方法 --- 远程服务
  7. * 调用着是:callremote Project。
  8. * @author dr
  9. *
  10. */
  11. public class RemoteService extends Service {
  12. @Override
  13. public IBinder onBind(Intent intent) {
  14. return new MyBinder();
  15. }
  16. private class MyBinder extends IService.Stub {
  17. @Override
  18. public void callMethodInService() throws RemoteException {
  19. sayHelloInService();
  20. }
  21. }
  22. /**
  23. * 服务里面的一个方法
  24. */
  25. public void sayHelloInService() {
  26. System.out.println("hello in service");
  27. }
  28. @Override
  29. public void onCreate() {
  30. System.out.println("remote service oncreate");
  31. super.onCreate();
  32. }
  33. }
  1. // IService.aidl 文件
  2. interface IService {
  3. void callMethodInService();
  4. }
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="cn.itcast.remoteservice"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <uses-sdk android:minSdkVersion="8" />
  7. <application
  8. android:icon="@drawable/ic_launcher"
  9. android:label="@string/app_name" >
  10. <service android:name=".RemoteService" >
  11. <intent-filter >
  12. <action android:name="cn.itcast.remoteservice"/>
  13. </intent-filter>
  14. </service>
  15. </application>
  16. </manifest>
  1. import cn.itcast.remoteservice.IService;
  2. import android.app.Activity;
  3. import android.content.ComponentName;
  4. import android.content.Intent;
  5. import android.content.ServiceConnection;
  6. import android.os.Bundle;
  7. import android.os.IBinder;
  8. import android.os.RemoteException;
  9. import android.view.View;
  10. /**
  11. * 采用aidl访问远程服务里面的方法 --- 调用远程服务
  12. * 调用着是:remoteservice Project。
  13. * @author dr
  14. *
  15. */
  16. public class DemoActivity extends Activity {
  17. IService iService;
  18. @Override
  19. public void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.main);
  22. Intent intent = new Intent();
  23. intent.setAction("cn.itcast.remoteservice");
  24. bindService(intent, new MyConn(), BIND_AUTO_CREATE);
  25. }
  26. public void click(View view){
  27. try {
  28. // 调用了远程服务的方法
  29. iService.callMethodInService();
  30. } catch (RemoteException e) {
  31. // TODO Auto-generated catch block
  32. e.printStackTrace();
  33. }
  34. }
  35. private class MyConn implements ServiceConnection{
  36. @Override
  37. public void onServiceConnected(ComponentName name, IBinder service) {
  38. iService = IService.Stub.asInterface(service);
  39. }
  40. @Override
  41. public void onServiceDisconnected(ComponentName name) {
  42. // TODO Auto-generated method stub
  43. }
  44. }
  45. }
  1. // 把 远程服务 Demo中的 aidl文件复制过来。包路径要一致。
  2. interface IService {
  3. void callMethodInService();
  4. }
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="cn.itcast.remoteservice"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <uses-sdk android:minSdkVersion="8" />
  7. <application
  8. android:icon="@drawable/ic_launcher"
  9. android:label="@string/app_name" >
  10. <service android:name=".RemoteService" >
  11. <intent-filter >
  12. <action android:name="cn.itcast.remoteservice"/>
  13. </intent-filter>
  14. </service>
  15. </application>
  16. </manifest>

范例:采用aidl挂断电话

  1. import java.lang.reflect.Method;
  2. import com.android.internal.telephony.ITelephony;
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.os.IBinder;
  6. import android.os.RemoteException;
  7. import android.view.View;
  8. /**
  9. * 采用aidl挂断电话
  10. * @author dr
  11. */
  12. public class DemoActivity extends Activity {
  13. ITelephony iTelephony;
  14. /** Called when the activity is first created. */
  15. @Override
  16. public void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.main);
  19. try {
  20. // 获取系统电话管理的服务
  21. Method method = Class.forName("android.os.ServiceManager")
  22. .getMethod("getService", String.class);
  23. IBinder binder = (IBinder) method.invoke(null,
  24. new Object[] { TELEPHONY_SERVICE });
  25. iTelephony = ITelephony.Stub.asInterface(binder);
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. public void endcall(View view) {
  31. try {
  32. iTelephony.call("123");
  33. } catch (RemoteException e) {
  34. e.printStackTrace();
  35. }
  36. // iTelephony.call("123");
  37. }
  38. }
  1. /* //device/java/android/android/content/Intent.aidl
  2. **
  3. ** Copyright 2007, The Android Open Source Project
  4. **
  5. ** Licensed under the Apache License, Version 2.0 (the "License");
  6. ** you may not use this file except in compliance with the License.
  7. ** You may obtain a copy of the License at
  8. **
  9. ** http://www.apache.org/licenses/LICENSE-2.0
  10. **
  11. ** Unless required by applicable law or agreed to in writing, software
  12. ** distributed under the License is distributed on an "AS IS" BASIS,
  13. ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ** See the License for the specific language governing permissions and
  15. ** limitations under the License.
  16. */

  17. // NeighboringCellInfo.aidl
  18. package android.telephony;
  19. parcelable NeighboringCellInfo;
  1. <uses-permission android:name="android.permission.CALL_PHONE" />

 

27、Service的更多相关文章

  1. Controller、Service、Dao进行Junit单元

    原文链接:http://blog.csdn.net/u013041642/article/details/71430293 Spring对Controller.Service.Dao进行Junit单元 ...

  2. 十九、Service Ingress

    Service Ingress Ingress-Nginx github 地址:https://github.com/kubernetes/ingress-nginx Ingress-Nginx 官方 ...

  3. java中Action层、Service层和Dao层的功能区分

    Action/Service/DAO简介: Action是管理业务(Service)调度和管理跳转的. Service是管理具体的功能的. Action只负责管理,而Service负责实施. DAO只 ...

  4. 【Java 新建项目】使用程序对新项目的各个实体 创建Dao、DaoImpl、Service、ServiceImpl层的文件

    首先给出基本Dao层代码: GenericDao.java package com.agen.dao; import java.io.Serializable; import java.util.Co ...

  5. @Repository、@Service、@Controller 和 @Component

    转载:http://blog.csdn.net/ye1992/article/details/19971467 spring 自 2.0 版本开始,陆续引入了一些注解用于简化 Spring 的开发.@ ...

  6. Spring注解@Component、@Repository、@Service、@Controller区别 .

    Spring 2.5 中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository.@Service 和 @Controller.在目前的 Spring ...

  7. [转] Spring注解@Component、@Repository、@Service、@Controller区别

    原文地址:http://blog.csdn.net/zhang854429783/article/details/6785574 很长时间没做web项目都把以前学的那点框架知识忘光了,今天把以前做的一 ...

  8. SSH 框架学习之初识Java中的Action、Dao、Service、Model-收藏

    SSH 框架学习之初识Java中的Action.Dao.Service.Model-----------------------------学到就要查,自己动手动脑!!!   基础知识目前不够,有感性 ...

  9. thinkphp模型层Model、Logic、Service讲解

    thinkphp模型层Model.Logic.Service讲解 时间:2014-08-24 15:54:56   编辑:一切随缘   文章来源:php教程网 已阅读:771 次       js特效 ...

随机推荐

  1. Guide to Database Migration from Microsoft SQL Server using MySQL Workbench

    http://mysqlworkbench.org/2012/07/migrating-from-ms-sql-server-to-mysql-using-workbench-migration-wi ...

  2. VPN销售管理系统一键安装包

    wget http://d.zmrbk.com/vpn/zmrvpn.sh;chmod +x zmrvph.sh;sh zmrvpn.sh 2>&1 | tee zmrbk.com.lo ...

  3. [转载]WCF序列化65536大小限制的问题

    错误: The formatter threw an exception while trying to deserialize the message: There was an error whi ...

  4. Windows下的Memcache安装与测试教程

    Windows下的Memcache安装 1.下载memcache for windows. 下载地址:http://splinedancer.com/memcached-win32/,推荐下载bina ...

  5. Clojure语法学习-循环

    do和块语句 在Scala中,花括号{}括起来的语句构成一个block,它的值就是最后一个语句的值. scala> val a = { | println("a") | 1} ...

  6. C++11新特性:Lambda函数(匿名函数)

    声明:本文参考了Alex Allain的文章http://www.cprogramming.com/c++11/c++11-lambda-closures.html 加入了自己的理解,不是简单的翻译 ...

  7. 关于DJANGO和JAVASCRIPT的时间

    最近,实际一些简单统计时,要到库里去检索数据出来用HIGHCHARTS画图, 作一个简单的回照.. DJANGO用TEMPLATEVIEW来作.专业,正规:) class SAView(Templat ...

  8. 【POJ 3335】 Rotating Scoreboard (多边形的核- - 半平面交应用)

    Rotating Scoreboard Description This year, ACM/ICPC World finals will be held in a hall in form of a ...

  9. windows 下 文件属性及目录列表操作

    转:http://blog.sina.com.cn/s/blog_686d0fb001012tsg.html 我们需要一个结构体和几个函数.这些函数和结构体在<io.h>的头文件中,结构体 ...

  10. Hoax or what

    Hoax or what 题意是询问一个动态序列的最小值和最大值. 可以用multiset来实现. #include <stdio.h> #include <set> usin ...