I want to create a little app, which logs data in the background. So I try it whit a bound service. This works fine but if i close the app the service stops too.
So, my question: Is it a good way to perform that with a instant service?
And how can I keep the service running in the background when app is closend (i want to start it after boot too)?
Asked
Active
Viewed 240 times
0

user3865090
- 3
- 1
-
Bound services should only run while there is some component of your app running. You need to use a "started" service as it is named in http://developer.android.com/guide/components/services.html – Salem Jul 22 '14 at 14:54
2 Answers
0
Check out this link on system applications.
If the app is not a system app, Android can destroy the process in a low-memory situation, this includes services. Otherwise checkout the startForeground() for application services.

RScottCarson
- 980
- 5
- 20
0
You can try this:
public class ServiceBackground extends Service {
@Override
public IBinder onBind( final Intent arg0 ) {
return null;
}
@Override
public void onCreate() {
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor( 1 ); // Number of threads keep in the pool
executor.scheduleAtFixedRate( new Runnable() {
@Override
public void run() {
Log.i( "LocalService", "service running" );
if (stopCondition == true ) {
executor.shutdownNow();
}
}
}, 1, 1000, TimeUnit.MILLISECONDS );
super.onCreate();
}
@Override
public int onStartCommand( final Intent intent, final int flags, final int startId ) {
return Service.START_STICKY;
}
}
Remember to register the service in AndroidManifest.xml
More information about ScheduledThreadPoolExecutor
Starting the service
public class MainActivity extends Activity {
@Override
protected void onCreate( final Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
this.setContentView( R.layout.activity_main );
this.startService( new Intent( this, ServiceBackground.class ) );
}
}

wbelarmino
- 509
- 3
- 7
-
I am trying this method out for a periodic task, but it does not seem to work http://stackoverflow.com/questions/27872016/scheduledthreadpoolexecutor-for-a-periodic-task-using-retrofit-just-firing-onc – dowjones123 Jan 10 '15 at 02:06