I have an android service, I bound it to an activity, and unbound on destroy. The problem is, it starts out of nothing when the application is closed, sometimes when I turn on the device, sometimes ramdomly, I know it starts ’cause of a toast message. Lets get to the code…
Activity onCreate
Intent intent = new Intent(this, Sincronizacao.class);
this.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
this.startService(intent);
The code for mConnection
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
serviceBound = true;
localBinder = (LocalBinder<Sincronizacao>) service;
}
public void onServiceDisconnected(ComponentName className) {
serviceBound = false;
localBinder = null;
}
};
And on destroy
@Override
protected void onDestroy() {
super.onDestroy();
if (serviceBound && mConnection != null) {
unbindService(mConnection);
}
Intent intent = new Intent(this, Sincronizacao.class);
stopService(intent);
localBinder = null;
}
In my service, onStartCommand is implemented, in there I start out a thread wich query a web service and insert data into a database, the thread has a while(true), I simply interrupt it onDestroy method of the service…
Edit:
Here’s the manifest line
android:name="com.company.package.service.Sincronizacao" />
I’m struggling in this bug for some time already, hope you can help me.
Thanks,
I was able to solve the problem… Within the service, I moved the code from
onStartCommandtoonBind. I’ve had no problems since, I just use the service on a bidden state.Also, previously I was stopping the Thread inside the service with
thread.interrupt(), now I’m using a flag in the while, and setting it to false ononUnbindandonDestroy.