日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

浅谈Android四大组件之Service

發(fā)布時(shí)間:2023/11/27 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 浅谈Android四大组件之Service 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一:Service簡(jiǎn)介

Android開發(fā)中,當(dāng)需要?jiǎng)?chuàng)建在后臺(tái)運(yùn)行的程序的時(shí)候,就要使用到Service。

1:Service(服務(wù))是一個(gè)沒有用戶界面的在后臺(tái)運(yùn)行執(zhí)行耗時(shí)操作的應(yīng)用組件。其他應(yīng)用組件能夠啟動(dòng)Service,并且當(dāng)用戶切換到另外的應(yīng)用場(chǎng)景,Service將持續(xù)在后臺(tái)運(yùn)行。另外,一個(gè)組件能夠綁定到一個(gè)service與之交互(IPC機(jī)制),例如,一個(gè)service可能會(huì)處理網(wǎng)絡(luò)操作,播放音樂,操作文件I/O或者與內(nèi)容提供者(content provider)交互,所有這些活動(dòng)都是在后臺(tái)進(jìn)行。

?

2:Service有兩種狀態(tài),“啟動(dòng)的”和“綁定:

通過startService()啟動(dòng)的服務(wù)處于“啟動(dòng)的”狀態(tài),一旦啟動(dòng),service就在后臺(tái)運(yùn)行,即使啟動(dòng)它的應(yīng)用組件已經(jīng)被銷毀了。通常started狀態(tài)的service執(zhí)行單任務(wù)并且不返回任何結(jié)果給啟動(dòng)者。比如當(dāng)下載或上傳一個(gè)文件,當(dāng)這項(xiàng)操作完成時(shí),service應(yīng)該停止它本身。

?

還有一種“綁定”狀態(tài)的service,通過調(diào)用bindService()來(lái)啟動(dòng),一個(gè)綁定的service提供一個(gè)允許組件與service交互的接口,可以發(fā)送請(qǐng)求、獲取返回結(jié)果,還可以通過夸進(jìn)程通信來(lái)交互(IPC)。綁定的service只有當(dāng)應(yīng)用組件綁定后才能運(yùn)行,多個(gè)組件可以綁定一個(gè)service,當(dāng)調(diào)用unbind()方法時(shí),這個(gè)service就會(huì)被銷毀了。

?

3:serviceactivity一樣都存在與當(dāng)前進(jìn)程的主線程中,所以,一些阻塞UI的操作,比如耗時(shí)操作不能放在service里進(jìn)行,比如另外開啟一個(gè)線程來(lái)處理諸如網(wǎng)絡(luò)請(qǐng)求的耗時(shí)操作。如果在service里進(jìn)行一些耗CPU和耗時(shí)操作,可能會(huì)引發(fā)ANR警告,這時(shí)應(yīng)用會(huì)彈出是強(qiáng)制關(guān)閉還是等待的對(duì)話框。所以,對(duì)service的理解就是和activity平級(jí)的,只不過是看不見的,在后臺(tái)運(yùn)行的一個(gè)組件,這也是為什么和activity同被說(shuō)為Android的基本組件。

?

二:Service的生命周期

Android Service生命周期與Activity生命周期是相似的,但是也存在一些細(xì)節(jié)上也存在著重要的不同:

onCreateonStart是不同的

通過從客戶端調(diào)用Context.startService(Intent)方法我們可以啟動(dòng)一個(gè)服務(wù)。如果這個(gè)服務(wù)還沒有運(yùn)行,Android將啟動(dòng)它并且在onCreate方法之后調(diào)用它的onStart方法。如果這個(gè)服務(wù)已經(jīng)在運(yùn)行,那么它的onStart方法將被新的Intent再次調(diào)用。所以對(duì)于單個(gè)運(yùn)行的Service它的onStart方法被反復(fù)調(diào)用是完全可能的并且是很正常的。

onResumeonPause以及onStop是不需要的

回調(diào)一個(gè)服務(wù)通常是沒有用戶界面的,所以我們也就不需要onPauseonResume或者onStop方法了。無(wú)論何時(shí)一個(gè)運(yùn)行中的Service它總是在后臺(tái)運(yùn)行。

onBind

如果一個(gè)客戶端需要持久的連接到一個(gè)服務(wù),那么他可以調(diào)用Context.bindService方法。如果這個(gè)服務(wù)沒有運(yùn)行方法將通過調(diào)用onCreate方法去創(chuàng)建這個(gè)服務(wù)但并不調(diào)用onStart方法來(lái)啟動(dòng)它。相反,onBind方法將被客戶端的Intent調(diào)用,并且它返回一個(gè)IBind對(duì)象以便客戶端稍后可以調(diào)用這個(gè)服務(wù)。同一服務(wù)被客戶端同時(shí)啟動(dòng)和綁定是很正常的。

