android service 组件

简介:
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.  
  3. package com.amaker.ch07.app;  
  4.  
  5. import com.amaker.ch07.app.R;  
  6.  
  7. import android.app.Activity;  
  8. import android.app.Service;  
  9. import android.content.ComponentName;  
  10. import android.content.Intent;  
  11. import android.content.ServiceConnection;  
  12. import android.os.Bundle;  
  13. import android.os.IBinder;  
  14. import android.util.Log;  
  15. import android.view.View;  
  16. import android.view.View.OnClickListener;  
  17. import android.widget.Button;  
  18. import android.widget.Toast;  
  19.  
  20. /**  
  21.  * 测试Service  
  22.  */ 
  23.  
  24. public class MainActivity extends Activity {  
  25.     // 声明Button  
  26.     private Button startBtn,stopBtn,bindBtn,unbindBtn;  
  27.     @Override  
  28.     public void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         // 设置当前布局视图  
  31.         setContentView(R.layout.main);  
  32.         // 实例化Button  
  33.         startBtn = (Button)findViewById(R.id.startButton01);  
  34.         stopBtn = (Button)findViewById(R.id.stopButton02);  
  35.         bindBtn = (Button)findViewById(R.id.bindButton03);  
  36.         unbindBtn = (Button)findViewById(R.id.unbindButton04);  
  37.           
  38.         // 添加监听器  
  39.         startBtn.setOnClickListener(startListener);  
  40.         stopBtn.setOnClickListener(stopListener);  
  41.         bindBtn.setOnClickListener(bindListener);  
  42.         unbindBtn.setOnClickListener(unBindListener);  
  43.           
  44.     }  
  45.     // 启动Service监听器  
  46.     private OnClickListener startListener = new OnClickListener() {  
  47.         @Override  
  48.         public void onClick(View v) {  
  49.             // 创建Intent  
  50.             Intent intent = new Intent();  
  51.             // 设置Action属性  
  52.             intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");  
  53.             // 启动该Service  
  54.             startService(intent);  
  55.         }  
  56.     };  
  57.       
  58.     // 停止Service监听器  
  59.     private OnClickListener stopListener = new OnClickListener() {  
  60.         @Override  
  61.         public void onClick(View v) {  
  62.             // 创建Intent  
  63.             Intent intent = new Intent();  
  64.             // 设置Action属性  
  65.             intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");  
  66.             // 启动该Service  
  67.             stopService(intent);  
  68.         }  
  69.     };  
  70.       
  71.    // 连接对象  
  72.    private ServiceConnection conn = new ServiceConnection() {  
  73.         @Override  
  74.         public void onServiceConnected(ComponentName name, IBinder service) {  
  75.             Log.i("SERVICE""连接成功!");  
  76.             Toast.makeText(MainActivity.this, "连接成功!", Toast.LENGTH_LONG).show();  
  77.         }  
  78.         @Override  
  79.         public void onServiceDisconnected(ComponentName name) {  
  80.             Log.i("SERVICE""断开连接!");  
  81.             Toast.makeText(MainActivity.this, "断开连接!", Toast.LENGTH_LONG).show();  
  82.         }  
  83.     };  
  84.       
  85.     // 綁定Service监听器  
  86.     private OnClickListener bindListener = new OnClickListener() {  
  87.         @Override  
  88.         public void onClick(View v) {  
  89.             // 创建Intent  
  90.             Intent intent = new Intent();  
  91.             // 设置Action属性  
  92.             intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");  
  93.            
  94.             // 绑定Service  
  95.             bindService(intent, conn, Service.BIND_AUTO_CREATE);  
  96.         }  
  97.     };  
  98.       
  99.       
  100.     // 解除绑定Service监听器  
  101.     private OnClickListener unBindListener = new OnClickListener() {  
  102.         @Override  
  103.         public void onClick(View v) {  
  104.             // 创建Intent  
  105.             Intent intent = new Intent();  
  106.             // 设置Action属性  
  107.             intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");  
  108.             // 解除绑定Service  
  109.             unbindService(conn);  
  110.         }  
  111.     };  
  112.       

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

 

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

布局文件

/Chapter07_Service_Example/res/layout/main.xml

 

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

清单文件

/Chapter07_Service_Example/AndroidManifest.xml

 

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

