語言

Context.StartService(Intent) 方法

定義

請求啟動某項應用程式服務。

[Android.Runtime.Register("startService", "(Landroid/content/Intent;)Landroid/content/ComponentName;", "GetStartService_Landroid_content_Intent_Handler")]
public abstract Android.Content.ComponentName? StartService(Android.Content.Intent? service);
[<Android.Runtime.Register("startService", "(Landroid/content/Intent;)Landroid/content/ComponentName;", "GetStartService_Landroid_content_Intent_Handler")>]
abstract member StartService : Android.Content.Intent -> Android.Content.ComponentName

參數

service
Intent

識別即將啟動的服務。 意圖必須完全明確(提供元件名稱)。 意圖附加值可包含,以配合此特定啟動呼叫提供論點。

傳回

如果服務正在啟動或已經在運行中, ComponentName 則會回傳實際啟動的服務;否則如果服務不存在,則回傳 null。

屬性

例外狀況

備註

請求啟動某項應用程式服務。 Intent 應該包含要開始的特定服務實作的完整類別名稱,或是針對特定套件名稱。 如果意圖說明較少,系統會記錄警告。 此時可使用多種匹配服務中的任一。 如果此服務尚未執行,將會被實例化並啟動(如有需要,建立程序);如果它在運行,那它就會一直運作。

每次呼叫此方法都會產生對目標服務android.app.Service#onStartCommand方法的相應呼叫,<><var 意圖/var> 格式在此給出。 這提供了一種方便的方式,可以將工作提交給服務,而無需綁定並呼叫其介面。

使用 startService() 會覆蓋預設的服務壽命,該服務由 管理 #bindService:它要求服務必須持續運行直到 #stopService 被呼叫,無論是否有用戶端連接。 請注意,呼叫 startService() 不會巢狀:無論你呼叫 startService() 多少次,只要呼叫一次 , #stopService 它就會停止。

系統會盡量讓服務持續運行。 只有當當前前台應用程式使用資源過多,導致服務必須終止時,才應該停止。 若服務過程中發生任何錯誤,將自動重新啟動。

如果你沒有啟動該服務的權限,這個函式會被觸發 SecurityException 。

<div 類別=「注意」>

<strong>Note:</strong> 每次呼叫 startService() 都會讓系統在管理意圖處理周邊的服務生命週期上投入大量工作,這可能耗費數毫秒的 CPU 時間。 由於成本高昂,startService() 不應用於頻繁的意圖傳遞,僅用於排程重大工作。 用於 #bindService bound services 高頻通話。

從 SDK 版本 android.os.Build.VERSION_CODES#O開始,針對 SDK 版本 android.os.Build.VERSION_CODES#O 或更高版本的應用程式不允許從背景啟動背景服務。 看!

更多細節請參考背景執行限制。

<strong>Note:</strong> 從 SDK 版本 android.os.Build.VERSION_CODES#S開始,針對 SDK 版本 android.os.Build.VERSION_CODES#S 或更高版本的應用程式不允許從背景啟動前台服務。 看!

行為變更:針對 Android 12 的應用程式

請參閱更多詳細資料。 </div>

Java 文件 android.content.Context.startService(android.content.Intent)。

本頁部分內容為基於 Open Source Project 所創建與分享的作品,並依授權條款所描述的使用進行修改。

適用於

另請參閱

  • StopService(Intent)
  • <xref:Android.Content.Context.BindService(Android.Content.Intent%2c+Android.Content.IServiceConnection%2c+Android.Content.IServiceConnection)>