Issue
I have a background Service
. I want its life cycle to be independent of that of the application's Activity
s.
And yes, I know I have to manually shut the service down manually as a part of the application logic.
Solution
How to start a Started Service together with the first activity of the Application?
Call startService(intent)
in the onCreate()
method of the first Activity
.
I have a background service. I want its life cycle to be independent of the application activities.
The best way to do that is to create a PendingIntent
for a Service
and register it with the 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. */
This will ensure that the Service
is periodically started at regular intervals, independent of whether the user has brought the app to the foreground or not.
How to start a Service when the Android application is started?
You can start the Service
automatically on application start by extending the Application
class:
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
startService(new Intent(this, NetworkService.class));
}
}
and modify the application
tag in your manifest
with
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:name="com.mycompanydomain.MyApp">
This works because the Application
class is one of the first entities to be created when an app launches. This will start the Service
irrespective of what the launch Activity
is.
Answered By - Yash Sampat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.