Service 概念及用途 : Android中的服务,它与Activity不同,它是不能与用户交互的,不能自己启动的,运行在后台的程序,如果我们退出应用时,Service进程并没有结束,它仍然在后台运行,那 我们什么时候会用到Service呢?比如我们播放音乐的时候,有可能想边听音乐边干些其他事情,当我们退出播放音乐的应用,如果不用Service,我 们就听不到歌了,所以这时候就得用到Service了,又比如当我们一个应用的数据是通过网络获取的,不同时间(一段时间)的数据是不同的这时候我们可以 用Service在后台定时更新,而不用每打开应用的时候在去获取。 Service 生命周期 : Android Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当我们第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法,具体的可以看下面的实例。 Service Activity 通信 : Service后端的数据最终还是要呈现在前端Activity之上的,因为启动Service时,系统会重新开启一个新的进程,这就涉及到不同进程间通信的问题了(AIDL)这一节我不作过多描述,当我们想获取启动的Service实例时,我们可以用到bindService和onBindService方法,它们分别执行了Service中IBinder()和onUnbind()方法。 Service的类型

Service有两种类型: 1. 本地服务(Local Service):用于应用程序内部 2. 远程服务(Remote Sercie):用于android系统内部的应用程序之间 前者用于实现应用程序自己的一些耗时任务,比如查询升级信息,并不占用应用程序比如Activity所属线程,而是单开线程后台执行,这样用户体验比较好。 后者可被其他应用程序复用,比如天气预报服务,其他应用程序不需要再写这样的服务,调用已有的即可。 实例一 演示如何创建、启动、停止及绑定一个service 程序文件 /Chapter07_Service_Example/src/com/amaker/ch07/app/MainActivity.java
        
  1. 代码
  2. packagecom.amaker.ch07.app;
  3. importcom.amaker.ch07.app.R;
  4. importandroid.app.Activity;
  5. importandroid.app.Service;
  6. importandroid.content.ComponentName;
  7. importandroid.content.Intent;
  8. importandroid.content.ServiceConnection;
  9. importandroid.os.Bundle;
  10. importandroid.os.IBinder;
  11. importandroid.util.Log;
  12. importandroid.view.View;
  13. importandroid.view.View.OnClickListener;
  14. importandroid.widget.Button;
  15. importandroid.widget.Toast;
  16. /**
  17. *测试Service
  18. */
  19. publicclassMainActivityextendsActivity{
  20. //声明Button
  21. privateButtonstartBtn,stopBtn,bindBtn,unbindBtn;
  22. @Override
  23. publicvoidonCreate(BundlesavedInstanceState){
  24. super.onCreate(savedInstanceState);
  25. //设置当前布局视图
  26. setContentView(R.layout.main);
  27. //实例化Button
  28. startBtn=(Button)findViewById(R.id.startButton01);
  29. stopBtn=(Button)findViewById(R.id.stopButton02);
  30. bindBtn=(Button)findViewById(R.id.bindButton03);
  31. unbindBtn=(Button)findViewById(R.id.unbindButton04);
  32. //添加监听器
  33. startBtn.setOnClickListener(startListener);
  34. stopBtn.setOnClickListener(stopListener);
  35. bindBtn.setOnClickListener(bindListener);
  36. unbindBtn.setOnClickListener(unBindListener);
  37. }
  38. //启动Service监听器
  39. privateOnClickListenerstartListener=newOnClickListener(){
  40. @Override
  41. publicvoidonClick(Viewv){
  42. //创建Intent
  43. Intentintent=newIntent();
  44. //设置Action属性
  45. intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");
  46. //启动该Service
  47. startService(intent);
  48. }
  49. };
  50. //停止Service监听器
  51. privateOnClickListenerstopListener=newOnClickListener(){
  52. @Override
  53. publicvoidonClick(Viewv){
  54. //创建Intent
  55. Intentintent=newIntent();
  56. //设置Action属性
  57. intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");
  58. //启动该Service
  59. stopService(intent);
  60. }
  61. };
  62. //连接对象
  63. privateServiceConnectionconn=newServiceConnection(){
  64. @Override
  65. publicvoidonServiceConnected(ComponentNamename,IBinderservice){
  66. Log.i("SERVICE","连接成功!");
  67. Toast.makeText(MainActivity.this,"连接成功!",Toast.LENGTH_LONG).show();
  68. }
  69. @Override
  70. publicvoidonServiceDisconnected(ComponentNamename){
  71. Log.i("SERVICE","断开连接!");
  72. Toast.makeText(MainActivity.this,"断开连接!",Toast.LENGTH_LONG).show();
  73. }
  74. };
  75. //�定Service监听器
  76. privateOnClickListenerbindListener=newOnClickListener(){
  77. @Override
  78. publicvoidonClick(Viewv){
  79. //创建Intent
  80. Intentintent=newIntent();
  81. //设置Action属性
  82. intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");
  83. //绑定Service
  84. bindService(intent,conn,Service.BIND_AUTO_CREATE);
  85. }
  86. };
  87. //解除绑定Service监听器
  88. privateOnClickListenerunBindListener=newOnClickListener(){
  89. @Override
  90. publicvoidonClick(Viewv){
  91. //创建Intent
  92. Intentintent=newIntent();
  93. //设置Action属性
  94. intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");
  95. //解除绑定Service
  96. unbindService(conn);
  97. }
  98. };
  99. }