onDestroy

Activity一樣,當(dāng)一個(gè)服務(wù)被結(jié)束是onDestroy方法將會(huì)被調(diào)用。當(dāng)沒有客戶端啟動(dòng)或綁定到一個(gè)服務(wù)時(shí)Android將終結(jié)這個(gè)服務(wù)。與很多Activity時(shí)的情況一樣,當(dāng)內(nèi)存很低的時(shí)候Android也可能會(huì)終結(jié)一個(gè)服務(wù)。如果這種情況發(fā)生,Android也可能在內(nèi)存夠用的時(shí)候嘗試啟動(dòng)被終止的服務(wù),所以你的服務(wù)必須為重啟持久保存信息,并且最好在onStart方法內(nèi)來(lái)做。

?

三.Service的啟動(dòng)方式

Service的啟動(dòng)方式有如下2種

CstartService()和bindService(),這兩種方式對(duì)Service生命周期的影響是不同的

startservice是由其他組件調(diào)用startService()方法啟動(dòng)的,這導(dǎo)致服務(wù)的onStartCommand()方法被調(diào)用,當(dāng)服務(wù)是started狀態(tài)時(shí),其生命周期與啟動(dòng)它的組件無(wú)關(guān),并且可以在后臺(tái)無(wú)限期運(yùn)行,即使啟動(dòng)服務(wù)的組件已經(jīng)被銷毀。因此,服務(wù)需要在完成任務(wù)后調(diào)用stopself()方法停止,或者有其他組件調(diào)用stopService()方法停止。

使用bindService()方法啟用服務(wù),調(diào)用者與服務(wù)綁定在了一起,調(diào)用者一旦退出,服務(wù)也就終止,大有‘不求同生,但求同死’的特點(diǎn)

Android應(yīng)用中每個(gè)Service都必須要在AndroidMainifest.Xml配置文件中聲明。

?四:2種啟動(dòng)方式的具體例子

?

startService()方式的生命周期:?
啟動(dòng)時(shí),startService –> onCreate() –> onStart()

停止時(shí),stopService –> onDestroy()

?

如果調(diào)用者直接退出而沒有停止Service,則Service 會(huì)一直在后臺(tái)運(yùn)行 Context.startService()方法啟動(dòng)服務(wù),在服務(wù)未被創(chuàng)建時(shí),系統(tǒng)會(huì)先調(diào)用服務(wù)的onCreate()方法,接著調(diào)用onStart()方法。如果調(diào)用startService()方法前服務(wù)已經(jīng)被創(chuàng)建,多次調(diào)用startService()方法并不會(huì)導(dǎo)致多次創(chuàng)建服務(wù),但會(huì)導(dǎo)致多次調(diào)用onStart()方法。采用startService()方法啟動(dòng)的服務(wù),只能調(diào)用Context.stopService()方法結(jié)束服務(wù),服務(wù)結(jié)束時(shí)會(huì)調(diào)用onDestroy()方法。

?

startService()方式啟動(dòng) Service的方法:

<?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" > <Button android:id="@+id/startBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="啟動(dòng) Service" /> <Button android:id="@+id/stopBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="停止 Service" /> 
</LinearLayout> 

MainActivity.java

package com.android.service.activity;  import android.app.Activity;  
import android.content.Intent;  
import android.os.Bundle;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  public class MainActivity extends Activity  
{  private Button startBtn;  private Button stopBtn;  @Override public void onCreate(Bundle savedInstanceState)  {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  startBtn = (Button) findViewById(R.id.startBtn);  stopBtn = (Button) findViewById(R.id.stopBtn);  //添加監(jiān)聽器  
        startBtn.setOnClickListener(listener);  stopBtn.setOnClickListener(listener);  }  //啟動(dòng)監(jiān)聽器  private OnClickListener listener=new OnClickListener()  {         @Override public void onClick(View v)  {  Intent intent=new Intent(MainActivity.this, ServiceDemo.class);  switch (v.getId())  {  case R.id.startBtn:  startService(intent);  break;  case R.id.stopBtn:  stopService(intent);  break;  default:  break;  }             }  };  
} 

新建ServiceDemo類,ServiceDemo.java如下

