I'm creating an IntentService with Binder, so I can communicate with this service from an Activity
public class MyService extends IntentService {
private ChatManager chatManager;
private final IBinder mBinder = new MyBinder();
public MyService() {
super("MyService");
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
if(chatManager == null) chatManager = new ChatManager();
}
@Override
public void onDestroy() {
super.onDestroy();
if(chatManager != null) {
chatManager.encerraChatManager();
}
}
public class MyBinder extends Binder{
public ChatManager getService() {
return chatManager;
}
}
}
In my activity, in the onCreate method I call
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
And in the onServiceConnected method I get the chatManager object
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
chatManager = ((ChatService.ChatBinder)iBinder).getService();
}
As my chatManager method was instantiated on a Background Thread I expected it to continue running in the background, but it is not. When I call any chatManager method it runs on the main thread.
What am I doing wrong or what concept did I misunderstand from the IntentService on android?
EDITION 07/31/2017 Explanation of the ChatManager Class
ChatManager opens a connection to the Realm database (realm.io). With an open connection, I can add messages to chat, terminate chat, change status, etc. With this I want to not have to open a connection with the bank for every new change in the bank, which is very frequent and consumes many resources.
On the other hand, I can not make the writes in the direct bank on the Main Thread, as this is slowing and even crashing the app.
ChatManager
public class ChatManager {
private Realm db;
private Chat chat;
public ChatManager() {
db = Realm.getDefaultInstance(); // Uma instancia do banco de dados Realm
}
/**
* Vários método que tem essa estrutura
*/
public void metodoGernerico(Object param) {
db.executeTransaction(realm -> {
// altera o banco de dados
});
}
/**
* Fecha o banco de dados quando sai da activity
*/
public void encerraChatManager() {
db.close();
}
}