/Chapter07_Service_Example/src/com/amaker/ch07/app/MyService.java

        
  1. 代码
  2. packagecom.amaker.ch07.app;
  3. importandroid.app.Service;
  4. importandroid.content.Intent;
  5. importandroid.os.IBinder;
  6. importandroid.util.Log;
  7. importandroid.widget.Toast;
  8. /**
  9. *测试Service
  10. */
  11. publicclassMyServiceextendsService{
  12. //可以返回null,通常返回一个有aidl定义的接口
  13. publicIBinderonBind(Intentintent){
  14. Log.i("SERVICE","onBind..............");
  15. Toast.makeText(MyService.this,"onBind..............",Toast.LENGTH_LONG).show();
  16. returnnull;
  17. }
  18. //Service创建时调用
  19. publicvoidonCreate(){
  20. Log.i("SERVICE","onCreate..............");
  21. Toast.makeText(MyService.this,"onCreate..............",Toast.LENGTH_LONG).show();
  22. }
  23. //当客户端调用startService()方法启动Service时,该方法被调用
  24. publicvoidonStart(Intentintent,intstartId){
  25. Log.i("SERVICE","onStart..............");
  26. Toast.makeText(MyService.this,"onStart..............",Toast.LENGTH_LONG).show();
  27. }
  28. //当Service不再使用时调用
  29. publicvoidonDestroy(){
  30. Log.i("SERVICE","onDestroy..............");
  31. Toast.makeText(MyService.this,"onDestroy..............",Toast.LENGTH_LONG).show();
  32. }
  33. }

布局文件

/Chapter07_Service_Example/res/layout/main.xml

        
  1. 代码
  2. <?xmlversion="1.0"encoding="utf-8"?>
  3. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  4. android:orientation="vertical"
  5. android:layout_width="fill_parent"
  6. android:layout_height="fill_parent"
  7. >
  8. <Button
  9. android:text="启动Service"
  10. android:id="@+id/startButton01"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"></Button>
  13. <Button
  14. android:text="停止Service"
  15. android:id="@+id/stopButton02"
  16. android:layout_width="wrap_content"
  17. android:layout_height="wrap_content"></Button>
  18. <Button
  19. android:text="绑定Service"
  20. android:id="@+id/bindButton03"
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"></Button>
  23. <Button
  24. android:text="解除绑定"
  25. android:id="@+id/unbindButton04"
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"></Button>
  28. </LinearLayout>

清单文件