package com.android.service.activity;  import android.app.Service;  
import android.content.Intent;  
import android.os.IBinder;  
import android.util.Log;  public class ServiceDemo extends Service  
{  private static final String TAG="Test";  @Override //Service時(shí)被調(diào)用  public void onCreate()  {  Log.i(TAG, "Service onCreate--->");  super.onCreate();  }  @Override //當(dāng)調(diào)用者使用startService()方法啟動(dòng)Service時(shí),該方法被調(diào)用  public void onStart(Intent intent, int startId)  {  Log.i(TAG, "Service onStart--->");  super.onStart(intent, startId);  }  @Override //當(dāng)Service不在使用時(shí)調(diào)用  public void onDestroy()  {  Log.i(TAG, "Service onDestroy--->");  super.onDestroy();  }  @Override //當(dāng)使用startService()方法啟動(dòng)Service時(shí),方法體內(nèi)只需寫return null  public IBinder onBind(Intent intent)  {  return null;  }  
}  

在AndroidManifest.xml文件中添加16~21行的聲明

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.service.activity" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="10" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MainActivity" 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=".ServiceDemo" >    <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </service>    </application> 
</manifest> 

效果如下:

當(dāng)點(diǎn)擊按鈕時(shí),先后執(zhí)行了Service中onCreate()->onStart()這兩個(gè)方法,LogCat顯示如下:

當(dāng)點(diǎn)擊?按鈕時(shí),Service則執(zhí)行了onDestroy()方法,LogCat顯示如下:

?

退出后,進(jìn)入Settings(設(shè)置)->Applications(應(yīng)用)->Running Services(正在運(yùn)行的服務(wù))看一下我們新啟動(dòng)了的服務(wù),效果圖如下:

?

?

bindService()方式的生命周期:?
綁定時(shí),bindService -> onCreate() –> onBind()
調(diào)用者退出了,即解綁定時(shí),Srevice就會(huì)unbindService –>onUnbind() –> onDestory() ? 用Context.bindService()方法啟動(dòng)服務(wù),在服務(wù)未被創(chuàng)建時(shí),系統(tǒng)會(huì)先調(diào)用服務(wù)的onCreate()方法,接著調(diào)用onBind()方法。這個(gè)時(shí)候調(diào)用者和服務(wù)綁定在一起,調(diào)用者退出了,系統(tǒng)就會(huì)先調(diào)用服務(wù)的onUnbind()方法,接著調(diào)用onDestroy()方法。如果調(diào)用bindService()方法前服務(wù)已經(jīng)被綁定,多次調(diào)用bindService()方法并不會(huì)導(dǎo)致多次創(chuàng)建服務(wù)及綁定(也就是說(shuō)onCreate()和onBind()方法并不會(huì)被多次調(diào)用)。如果調(diào)用者希望與正在綁定的服務(wù)解除綁定,可以調(diào)用unbindService()方法,調(diào)用該方法也會(huì)導(dǎo)致系統(tǒng)調(diào)用服務(wù)的onUnbind()-->onDestroy()方法。 ?bindService()方式啟動(dòng) Service的方法: 綁定Service需要三個(gè)參數(shù):bindService(intent, conn, Service.BIND_AUTO_CREATE); 第一個(gè):Intent對(duì)象 第二個(gè):ServiceConnection對(duì)象,創(chuàng)建該對(duì)象要實(shí)現(xiàn)它的onServiceConnected()和?onServiceDisconnected()來(lái)判斷連接成功或者是斷開連接 第三個(gè):如何創(chuàng)建Service,一般指定綁定的時(shí)候自動(dòng)創(chuàng)建。 例子如下: main.xml
<?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" > <Button   android:text="啟動(dòng)Service"   android:id="@+id/startBtn1"   android:layout_width="match_parent"   android:layout_height="wrap_content" />    <Button   android:text="停止Service"   android:id="@+id/stopBtn2"   android:layout_width="match_parent"   android:layout_height="wrap_content" />    <Button   android:text="綁定Service"   android:id="@+id/bindBtn3"   android:layout_width="match_parent"   android:layout_height="wrap_content" /> <Button   android:text="解除綁定"   android:id="@+id/unbindBtn4"   android:layout_width="match_parent"   android:layout_height="wrap_content" /> 
</LinearLayout> 

MainActivity.java

