原文來自:
首先我們要知道Service具體是干什么的,什么時候用到?以及它的生命周期等。
Service概念及用途:
Android中的服務,它與Activity不同,它是不能與用戶交互的,不能自己啟動的,運行在后臺的程序,如果我們退出應用時,Service進程并沒有結(jié)束,它仍然在后臺運行,那 我們什么時候會用到Service呢?比如我們播放音樂的時候,有可能想邊聽音樂邊干些其他事情,當我們退出播放音樂的應用,如果不用Service,我 們就聽不到歌了,所以這時候就得用到Service了,又比如當我們一個應用的數(shù)據(jù)是通過網(wǎng)絡獲取的,不同時間(一段時間)的數(shù)據(jù)是不同的這時候我們可以 用Service在后臺定時更新,而不用每打開應用的時候在去獲取。
Service生命周期?:
Android Service的生命周期并不像Activity那么復雜,它只繼承了onCreate(),onStart(),onDestroy()三個方法,當我們第一次啟動Service時,先后調(diào)用了onCreate(),onStart()這兩個方法,當停止Service時,則執(zhí)行onDestroy()方法,這里需要注意的是,如果Service已經(jīng)啟動了,當我們再次啟動Service時,不會在執(zhí)行onCreate()方法,而是直接執(zhí)行onStart()方法,具體的可以看下面的實例。
Service與Activity通信:
Service后端的數(shù)據(jù)最終還是要呈現(xiàn)在前端Activity之上的,因為啟動Service時,系統(tǒng)會重新開啟一個新的進程,這就涉及到不同進程間通信的問題了(AIDL)這一節(jié)我不作過多描述,當我們想獲取啟動的Service實例時,我們可以用到bindService和onBindService方法,它們分別執(zhí)行了Service中IBinder()和onUnbind()方法。
?
為了讓大家 更容易理解,我寫了一個簡單的Demo,大家可以模仿著我,一步一步的來。
?
第一步:新建一個Android工程,我這里命名為ServiceDemo.
第二步:修改main.xml代碼,我這里增加了四個按鈕,代碼如下:
[java]?view plaincopy
<?xml?version="1.0"?encoding="utf-8"?>?? <LinearLayout?xmlns:android="http://schemas.android.com/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 plaincopy
package?com.tutor.servicedemo;?? import?android.app.Service;?? import?android.content.Intent;?? import?android.os.Binder;?? import?android.os.IBinder;?? import?android.text.format.Time;?? import?android.util.Log;?? public?class?MyService?extends?Service?{?? ?????? ????private?static?final?String?TAG?=?"MyService";?? ?????? ????private?MyBinder?mBinder?=?new?MyBinder();?? ????@Override?? ????public?IBinder?onBind(Intent?intent)?{?? ????????Log.e(TAG,?"start?IBinder~~~");?? ????????return?mBinder;?? ????}?? ????@Override?? ????public?void?onCreate()?{?? ????????Log.e(TAG,?"start?onCreate~~~");?? ????????super.onCreate();?? ????}?? ?????? ????@Override?? ????public?void?onStart(Intent?intent,?int?startId)?{?? ????????Log.e(TAG,?"start?onStart~~~");?? ????????super.onStart(intent,?startId);??? ????}?? ?????? ????@Override?? ????public?void?onDestroy()?{?? ????????Log.e(TAG,?"start?onDestroy~~~");?? ????????super.onDestroy();?? ????}?? ?????? ?????? ????@Override?? ????public?boolean?onUnbind(Intent?intent)?{?? ????????Log.e(TAG,?"start?onUnbind~~~");?? ????????return?super.onUnbind(intent);?? ????}?? ?????? ?????? ????public?String?getSystemTime(){?? ?????????? ????????Time?t?=?new?Time();?? ????????t.setToNow();?? ????????return?t.toString();?? ????}?? ?????? ????public?class?MyBinder?extends?Binder{?? ????????MyService?getService()?? ????????{?? ????????????return?MyService.this;?? ????????}?? ????}?? }??
第四步:修改ServiceDemo.java,代碼如下:
[java]?view plaincopy
package?com.tutor.servicedemo;?? import?android.app.Activity;?? import?android.content.ComponentName;?? import?android.content.Context;?? import?android.content.Intent;?? import?android.content.ServiceConnection;?? import?android.os.Bundle;?? import?android.os.IBinder;?? import?android.view.View;?? import?android.view.View.OnClickListener;?? import?android.widget.Button;?? import?android.widget.TextView;?? public?class?ServiceDemo?extends?Activity?implements?OnClickListener{?? ????? ????private?MyService??mMyService;?? ????private?TextView?mTextView;?? ????private?Button?startServiceButton;?? ????private?Button?stopServiceButton;?? ????private?Button?bindServiceButton;?? ????private?Button?unbindServiceButton;?? ????private?Context?mContext;?? ?????? ?????? ????private?ServiceConnection?mServiceConnection?=?new?ServiceConnection()?{?? ?????????? ????????public?void?onServiceConnected(ComponentName?name,?IBinder?service)?{?? ?????????????? ????????????mMyService?=?((MyService.MyBinder)service).getService();?? ????????????mTextView.setText("I?am?frome?Service?:"?+?mMyService.getSystemTime());?? ????????}?? ?????????? ????????public?void?onServiceDisconnected(ComponentName?name)?{?? ?????????????? ?????????????? ????????}?? ????};?? ????public?void?onCreate(Bundle?savedInstanceState)?{?? ????????super.onCreate(savedInstanceState);?? ????????setContentView(R.layout.main);?? ????????setupViews();?? ????}?? ?????? ????public?void?setupViews(){?? ?????? ????????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);?? ????}?? ????? ????public?void?onClick(View?v)?{?? ?????????? ????????if(v?==?startServiceButton){?? ????????????Intent?i??=?new?Intent();?? ????????????i.setClass(ServiceDemo.this,?MyService.class);?? ????????????mContext.startService(i);?? ????????}else?if(v?==?stopServiceButton){?? ????????????Intent?i??=?new?Intent();?? ????????????i.setClass(ServiceDemo.this,?MyService.class);?? ????????????mContext.stopService(i);?? ????????}else?if(v?==?bindServiceButton){?? ????????????Intent?i??=?new?Intent();?? ????????????i.setClass(ServiceDemo.this,?MyService.class);?? ????????????mContext.bindService(i,?mServiceConnection,?BIND_AUTO_CREATE);?? ????????}else{?? ????????????mContext.unbindService(mServiceConnection);?? ????????}?? ????}?? ?????? ?????? ?????? }??
第五步:修改AndroidManifest.xml代碼(將我們新建的MyService注冊進去如下代碼第14行:)?
[java]?view plaincopy
<?xml?version="1.0"?encoding="utf-8"?>?? <manifest?xmlns:android="http://schemas.android.com/apk/res/android"?? ??????package="com.tutor.servicedemo"?? ??????android:versionCode="1"?? ??????android:versionName="1.0">?? ????<application?android:icon="@drawable/icon"?android:label="@string/app_name">?? ????????<activity?android:name=".ServiceDemo"?? ??????????????????android:label="@string/app_name">?? ????????????<intent-filter>?? ????????????????<action?android:name="android.intent.action.MAIN"?/>?? ????????????????<category?android:name="android.intent.category.LAUNCHER"?/>?? ????????????</intent-filter>?? ????????</activity>?? ????????<service?android:name=".MyService"?android:exported="true"></service>?? ????</application>?? ????<uses-sdk?android:minSdkVersion="7"?/>?? </manifest>???
?
第六步:執(zhí)行上述工程,效果圖如下:
點擊startServie按鈕時先后執(zhí)行了Service中onCreate()->onStart()這兩個方法,打開Logcat視窗效果如下圖:
我們這時可以按HOME鍵進入Settings(設置)->Applications(應用)->Running Services(正在運行的服務)看一下我們新啟動了一個服務,效果如下:
點擊stopService按鈕時,Service則執(zhí)行了onDestroy()方法,效果圖如下所示:
這時候我們再次點擊startService按鈕,然后點擊bindService按鈕(通常bindService都是bind已經(jīng)啟動的Service),我們看一下Service執(zhí)行了IBinder()方法,以及TextView的值也有所變化了,如下兩張圖所示:
?
最后點擊unbindService按鈕,則Service執(zhí)行了onUnbind()方法,如下圖所示:
?
Ok,今天就先講到這里了,謝謝大家關注~
? ? service的原理在這里就不在復述了,下面直接介紹service的兩種啟動方式及生命周期。
?????????? 首先建立一個serviceDemo,如圖所示。
???????????
?????? 然后修改main.xml布局文件:
????
[html]?view plaincopy
<?xml?version="1.0"?encoding="utf-8"?>?? <LinearLayout?xmlns:android="http://schemas.android.com/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 plaincopy
public?class?MyService?extends?Service?{?? ?????private?static?final?String?TAG?=?"MyService";???? ?????private?MyBinder?mBinder=new?MyBinder();?? ????@Override?? ????public?IBinder?onBind(Intent?arg0)?{?? ?????????? ??????????Log.e(TAG,?"start?IBinder~~~");???? ????????return?mBinder;?? ????}?? ????@Override?? ????public?void?onCreate()?{?? ?????????? ?????????Log.e(TAG,?"start?onCreate~~~");???? ????????super.onCreate();?? ????}?? ????@Override?? ????public?void?onDestroy()?{?? ?????????? ??????????Log.e(TAG,?"start?onDestroy~~~");???? ????????super.onDestroy();?? ????}?? ????@Override?? ????public?int?onStartCommand(Intent?intent,?int?flags,?int?startId)?{?? ?????????? ?????????Log.e(TAG,?"start?onStartCommand~~~");???? ????????return?super.onStartCommand(intent,?flags,?startId);?? ????}?? ????@Override?? ????public?boolean?onUnbind(Intent?intent)?{?? ?????????? ?????????Log.e(TAG,?"start?onUnbind~~~");???? ????????return?super.onUnbind(intent);?? ????}?? ????public?String?getSystemTime(){???? ??????????? ?? ??????????SimpleDateFormat?format=new?SimpleDateFormat("yyyy-MM-dd?HH:mm:ss");?? ??????????return?format.format(new?Date());?? ????}?? ?????public?class?MyBinder?extends?Binder{?? ????????????public?MyService?getService(){?? ????????????????return?MyService.this;?? ????????????}?? ?????}?? ???????? }??
??? 分別實現(xiàn)了他的相應的生命周期方法,然后修改主activity為:
[java]?view plaincopy
public?class?ServiceDemoActivity?extends?Activity?implements?OnClickListener{?? ?????? ?????private?MyService?mMyService;?? ?????private?TextView?mTextView;?? ?????private?Context?mContext;?? ?????private?Button?startServiceButton;???? ?????private?Button?stopServiceButton;???? ?????private?Button?bindServiceButton;???? ?????private?Button?unbindServiceButton;???? ??????? ?????? ????private?ServiceConnection?mServiceConnection?=?new?ServiceConnection()?{???? ?????????? ?? ????????@Override?? ????????public?void?onServiceConnected(ComponentName?name,?IBinder?service)?{?? ?????????????? ?????????????mMyService?=?((MyService.MyBinder)service).getService();???? ????????????mTextView.setText("I?am?frome?Service?:"?+?mMyService.getSystemTime());???? ??????? ????????}?? ?? ????????@Override?? ????????public?void?onServiceDisconnected(ComponentName?name)?{?? ?????????????? ?????????????? ????????}???? ????};?? ????@Override?? ????public?void?onCreate(Bundle?savedInstanceState)?{?? ????????super.onCreate(savedInstanceState);?? ????????setContentView(R.layout.main);?? ????????setupViews();???? ????}?? ????private?void?setupViews(){?? ????????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?? ????public?void?onClick(View?v)?{?? ?????????? ?????????if(v?==?startServiceButton){???? ????????????????Intent?i??=?new?Intent();???? ????????????????i.setClass(ServiceDemoActivity.this,?MyService.class);???? ????????????????mContext.startService(i);???? ????????????}else?if(v?==?stopServiceButton){???? ????????????????Intent?i??=?new?Intent();???? ????????????????i.setClass(ServiceDemoActivity.this,?MyService.class);???? ????????????????mContext.stopService(i);???? ????????????}else?if(v?==?bindServiceButton){???? ????????????????Intent?i??=?new?Intent();???? ????????????????i.setClass(ServiceDemoActivity.this,?MyService.class);???? ????????????????mContext.bindService(i,?mServiceConnection,?BIND_AUTO_CREATE);???? ????????????}else{???? ????????????????mContext.unbindService(mServiceConnection);???? ????????????}???? ????}?? }??
????? 在這里不要忘記在AndroidManifest.xml里注冊service
????? 下面看一下運行效果:
??????
????? 點擊startService按鈕看一下打印的log日志:
??????
???? 首先開啟一個start服務先是執(zhí)行了onCreate方法和onStartCommand方法,然后點擊stopService按鈕:
?????
??? 執(zhí)行了onDestroy方法,知道了這些生命周期方法后我們就可以在這些生命周期方法里做一些相應的事件了。
??? 下面點擊一下bindService按鈕看會出現(xiàn)什么效果吧:
???
??? 在最上方打印出了系統(tǒng)時間,綁定服務其實就是讓服務執(zhí)行完后,返回一些數(shù)據(jù)給啟動它的組件比如activity。
?? ? 這是后臺打印的log:
???? 最后點擊unbindService取消綁定:
????
?? 綁定服務 生命周期結(jié)束 。
?? 下面讓我們再看一下官方給出的兩種服務的生命周期圖:
?????
??????? 這樣是不是一眼就看明白了。
總結(jié)
以上是生活随笔為你收集整理的【Android】 Android Service生命周期及用法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。