[英]How to start a Service when the Android application is started?
我有一個后台Service
。 我希望它的生命周期獨立於應用程序Activity
的生命周期。
是的,我知道我必須手動關閉服務作為應用程序邏輯的一部分。
如何與應用程序的第一個活動一起啟動已啟動的服務?
在第一個Activity
的onCreate()
方法中調用startService(intent)
。
我有一個后台服務。 我希望它的生命周期獨立於應用程序活動。
要做到這一點,最好的方法是創建一個PendingIntent
的Service
,並與注冊它AlarmManager
:
Intent i = new Intent(this, LocationService.class);
PendingIntent pi = PendingIntent.getService(this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP,0,60*60*1000, pi); /* start Service every hour. */
這將確保定期定期啟動Service
,而不管用戶是否已將應用程序帶到前台。
Android應用程序啟動時如何啟動服務?
您可以通過擴展Application
類在應用程序啟動時自動啟動Service
:
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
startService(new Intent(this, NetworkService.class));
}
}
並使用修改manifest
的application
標記
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:name="com.mycompanydomain.MyApp">
這是有效的,因為Application
類是應用程序啟動時要創建的第一個實體之一。 無論啟動Activity
是什么,這都將啟動Service
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.