android的service
packagecom.service.service;importcom.example.service.R;importandroid.app.Activity;importandroid.content.ComponentName;importandroid.content.Context;importandroid.content.Intent;importandroid.content.ServiceConnection;importandroid.os.Bundle;importandroid.os.IBinder;importandroid.os.RemoteException;importandroid.view.View;importandroid.widget.Toast;/***service组件*1.定义一个类继承Service类*Service两种启动方式*<1>.start*<2>.onBind*服务对象同时只有一个*默认情况下,一个started的service与启动它的应用组件在同一线程中,*所以如果我们使用service来完成一些好使的操作任务时,就会阻塞主线程*那我们就必须在线程中来处理耗时任务*停止一个服务的两种方法*<1>.在外部使用stopService()*<2>.在服务类内部使用stopSelf()**IntentService*该类型的service会在单独的线程中执行任务,任务完成后会自动结束service*当我们有需要这样一次性完成的任务就可以使用IntentService来完成****IPC(进程间的通讯)*AIDL(android接口定义语言)*使用aidl定义业务接口,通过ADT工具来生成一个java类,此类实现了进程间远程通讯的代理*编写自己的业务类(继承生成的类中的stub存根)来实现业务接口*再通过绑定service的方式来暴露此业务对象给其他组件提供功能**调用者组件通过servuce方法绑定服务,从而可以获取绑定成功后的远程业务对象或本地对象*可以调用相关的功能*注意:一般在使用完绑定服务后,需要解除绑定**自定义AIDL对象*1.需要自自定义的类型上实现Parcelable接口*2.需要定义一个aidl文件来申明自定义类型(在student。aidl文件中申明parcelableStudent;)*3.在使用该自定义类型时必须使用import语句导入该自定义类型,否则报错****使用started与bing服务之间的区别*使用started会一直运行在后台,需要服务本身或外部组件停止服务才会结束运行*通过bind的服务,它的生命周期依赖绑定的组件,*1.started服务可以给启动的对象传递参数,但无法获取服务中的方法返回*2.可以给启动的服务对象传递参数,也可以通过绑定的业务对象获取返回结果*在实际应用中的使用技巧*1.第一次先使用started来启动一个服务,*之后可以使用绑定的方式绑定服务,从而可以直接调用业务方法返回值**/publicclassMainActivityextendsActivity{privateIPersonperson;//要使用的业务对象接口booleanflag=false;//服务连接对象privateServiceConnectionserviceConnection=newServiceConnection(){@OverridepublicvoidonServiceDisconnected(ComponentNamename){//TODOAuto-generatedmethodstub//当服务异常终止时会调用,注意:解除绑定服务时不会调用System.out.println("onServiceDisconnected");flag=false;}@OverridepublicvoidonServiceConnected(ComponentNamename,IBinderservice){//TODOAuto-generatedmethodstub//绑定成功后服务会回调该方法,自动传入IBinder对象System.out.println("onServiceConnected");person=IPerson.Stub.asInterface(service);System.out.println(person);}};@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}/***启动一个服务**/publicvoidstart1(Viewview){System.out.println("start1");Intentintent=newIntent(this,HelloService.class);startService(intent);}publicvoidstop(Viewview){System.out.println("stop");Intentintent=newIntent(this,HelloService.class);stopService(intent);}publicvoidstart2(Viewview){Intentintent=newIntent(this,HelloIntentService.class);startService(intent);}//绑定一个服务publicvoidbindService(Viewview){System.out.println("bindService");Intentintent=newIntent(this,MyService.class);//参数(1.intent对象,2.服务连接对象,3.绑定服务的标记)flag=bindService(intent,serviceConnection,Context.BIND_AUTO_CREATE);}//解除绑定服务publicvoidunBindService(Viewview){if(flag){unbindService(serviceConnection);flag=false;}}//调用远程业务对象方法(或是本地业务)publicvoidcallPerson(Viewview)throwsRemoteException{person.setName("张三");person.setAge(21);person.setSex("男");Strings=person.getPerson();Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();}
activity_main.xml
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context="com.service.service.MainActivity"android:orientation="vertical"><Buttonandroid:id="@+id/activity1_button1"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="启动service1"android:onClick="start1"/><Buttonandroid:id="@+id/activity1_button2"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="停止service1"android:onClick="stop"/><Buttonandroid:id="@+id/activity1_button3"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="startIntentService"android:onClick="start2"/><Buttonandroid:id="@+id/activity1_button4"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="绑定Service"android:onClick="bindService"/><Buttonandroid:id="@+id/activity1_button5"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="解绑Service"android:onClick="unBindService"/><Buttonandroid:id="@+id/activity1_callPerson"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="调用业务对象Person的方法"android:onClick="callPerson"/></LinearLayout>
HelloService
packagecom.service.service;importandroid.app.Service;importandroid.content.Intent;importandroid.os.IBinder;importandroid.util.Log;publicclassHelloServiceextendsService{privatePersonImplpersonImpl;@OverridepublicIBinderonBind(Intentintent){//TODOAuto-generatedmethodstubreturnnewPersonImpl();}//创建服务时调用@OverridepublicvoidonCreate(){//TODOAuto-generatedmethodstubsuper.onCreate();Log.i("HelloService","HelloServiceOnCreate");}//销毁服务时调用@OverridepublicvoidonDestroy(){//TODOAuto-generatedmethodstubsuper.onDestroy();Log.i("HelloService","HelloServiceONDestory");}//服务执行时的操作@OverridepublicintonStartCommand(Intentintent,intflags,intstartId){//TODOAuto-generatedmethodstubLog.i("HelloService","HelloServiceONStartCommand");System.out.println("HelloServiceONStartCommand");newThread(newRunnable(){@Overridepublicvoidrun(){//TODOAuto-generatedmethodstubinti=0;for(;i<10;i++){System.out.println(Thread.currentThread().getName()+":"+i);try{Thread.sleep(1000);}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}//HelloService.this.stopSelf();//停止服务}}).start();returnsuper.onStartCommand(intent,flags,startId);}}
IPerson.aidl文件
packagecom.service.service;interfaceIPerson{voidsetName(Stringname);voidsetSex(Stringsex);voidsetAge(intage);StringgetPerson();}
PersonImpl
packagecom.service.service;importandroid.os.RemoteException;publicclassPersonImplextendsIPerson.Stub{privateStringname;privateStringsex;privateintage;@OverridepublicvoidsetName(Stringname)throwsRemoteException{//TODOAuto-generatedmethodstubthis.name=name;}@OverridepublicvoidsetSex(Stringsex)throwsRemoteException{//TODOAuto-generatedmethodstubthis.sex=sex;}@OverridepublicvoidsetAge(intage)throwsRemoteException{//TODOAuto-generatedmethodstubthis.age=age;}@OverridepublicStringgetPerson()throwsRemoteException{//TODOAuto-generatedmethodstubreturn"name="+name+"sex="+sex+"age="+age;}}
第二种:继承IntentService
HelloIntentService
packagecom.service.service;importandroid.app.IntentService;importandroid.content.Intent;publicclassHelloIntentServiceextendsIntentService{publicHelloIntentService(){super("IntentSerice");//TODOAuto-generatedconstructorstub}//该方法会在一个单独的线程中执行,来完成工作任务//任务结束后,该service会自动停止@OverrideprotectedvoidonHandleIntent(Intentintent){//TODOAuto-generatedmethodstubfor(inti=0;i<10;i++){System.out.println(Thread.currentThread().getName()+":"+i);try{Thread.sleep(1000);}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}@OverridepublicvoidonDestroy(){//TODOAuto-generatedmethodstubsuper.onDestroy();System.out.println("OnDestory");}}
所有的service需要在清单文件中申明
<service android:name="com.service.service.HelloService"></service>
<service android:name="com.service.service.HelloIntentService"></service>
使用onBind方式
packagecom.service.service;importandroid.app.Service;importandroid.content.Intent;importandroid.os.Binder;importandroid.os.IBinder;/***实现一个绑定服务***/publicclassMyServiceextendsService{privatePersonImplpersonImpl;@OverridepublicvoidonCreate(){//TODOAuto-generatedmethodstubsuper.onCreate();System.out.println("MyServiceOnCreate()");}@OverridepublicIBinderonBind(Intentintent){//TODOAuto-generatedmethodstubSystem.out.println("MyServiceOnBind()");personImpl=newPersonImpl();returnpersonImpl;}@OverridepublicbooleanonUnbind(Intentintent){//TODOAuto-generatedmethodstubSystem.out.println("MyServiceOnUnBind()");returnsuper.onUnbind(intent);}}
自定义AIDL
IStudent.aidl
packagecom.service.service;importcom.service.service.Student;interfaceIStudent{voidsetStudnet(Stringname,Stringsex);StudentgetStudent();}
Student.aidl
parcelableStudent;
Student
packagecom.service.service;importandroid.os.Parcel;importandroid.os.Parcelable;publicclassStudentimplementsParcelable{privateStringname;privateStringsex;publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicStringgetSex(){returnsex;}publicvoidsetSex(Stringsex){this.sex=sex;}@OverridepublicintdescribeContents(){//TODOAuto-generatedmethodstubreturn0;}@OverridepublicvoidwriteToParcel(Parceldest,intflags){//TODOAuto-generatedmethodstubdest.writeString("name");dest.writeString("sex");}publicstaticfinalParcelable.Creator<Student>CREATOR=newParcelable.Creator<Student>(){publicStudentcreateFromParcel(Parcelin){Studentstudent=newStudent();student.setName(in.readString());student.setSex(in.readString());returnstudent;}publicStudent[]newArray(intsize){returnnewStudent[size];}};}
StudentImpl
packagecom.service.service;importandroid.os.RemoteException;/***业务对象的实现**/publicclassStudentImplextendsIStudent.Stub{privateStudentstudent;publicStudentImpl(){student=newStudent();}@OverridepublicvoidsetStudnet(Stringname,Stringsex)throwsRemoteException{//TODOAuto-generatedmethodstubthis.student.setName(name);;this.student.setSex(sex);}@OverridepublicStudentgetStudent()throwsRemoteException{//TODOAuto-generatedmethodstubreturnstudent;}}
StudentService
packagecom.service.service;importandroid.app.Service;importandroid.content.Intent;importandroid.os.IBinder;publicclassStudentServiceextendsService{privateStudentImplstudentImpl;@OverridepublicIBinderonBind(Intentintent){//TODOAuto-generatedmethodstubstudentImpl=newStudentImpl();returnstudentImpl;}}
使用Messenge
MessageService
packagecom.service.service;importandroid.app.Service;importandroid.content.Intent;importandroid.os.Handler;importandroid.os.IBinder;importandroid.os.Message;importandroid.os.Messenger;importandroid.widget.Toast;publicclassMessageServiceextendsService{staticfinalintMSG_HELLO=0x1;privateHandlerhandler=newHandler(){publicvoidhandleMessage(android.os.Messagemsg){switch(msg.what){caseMSG_HELLO:Toast.makeText(MessageService.this,"hello",Toast.LENGTH_SHORT).show();break;default:break;}};};privateMessengermessenger=newMessenger(handler);@OverridepublicIBinderonBind(Intentintent){//TODOAuto-generatedmethodstubreturnmessenger.getBinder();}}
MessageActivity
packagecom.service.service;importcom.example.service.R;importandroid.app.Activity;importandroid.content.ComponentName;importandroid.content.Context;importandroid.content.Intent;importandroid.content.ServiceConnection;importandroid.os.Bundle;importandroid.os.IBinder;importandroid.os.Message;importandroid.os.Messenger;importandroid.os.RemoteException;importandroid.view.View;/***使用Messenger实现IPC,*1.Messenger是线程安全的,在service中创建一个Messenger对象并绑定一个handle*2.在onBind方法中返回messenger对象,通过messenger的getIBinder方法返回一个IBinder对象*3.在调用的组件中,ServiceConnection的onServiceConnection时间中,根据IBinder对象来创建一个Messenger对象*这样两个Messenger对象就同事绑定到一个IBinder对象上,从而可以底线通信,*在调用组件中方法种使用Messenger的send方法来发送消息到service的Messenger对象中**/publicclassMessageActivityextendsActivity{privateMessengermessenger;privatebooleanmBound=false;privateServiceConnectionconn=newServiceConnection(){@OverridepublicvoidonServiceDisconnected(ComponentNamename){//TODOAuto-generatedmethodstubif(mBound){mBound=false;}}@OverridepublicvoidonServiceConnected(ComponentNamename,IBinderservice){//TODOAuto-generatedmethodstubmessenger=newMessenger(service);mBound=true;}};@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);setContentView(R.layout.message_main);}publicvoiduseMessenger(Viewview){Messagemessage=Message.obtain();message.what=MessageService.MSG_HELLO;try{messenger.send(message);}catch(RemoteExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}@OverrideprotectedvoidonStart(){//TODOAuto-generatedmethodstubsuper.onStart();Intentintent=newIntent(this,MessageService.class);bindService(intent,conn,Context.BIND_AUTO_CREATE);}@OverrideprotectedvoidonStop(){//TODOAuto-generatedmethodstubsuper.onStop();if(mBound){unbindService(conn);mBound=false;}}}
清单文件
<?xmlversion="1.0"encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.example.service"android:versionCode="1"android:versionName="1.0"><uses-sdkandroid:minSdkVersion="14"android:targetSdkVersion="21"/><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme"><activityandroid:name="com.service.service.MessageActivity"android:label="@string/app_name"><intent-filter><actionandroid:name="android.intent.action.MAIN"/><categoryandroid:name="android.intent.category.LAUNCHER"/></intent-filter></activity><serviceandroid:name="com.service.service.HelloService"></service><serviceandroid:name="com.service.service.HelloIntentService"></service><serviceandroid:name="com.service.service.MyService"android:process=":remote"></service><serviceandroid:name="com.service.service.StudentService"></service><serviceandroid:name="com.service.service.MessageService"></service></application></manifest><!--android:process=":remote"设置运行在自己的进程中-->
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。