实例二、远程service调用

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

 

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

 

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

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

 

 
  1. 代码  
  2.  
  3. package com.amaker.ch07.app;  
  4.  
  5. import android.app.Service;  
  6. import android.content.Intent;  
  7. import android.os.IBinder;  
  8.  
  9. import com.amaker.ch07.app.IPerson.Stub;  
  10.  
  11. /**  
  12.  * 使用Service将接口暴露给客户端  
  13.  */ 
  14. public class MyRemoteService extends Service{  
  15.     // 声明IPerson接口  
  16.     private Stub iPerson = new IPersonImpl();  
  17.     @Override 
  18.     public IBinder onBind(Intent intent) {  
  19.         return iPerson;  
  20.     }  

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

 

 
  1. 代码  
  2.  
  3. package com.amaker.ch07.app;  
  4.  
  5. import com.amaker.ch07.app.IPerson;  
  6.  
  7. import android.os.RemoteException;  
  8. /**  
  9.  *   
  10.  * IPerson接口实现类  
  11.  */ 
  12. public class IPersonImpl extends IPerson.Stub{  
  13.     // 声明两个变量  
  14.     private int age;  
  15.     private String name;  
  16.     @Override 
  17.     // 显示name和age  
  18.     public String display() throws RemoteException {  
  19.         return "name:"+name+";age="+age;  
  20.     }  
  21.     @Override 
  22.     // 设置age  
  23.     public void setAge(int age) throws RemoteException {  
  24.         this.age = age;  
  25.     }  
  26.     @Override 
  27.     // 设置name  
  28.     public void setName(String name) throws RemoteException {  
  29.         this.name = name;  
  30.     }  

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

 

 
  1. package com.amaker.ch07.app;  
  2.  
  3. interface IPerson {  
  4.     void setAge(int age);  
  5.     void setName(String name);  
  6.     String display();  

布局文件

/Chapter07_Service_Remote/res/layout/main.xml

 

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

清单文件

/Chapter07_Service_Remote/AndroidManifest.xml

 

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

 

本文转自linzheng 51CTO博客,原文链接:http://blog.51cto.com/linzheng/1080655



相关文章
|
2月前
|
设计模式 Android开发
[Android 四大组件] --- BroadcastReceiver
[Android 四大组件] --- BroadcastReceiver
33 0
|
3月前
|
Android开发 开发者
什么是Android Jetpack,它包括哪些组件?
什么是Android Jetpack,它包括哪些组件?
39 0
|
4月前
|
数据库 Android开发
Android Studio开发之应用组件Application的讲解及实战(附源码,通过图书管理信息系统实战)
Android Studio开发之应用组件Application的讲解及实战(附源码,通过图书管理信息系统实战)
49 0
|
4月前
|
XML Java Android开发
Android Studio开发之使用内容组件Content获取通讯信息讲解及实战(附源码 包括添加手机联系人和发短信)
Android Studio开发之使用内容组件Content获取通讯信息讲解及实战(附源码 包括添加手机联系人和发短信)
72 0
|
4月前
|
XML Java Android开发
Android Studio App开发之服务Service的讲解及实战(包括启动和停止,绑定与解绑,推送服务到前台实现音乐播放器,附源码)
Android Studio App开发之服务Service的讲解及实战(包括启动和停止,绑定与解绑,推送服务到前台实现音乐播放器,附源码)
98 0
|
2月前
|
数据可视化 Android开发
[Android 四大组件] --- Service
[Android 四大组件] --- Service
24 0
|
2月前
|
Android开发
[Android 四大组件] --- Activity
[Android 四大组件] --- Activity
22 1
|
2月前
|
存储 数据库 Android开发
安卓四大组件是什么?
安卓四大组件是什么?
|
3月前
|
数据库 Android开发 开发者
Android基础知识:什么是Android应用的四大组件?
Android基础知识:什么是Android应用的四大组件?
59 1
|
4月前
|
XML 安全 Java
Android Studio App开发之广播组件Broadcast的讲解及实战(包括收发标准、有序、静态广播实现手机震动功能 附源码)
Android Studio App开发之广播组件Broadcast的讲解及实战(包括收发标准、有序、静态广播实现手机震动功能 附源码)
37 0