/Chapter07_Service_Example/AndroidManifest.xml

        
  1. 代码
  2. <?xmlversion="1.0"encoding="utf-8"?>
  3. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  4. package="com.amaker.ch07.app"
  5. android:versionCode="1"
  6. android:versionName="1.0">
  7. <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
  8. <activityandroid:name=".MainActivity"
  9. android:label="@string/app_name">
  10. <intent-filter>
  11. <actionandroid:name="android.intent.action.MAIN"/>
  12. <categoryandroid:name="android.intent.category.LAUNCHER"/>
  13. </intent-filter>
  14. </activity>
  15. <serviceandroid:name="MyService">
  16. <intent-filter>
  17. <actionandroid:name="com.amaker.ch07.app.action.MY_SERVICE"/>
  18. </intent-filter>
  19. </service>
  20. </application>
  21. <uses-sdkandroid:minSdkVersion="3"/>
  22. </manifest>

实例二、远程service调用

实现方式RPC(remote procedures call)远程进程调用 (android interface definition)接口定义语言

/Chapter07_Service_Remote/src/com/amaker/ch07/app/MainActivity.java

        
  1. 代码
  2. packagecom.amaker.ch07.app;
  3. importcom.amaker.ch07.app.IPerson;
  4. importcom.amaker.ch07.app.R;
  5. importandroid.app.Activity;
  6. importandroid.app.Service;
  7. importandroid.content.ComponentName;
  8. importandroid.content.Intent;
  9. importandroid.content.ServiceConnection;
  10. importandroid.os.Bundle;
  11. importandroid.os.IBinder;
  12. importandroid.os.RemoteException;
  13. importandroid.view.View;
  14. importandroid.view.View.OnClickListener;
  15. importandroid.widget.Button;
  16. importandroid.widget.Toast;
  17. /**
  18. *
  19. *RPC测试
  20. */
  21. publicclassMainActivityextendsActivity{
  22. //声明IPerson接口
  23. privateIPersoniPerson;
  24. //声明Button
  25. privateButtonbtn;
  26. //实例化ServiceConnection
  27. privateServiceConnectionconn=newServiceConnection(){
  28. @Override
  29. synchronizedpublicvoidonServiceConnected(ComponentNamename,IBinderservice){
  30. //获得IPerson接口
  31. iPerson=IPerson.Stub.asInterface(service);
  32. if(iPerson!=null)
  33. try{
  34. //RPC方法调用
  35. iPerson.setName("hz.guo");
  36. iPerson.setAge(30);
  37. Stringmsg=iPerson.display();
  38. //显示方法调用返回值
  39. Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG)
  40. .show();
  41. }catch(RemoteExceptione){
  42. e.printStackTrace();
  43. }
  44. }
  45. @Override
  46. publicvoidonServiceDisconnected(ComponentNamename){
  47. }
  48. };
  49. @Override
  50. publicvoidonCreate(BundlesavedInstanceState){
  51. super.onCreate(savedInstanceState);
  52. //设置当前视图布局
  53. setContentView(R.layout.main);
  54. //实例化Button
  55. btn=(Button)findViewById(R.id.Button01);
  56. //为Button添加单击事件监听器
  57. btn.setOnClickListener(newOnClickListener(){
  58. @Override
  59. publicvoidonClick(Viewv){
  60. //实例化Intent
  61. Intentintent=newIntent();
  62. //设置IntentAction属性
  63. intent
  64. .setAction("com.amaker.ch09.app.action.MY_REMOTE_SERVICE");
  65. //绑定服务
  66. bindService(intent,conn,Service.BIND_AUTO_CREATE);
  67. }
  68. });
  69. }
  70. }

/Chapter07_Service_Remote/src/com/amaker/ch07/app/MyRemoteService.java

        
  1. 代码
  2. packagecom.amaker.ch07.app;
  3. importandroid.app.Service;
  4. importandroid.content.Intent;
  5. importandroid.os.IBinder;
  6. importcom.amaker.ch07.app.IPerson.Stub;
  7. /**
  8. *使用Service将接口暴露给客户端
  9. */
  10. publicclassMyRemoteServiceextendsService{
  11. //声明IPerson接口
  12. privateStubiPerson=newIPersonImpl();
  13. @Override
  14. publicIBinderonBind(Intentintent){
  15. returniPerson;
  16. }
  17. }

