Reputation: 390
As per android documentation long running task should be performed using service and service should be in separate thread. I'm having following question? Note: I'm using normal service not intent service. 1 By default service runs in main thread, where I need to create thread for executing my long running task onCreate, onStartCommand? 2 In case of bound service where I need to create thread for executing my long running task onCreate, onBind?
Upvotes: 1
Views: 95
Reputation: 572
use this
public class NetworkService extends Service {
private HandlerThread mHandlerThread;
private Handler mHandler;
private final IBinder mBinder = new MyLocalBinder();
@Override
public void onCreate() {
super.onCreate();
mHandlerThread = new HandlerThread("LocalServiceThread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
}
public void postRunnable(Runnable runnable) {
mHandler.post(runnable);
}
public class MyLocalBinder extends Binder {
public NetworkService getService() {
return NetworkService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
Upvotes: 2