package com.android.bindservice.activity;  import android.app.Activity;  
import android.app.Service;  
import android.content.ComponentName;  
import android.content.Intent;  
import android.content.ServiceConnection;  
import android.os.Bundle;  
import android.os.IBinder;  
import android.util.Log;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  public class MainActivity extends Activity {  // 聲明Button  private Button startBtn,stopBtn,bindBtn,unbindBtn;  @Override public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  // 設(shè)置當(dāng)前布局視圖  
        setContentView(R.layout.main);  // 實(shí)例化Button  startBtn = (Button)findViewById(R.id.startBtn1);  stopBtn = (Button)findViewById(R.id.stopBtn2);  bindBtn = (Button)findViewById(R.id.bindBtn3);  unbindBtn = (Button)findViewById(R.id.unbindBtn4);  // 添加監(jiān)聽器  
        startBtn.setOnClickListener(startListener);  stopBtn.setOnClickListener(stopListener);  bindBtn.setOnClickListener(bindListener);  unbindBtn.setOnClickListener(unBindListener);  }  // 啟動(dòng)Service監(jiān)聽器  private OnClickListener startListener = new OnClickListener() {  @Override public void onClick(View v) {  // 創(chuàng)建Intent  Intent intent = new Intent();  // 設(shè)置Class屬性  intent.setClass(MainActivity.this, BindService.class);  // 啟動(dòng)該Service  
            startService(intent);  }  };  // 停止Service監(jiān)聽器  private OnClickListener stopListener = new OnClickListener() {  @Override public void onClick(View v) {  // 創(chuàng)建Intent  Intent intent = new Intent();  // 設(shè)置Class屬性  intent.setClass(MainActivity.this, BindService.class);  // 啟動(dòng)該Service  
            stopService(intent);  }  };  // 連接對(duì)象  private ServiceConnection conn = new ServiceConnection() {  @Override public void onServiceConnected(ComponentName name, IBinder service) {  Log.i("Service", "連接成功!");  }  @Override public void onServiceDisconnected(ComponentName name) {  Log.i("Service", "斷開連接!");  }  };  // 綁定Service監(jiān)聽器  private OnClickListener bindListener = new OnClickListener() {  @Override public void onClick(View v) {  // 創(chuàng)建Intent  Intent intent = new Intent();  // 設(shè)置Class屬性  intent.setClass(MainActivity.this, BindService.class);  // 綁定Service  
            bindService(intent, conn, Service.BIND_AUTO_CREATE);  }  };  // 解除綁定Service監(jiān)聽器  private OnClickListener unBindListener = new OnClickListener() {  @Override public void onClick(View v) {  // 創(chuàng)建Intent  Intent intent = new Intent();  // 設(shè)置Class屬性  intent.setClass(MainActivity.this, BindService.class);  // 解除綁定Service  
            unbindService(conn);  }  };    
} 

BindService.java

package com.android.bindservice.activity;  import android.app.Service;  
import android.content.Intent;  
import android.os.IBinder;  
import android.util.Log;  public class BindService extends Service{  private static final String TAG="Test";  //返回null  public IBinder onBind(Intent intent) {  Log.i(TAG, "Service onBind--->");  return null;  }  // Service創(chuàng)建時(shí)調(diào)用  public void onCreate() {  Log.i(TAG, "Service onCreate--->");  }  // 當(dāng)客戶端調(diào)用startService()方法啟動(dòng)Service時(shí),該方法被調(diào)用  public void onStart(Intent intent, int startId) {  Log.i(TAG, "Service onStart--->");  }  // 當(dāng)Service不再使用時(shí)調(diào)用  public void onDestroy() {  Log.i(TAG, "Service onDestroy--->");  }  // 當(dāng)解除綁定時(shí)調(diào)用  public boolean onUnbind(Intent intent) {    Log.i(TAG, "Service onUnbind--->");    return super.onUnbind(intent);    }    
}  

?

在AndroidManifest.xml文件中添加16~21行的聲明

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.bindservice.activity" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="10" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MainActivity" 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=".BindService" >    <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </service> </application> 
</manifest> 

效果如下:

當(dāng)點(diǎn)擊按鈕時(shí),先后執(zhí)行了Service中onCreate()->onStart()這兩個(gè)方法,LogCat顯示如下:

當(dāng)點(diǎn)擊按鈕,則Service執(zhí)行了onUnbind()方法,LogCat顯示如下:

?

當(dāng)點(diǎn)擊按鈕,則Service執(zhí)行了onUnbind()方法,LogCat顯示如下:

?

?

轉(zhuǎn)載于:https://www.cnblogs.com/FENGXUUEILIN/p/5663280.html

總結(jié)

以上是生活随笔為你收集整理的浅谈Android四大组件之Service的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。