android service 组件
16lz
2021-01-25
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
- 代码
- packagecom.amaker.ch07.app;
- importcom.amaker.ch07.app.R;
- importandroid.app.Activity;
- importandroid.app.Service;
- importandroid.content.ComponentName;
- importandroid.content.Intent;
- importandroid.content.ServiceConnection;
- importandroid.os.Bundle;
- importandroid.os.IBinder;
- importandroid.util.Log;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.Button;
- importandroid.widget.Toast;
- /**
- *测试Service
- */
- publicclassMainActivityextendsActivity{
- //声明Button
- privateButtonstartBtn,stopBtn,bindBtn,unbindBtn;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- //设置当前布局视图
- setContentView(R.layout.main);
- //实例化Button
- startBtn=(Button)findViewById(R.id.startButton01);
- stopBtn=(Button)findViewById(R.id.stopButton02);
- bindBtn=(Button)findViewById(R.id.bindButton03);
- unbindBtn=(Button)findViewById(R.id.unbindButton04);
- //添加监听器
- startBtn.setOnClickListener(startListener);
- stopBtn.setOnClickListener(stopListener);
- bindBtn.setOnClickListener(bindListener);
- unbindBtn.setOnClickListener(unBindListener);
- }
- //启动Service监听器
- privateOnClickListenerstartListener=newOnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- //创建Intent
- Intentintent=newIntent();
- //设置Action属性
- intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");
- //启动该Service
- startService(intent);
- }
- };
- //停止Service监听器
- privateOnClickListenerstopListener=newOnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- //创建Intent
- Intentintent=newIntent();
- //设置Action属性
- intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");
- //启动该Service
- stopService(intent);
- }
- };
- //连接对象
- privateServiceConnectionconn=newServiceConnection(){
- @Override
- publicvoidonServiceConnected(ComponentNamename,IBinderservice){
- Log.i("SERVICE","连接成功!");
- Toast.makeText(MainActivity.this,"连接成功!",Toast.LENGTH_LONG).show();
- }
- @Override
- publicvoidonServiceDisconnected(ComponentNamename){
- Log.i("SERVICE","断开连接!");
- Toast.makeText(MainActivity.this,"断开连接!",Toast.LENGTH_LONG).show();
- }
- };
- //�定Service监听器
- privateOnClickListenerbindListener=newOnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- //创建Intent
- Intentintent=newIntent();
- //设置Action属性
- intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");
- //绑定Service
- bindService(intent,conn,Service.BIND_AUTO_CREATE);
- }
- };
- //解除绑定Service监听器
- privateOnClickListenerunBindListener=newOnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- //创建Intent
- Intentintent=newIntent();
- //设置Action属性
- intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");
- //解除绑定Service
- unbindService(conn);
- }
- };
- }
/Chapter07_Service_Example/src/com/amaker/ch07/app/MyService.java
- 代码
- packagecom.amaker.ch07.app;
- importandroid.app.Service;
- importandroid.content.Intent;
- importandroid.os.IBinder;
- importandroid.util.Log;
- importandroid.widget.Toast;
- /**
- *测试Service
- */
- publicclassMyServiceextendsService{
- //可以返回null,通常返回一个有aidl定义的接口
- publicIBinderonBind(Intentintent){
- Log.i("SERVICE","onBind..............");
- Toast.makeText(MyService.this,"onBind..............",Toast.LENGTH_LONG).show();
- returnnull;
- }
- //Service创建时调用
- publicvoidonCreate(){
- Log.i("SERVICE","onCreate..............");
- Toast.makeText(MyService.this,"onCreate..............",Toast.LENGTH_LONG).show();
- }
- //当客户端调用startService()方法启动Service时,该方法被调用
- publicvoidonStart(Intentintent,intstartId){
- Log.i("SERVICE","onStart..............");
- Toast.makeText(MyService.this,"onStart..............",Toast.LENGTH_LONG).show();
- }
- //当Service不再使用时调用
- publicvoidonDestroy(){
- Log.i("SERVICE","onDestroy..............");
- Toast.makeText(MyService.this,"onDestroy..............",Toast.LENGTH_LONG).show();
- }
- }
布局文件
/Chapter07_Service_Example/res/layout/main.xml
- 代码
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <Button
- android:text="启动Service"
- android:id="@+id/startButton01"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"></Button>
- <Button
- android:text="停止Service"
- android:id="@+id/stopButton02"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"></Button>
- <Button
- android:text="绑定Service"
- android:id="@+id/bindButton03"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"></Button>
- <Button
- android:text="解除绑定"
- android:id="@+id/unbindButton04"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"></Button>
- </LinearLayout>
清单文件
/Chapter07_Service_Example/AndroidManifest.xml
- 代码
- <?xmlversion="1.0"encoding="utf-8"?>
- <manifestxmlns:android="http://schemas.android.com/apk/res/android"
- package="com.amaker.ch07.app"
- android:versionCode="1"
- android:versionName="1.0">
- <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
- <activityandroid:name=".MainActivity"
- android:label="@string/app_name">
- <intent-filter>
- <actionandroid:name="android.intent.action.MAIN"/>
- <categoryandroid:name="android.intent.category.LAUNCHER"/>
- </intent-filter>
- </activity>
- <serviceandroid:name="MyService">
- <intent-filter>
- <actionandroid:name="com.amaker.ch07.app.action.MY_SERVICE"/>
- </intent-filter>
- </service>
- </application>
- <uses-sdkandroid:minSdkVersion="3"/>
- </manifest>
实例二、远程service调用
实现方式RPC(remote procedures call)远程进程调用 (android interface definition)接口定义语言
/Chapter07_Service_Remote/src/com/amaker/ch07/app/MainActivity.java
- 代码
- packagecom.amaker.ch07.app;
- importcom.amaker.ch07.app.IPerson;
- importcom.amaker.ch07.app.R;
- importandroid.app.Activity;
- importandroid.app.Service;
- importandroid.content.ComponentName;
- importandroid.content.Intent;
- importandroid.content.ServiceConnection;
- importandroid.os.Bundle;
- importandroid.os.IBinder;
- importandroid.os.RemoteException;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.Button;
- importandroid.widget.Toast;
- /**
- *
- *RPC测试
- */
- publicclassMainActivityextendsActivity{
- //声明IPerson接口
- privateIPersoniPerson;
- //声明Button
- privateButtonbtn;
- //实例化ServiceConnection
- privateServiceConnectionconn=newServiceConnection(){
- @Override
- synchronizedpublicvoidonServiceConnected(ComponentNamename,IBinderservice){
- //获得IPerson接口
- iPerson=IPerson.Stub.asInterface(service);
- if(iPerson!=null)
- try{
- //RPC方法调用
- iPerson.setName("hz.guo");
- iPerson.setAge(30);
- Stringmsg=iPerson.display();
- //显示方法调用返回值
- Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG)
- .show();
- }catch(RemoteExceptione){
- e.printStackTrace();
- }
- }
- @Override
- publicvoidonServiceDisconnected(ComponentNamename){
- }
- };
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- //设置当前视图布局
- setContentView(R.layout.main);
- //实例化Button
- btn=(Button)findViewById(R.id.Button01);
- //为Button添加单击事件监听器
- btn.setOnClickListener(newOnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- //实例化Intent
- Intentintent=newIntent();
- //设置IntentAction属性
- intent
- .setAction("com.amaker.ch09.app.action.MY_REMOTE_SERVICE");
- //绑定服务
- bindService(intent,conn,Service.BIND_AUTO_CREATE);
- }
- });
- }
- }
/Chapter07_Service_Remote/src/com/amaker/ch07/app/MyRemoteService.java
- 代码
- packagecom.amaker.ch07.app;
- importandroid.app.Service;
- importandroid.content.Intent;
- importandroid.os.IBinder;
- importcom.amaker.ch07.app.IPerson.Stub;
- /**
- *使用Service将接口暴露给客户端
- */
- publicclassMyRemoteServiceextendsService{
- //声明IPerson接口
- privateStubiPerson=newIPersonImpl();
- @Override
- publicIBinderonBind(Intentintent){
- returniPerson;
- }
- }
/Chapter07_Service_Remote/src/com/amaker/ch07/app/IPersonImpl.java
- 代码
- packagecom.amaker.ch07.app;
- importcom.amaker.ch07.app.IPerson;
- importandroid.os.RemoteException;
- /**
- *
- *IPerson接口实现类
- */
- publicclassIPersonImplextendsIPerson.Stub{
- //声明两个变量
- privateintage;
- privateStringname;
- @Override
- //显示name和age
- publicStringdisplay()throwsRemoteException{
- return"name:"+name+";age="+age;
- }
- @Override
- //设置age
- publicvoidsetAge(intage)throwsRemoteException{
- this.age=age;
- }
- @Override
- //设置name
- publicvoidsetName(Stringname)throwsRemoteException{
- this.name=name;
- }
- }
/Chapter07_Service_Remote/src/com/amaker/ch07/app/IPerson.aidl
- packagecom.amaker.ch07.app;
- interfaceIPerson{
- voidsetAge(intage);
- voidsetName(Stringname);
- Stringdisplay();
- }
布局文件
/Chapter07_Service_Remote/res/layout/main.xml
- 代码
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <Button
- android:text="测试远程Service"
- android:id="@+id/Button01"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"></Button>
- </LinearLayout>
清单文件
/Chapter07_Service_Remote/AndroidManifest.xml
- 代码
- <?xmlversion="1.0"encoding="utf-8"?>
- <manifestxmlns:android="http://schemas.android.com/apk/res/android"
- package="com.amaker.ch07.app"
- android:versionCode="1"
- android:versionName="1.0">
- <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
- <activityandroid:name=".MainActivity"
- android:label="@string/app_name">
- <intent-filter>
- <actionandroid:name="android.intent.action.MAIN"/>
- <categoryandroid:name="android.intent.category.LAUNCHER"/>
- </intent-filter>
- </activity>
- <serviceandroid:name="MyRemoteService">
- <intent-filter>
- <actionandroid:name="com.amaker.ch07.app.action.MY_REMOTE_SERVICE"/>
- </intent-filter>
- </service>
- </application>
- <uses-sdkandroid:minSdkVersion="3"/>
- </manifest>
更多相关文章
- 实现Unity和Android进行交互
- Android(安卓)2D画图类Path精炼详解
- Android(安卓)用户界面---菜单(Menus 一)
- Android控件系列之Button以及Android监听器
- 踏破铁鞋无觅处,从 AsyncTask 学 Android(安卓)线程池
- Java采用JNI调用VC++生成的dll(Java与C++交互)
- Android中的绘制机制
- Android(安卓)SurfaceFlinger VSync流程分析
- Android(安卓)两个Fragment之间的跳转和数据的传递实例详解