/Chapter07_Service_Remote/src/com/amaker/ch07/app/IPersonImpl.java

        
  1. 代码
  2. packagecom.amaker.ch07.app;
  3. importcom.amaker.ch07.app.IPerson;
  4. importandroid.os.RemoteException;
  5. /**
  6. *
  7. *IPerson接口实现类
  8. */
  9. publicclassIPersonImplextendsIPerson.Stub{
  10. //声明两个变量
  11. privateintage;
  12. privateStringname;
  13. @Override
  14. //显示name和age
  15. publicStringdisplay()throwsRemoteException{
  16. return"name:"+name+";age="+age;
  17. }
  18. @Override
  19. //设置age
  20. publicvoidsetAge(intage)throwsRemoteException{
  21. this.age=age;
  22. }
  23. @Override
  24. //设置name
  25. publicvoidsetName(Stringname)throwsRemoteException{
  26. this.name=name;
  27. }
  28. }

/Chapter07_Service_Remote/src/com/amaker/ch07/app/IPerson.aidl

        
  1. packagecom.amaker.ch07.app;
  2. interfaceIPerson{
  3. voidsetAge(intage);
  4. voidsetName(Stringname);
  5. Stringdisplay();
  6. }

布局文件

/Chapter07_Service_Remote/res/layout/main.xml

        
  1. 代码
  2. <?xmlversion="1.0"encoding="utf-8"?>
  3. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  4. android:orientation="vertical"
  5. android:layout_width="fill_parent"
  6. android:layout_height="fill_parent"
  7. >
  8. <Button
  9. android:text="测试远程Service"
  10. android:id="@+id/Button01"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"></Button>
  13. </LinearLayout>

清单文件

/Chapter07_Service_Remote/AndroidManifest.xml

        
  1. 代码
  2. <?xmlversion="1.0"encoding="utf-8"?>
  3. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  4. package="com.amaker.ch07.app"
  5. android:versionCode="1"
  6. android:versionName="1.0">
  7. <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
  8. <activityandroid:name=".MainActivity"
  9. android:label="@string/app_name">
  10. <intent-filter>
  11. <actionandroid:name="android.intent.action.MAIN"/>
  12. <categoryandroid:name="android.intent.category.LAUNCHER"/>
  13. </intent-filter>
  14. </activity>
  15. <serviceandroid:name="MyRemoteService">
  16. <intent-filter>
  17. <actionandroid:name="com.amaker.ch07.app.action.MY_REMOTE_SERVICE"/>
  18. </intent-filter>
  19. </service>
  20. </application>
  21. <uses-sdkandroid:minSdkVersion="3"/>
  22. </manifest>

更多相关文章

  1. 实现Unity和Android进行交互
  2. Android(安卓)2D画图类Path精炼详解
  3. Android(安卓)用户界面---菜单(Menus 一)
  4. Android控件系列之Button以及Android监听器
  5. 踏破铁鞋无觅处,从 AsyncTask 学 Android(安卓)线程池
  6. Java采用JNI调用VC++生成的dll(Java与C++交互)
  7. Android中的绘制机制
  8. Android(安卓)SurfaceFlinger VSync流程分析
  9. Android(安卓)两个Fragment之间的跳转和数据的传递实例详解

随机推荐

  1. MAC下修改mysql默认字符集为utf8的方法
  2. my.cnf(my.ini)重要参数优化配置说明
  3. MySql优化之InnoDB,4GB内存,多查询的my.i
  4. MySQL性能全面优化方法参考,从CPU,文件系
  5. Mysql5.7中使用group concat函数数据被截
  6. MySQL常见内存不足启动失败的完美解决方
  7. linux下mysql的安装步骤
  8. Mac环境mysql5.7.21 utf8编码问题及解决
  9. CentOS 7.0如何启动多个MySQL实例教程(my
  10. MySQL中count(*)、count(1)和count(col)