700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 【Android】 Android Service生命周期及用法

【Android】 Android Service生命周期及用法

时间:2021-03-22 13:19:24

相关推荐

【Android】 Android Service生命周期及用法

原文来自:

首先我们要知道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()方法。

为了让大家 更容易理解,我写了一个简单的Demo,大家可以模仿着我,一步一步的来。

第一步:新建一个Android工程,我这里命名为ServiceDemo.

第二步:修改main.xml代码,我这里增加了四个按钮,代码如下:

[java]view plaincopy<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/startservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="startService" /> <Button android:id="@+id/stopservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="stopService" /> <Button android:id="@+id/bindservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="bindService" /> <Button android:id="@+id/unbindservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="unbindService" /> </LinearLayout>

第三步:新建一个Service,命名为MyService.java代码如下:

[java]view plaincopypackagecom.tutor.servicedemo; importandroid.app.Service; importandroid.content.Intent; importandroid.os.Binder; importandroid.os.IBinder; importandroid.text.format.Time; importandroid.util.Log; publicclassMyServiceextendsService{ //定义个一个Tag标签 privatestaticfinalStringTAG="MyService"; //这里定义吧一个Binder类,用在onBind()有方法里,这样Activity那边可以获取到 privateMyBindermBinder=newMyBinder(); @Override publicIBinderonBind(Intentintent){ Log.e(TAG,"startIBinder~~~"); returnmBinder; } @Override publicvoidonCreate(){ Log.e(TAG,"startonCreate~~~"); super.onCreate(); } @Override publicvoidonStart(Intentintent,intstartId){ Log.e(TAG,"startonStart~~~"); super.onStart(intent,startId); } @Override publicvoidonDestroy(){ Log.e(TAG,"startonDestroy~~~"); super.onDestroy(); } @Override publicbooleanonUnbind(Intentintent){ Log.e(TAG,"startonUnbind~~~"); returnsuper.onUnbind(intent); } //这里我写了一个获取当前时间的函数,不过没有格式化就先这么着吧 publicStringgetSystemTime(){ Timet=newTime(); t.setToNow(); returnt.toString(); } publicclassMyBinderextendsBinder{ MyServicegetService() { returnMyService.this; } } }

第四步:修改ServiceDemo.java,代码如下:

[java]view plaincopypackagecom.tutor.servicedemo; importandroid.app.Activity; ponentName; importandroid.content.Context; importandroid.content.Intent; importandroid.content.ServiceConnection; importandroid.os.Bundle; importandroid.os.IBinder; importandroid.view.View; importandroid.view.View.OnClickListener; importandroid.widget.Button; importandroid.widget.TextView; publicclassServiceDemoextendsActivityimplementsOnClickListener{ privateMyServicemMyService; privateTextViewmTextView; privateButtonstartServiceButton; privateButtonstopServiceButton; privateButtonbindServiceButton; privateButtonunbindServiceButton; privateContextmContext; //这里需要用到ServiceConnection在Context.bindService和context.unBindService()里用到 privateServiceConnectionmServiceConnection=newServiceConnection(){ //当我bindService时,让TextView显示MyService里getSystemTime()方法的返回值 publicvoidonServiceConnected(ComponentNamename,IBinderservice){ //TODOAuto-generatedmethodstub mMyService=((MyService.MyBinder)service).getService(); mTextView.setText("IamfromeService:"+mMyService.getSystemTime()); } publicvoidonServiceDisconnected(ComponentNamename){ //TODOAuto-generatedmethodstub } }; publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); setupViews(); } publicvoidsetupViews(){ mContext=ServiceDemo.this; mTextView=(TextView)findViewById(R.id.text); startServiceButton=(Button)findViewById(R.id.startservice); stopServiceButton=(Button)findViewById(R.id.stopservice); bindServiceButton=(Button)findViewById(R.id.bindservice); unbindServiceButton=(Button)findViewById(R.id.unbindservice); startServiceButton.setOnClickListener(this); stopServiceButton.setOnClickListener(this); bindServiceButton.setOnClickListener(this); unbindServiceButton.setOnClickListener(this); } publicvoidonClick(Viewv){ //TODOAuto-generatedmethodstub if(v==startServiceButton){ Intenti=newIntent(); i.setClass(ServiceDemo.this,MyService.class); mContext.startService(i); }elseif(v==stopServiceButton){ Intenti=newIntent(); i.setClass(ServiceDemo.this,MyService.class); mContext.stopService(i); }elseif(v==bindServiceButton){ Intenti=newIntent(); i.setClass(ServiceDemo.this,MyService.class); mContext.bindService(i,mServiceConnection,BIND_AUTO_CREATE); }else{ mContext.unbindService(mServiceConnection); } } }

第五步:修改AndroidManifest.xml代码(将我们新建的MyService注册进去如下代码第14行:)

[java]view plaincopy<?xmlversion="1.0"encoding="utf-8"?> <manifestxmlns:android="/apk/res/android" package="com.tutor.servicedemo" android:versionCode="1" android:versionName="1.0"> <applicationandroid:icon="@drawable/icon"android:label="@string/app_name"> <activityandroid:name=".ServiceDemo" 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"android:exported="true"></service> </application> <uses-sdkandroid:minSdkVersion="7"/> </manifest>

第六步:执行上述工程,效果图如下:

点击startServie按钮时先后执行了Service中onCreate()->onStart()这两个方法,打开Logcat视窗效果如下图:

我们这时可以按HOME键进入Settings(设置)->Applications(应用)->Running Services(正在运行的服务)看一下我们新启动了一个服务,效果如下:

点击stopService按钮时,Service则执行了onDestroy()方法,效果图如下所示:

这时候我们再次点击startService按钮,然后点击bindService按钮(通常bindService都是bind已经启动的Service),我们看一下Service执行了IBinder()方法,以及TextView的值也有所变化了,如下两张图所示:

最后点击unbindService按钮,则Service执行了onUnbind()方法,如下图所示:

Ok,今天就先讲到这里了,谢谢大家关注~

service的原理在这里就不在复述了,下面直接介绍service的两种启动方式及生命周期。

首先建立一个serviceDemo,如图所示。

然后修改main.xml布局文件:

[html]view plaincopy<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <TextView android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello"/> <Button android:id="@+id/startservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="startService"/> <Button android:id="@+id/stopservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="stopService"/> <Button android:id="@+id/bindservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="bindService"/> <Button android:id="@+id/unbindservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="unbindService"/> </LinearLayout> 接下来 建立一个MyService来继承service[java]view plaincopypublicclassMyServiceextendsService{ privatestaticfinalStringTAG="MyService"; privateMyBindermBinder=newMyBinder(); @Override publicIBinderonBind(Intentarg0){ //TODOAuto-generatedmethodstub Log.e(TAG,"startIBinder~~~"); returnmBinder; } @Override publicvoidonCreate(){ //TODOAuto-generatedmethodstub Log.e(TAG,"startonCreate~~~"); super.onCreate(); } @Override publicvoidonDestroy(){ //TODOAuto-generatedmethodstub Log.e(TAG,"startonDestroy~~~"); super.onDestroy(); } @Override publicintonStartCommand(Intentintent,intflags,intstartId){ //TODOAuto-generatedmethodstub Log.e(TAG,"startonStartCommand~~~"); returnsuper.onStartCommand(intent,flags,startId); } @Override publicbooleanonUnbind(Intentintent){ //TODOAuto-generatedmethodstub Log.e(TAG,"startonUnbind~~~"); returnsuper.onUnbind(intent); } publicStringgetSystemTime(){ /*Timet=newTime(); t.setToNow();*/ SimpleDateFormatformat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); returnformat.format(newDate()); } publicclassMyBinderextendsBinder{ publicMyServicegetService(){ returnMyService.this; } } } 分别实现了他的相应的生命周期方法,然后修改主activity为:[java]view plaincopypublicclassServiceDemoActivityextendsActivityimplementsOnClickListener{ /**Calledwhentheactivityisfirstcreated.*/ privateMyServicemMyService; privateTextViewmTextView; privateContextmContext; privateButtonstartServiceButton; privateButtonstopServiceButton; privateButtonbindServiceButton; privateButtonunbindServiceButton; //这里需要用到ServiceConnection在Context.bindService和context.unBindService()里用到 privateServiceConnectionmServiceConnection=newServiceConnection(){ //当我bindService时,让TextView显示MyService里getSystemTime()方法的返回值 @Override publicvoidonServiceConnected(ComponentNamename,IBinderservice){ //TODOAuto-generatedmethodstub mMyService=((MyService.MyBinder)service).getService(); mTextView.setText("IamfromeService:"+mMyService.getSystemTime()); } @Override publicvoidonServiceDisconnected(ComponentNamename){ //TODOAuto-generatedmethodstub } }; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); setupViews(); } privatevoidsetupViews(){ mContext=this; mTextView=(TextView)this.findViewById(R.id.text); startServiceButton=(Button)findViewById(R.id.startservice); stopServiceButton=(Button)findViewById(R.id.stopservice); bindServiceButton=(Button)findViewById(R.id.bindservice); unbindServiceButton=(Button)findViewById(R.id.unbindservice); startServiceButton.setOnClickListener(this); stopServiceButton.setOnClickListener(this); bindServiceButton.setOnClickListener(this); unbindServiceButton.setOnClickListener(this); } @Override publicvoidonClick(Viewv){ //TODOAuto-generatedmethodstub if(v==startServiceButton){ Intenti=newIntent(); i.setClass(ServiceDemoActivity.this,MyService.class); mContext.startService(i); }elseif(v==stopServiceButton){ Intenti=newIntent(); i.setClass(ServiceDemoActivity.this,MyService.class); mContext.stopService(i); }elseif(v==bindServiceButton){ Intenti=newIntent(); i.setClass(ServiceDemoActivity.this,MyService.class); mContext.bindService(i,mServiceConnection,BIND_AUTO_CREATE); }else{ mContext.unbindService(mServiceConnection); } } } 在这里不要忘记在AndroidManifest.xml里注册service

下面看一下运行效果:

点击startService按钮看一下打印的log日志:

首先开启一个start服务先是执行了onCreate方法和onStartCommand方法,然后点击stopService按钮:

执行了onDestroy方法,知道了这些生命周期方法后我们就可以在这些生命周期方法里做一些相应的事件了。

下面点击一下bindService按钮看会出现什么效果吧:

在最上方打印出了系统时间,绑定服务其实就是让服务执行完后,返回一些数据给启动它的组件比如activity。

这是后台打印的log:

最后点击unbindService取消绑定:

绑定服务 生命周期结束 。

下面让我们再看一下官方给出的两种服务的生命周期图:

这样是不是一眼就看明白了。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。