Android service starts ramdomly / automatically

I have an android service, I bound it to activity and unbound on destruction. The problem is that it starts from nothing when the application is closed, sometimes when I turn on the device, sometimes ramdomly, I know that it starts โ€œbecause of a toast messageโ€. Let's get to the code ...

OnCreate action

Intent intent = new Intent(this, Sincronizacao.class); this.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); this.startService(intent); 

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 to 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, the onStartCommand function is implemented, there I start a stream that requests a web service and inserts data into the database, the stream has some time (true), I just interrupt it on the onDestroy method of the service ..

Edit

Here is the manifest line

 android:name="com.company.package.service.Sincronizacao" /> 

I have been afraid of this error for some time, I hope you can help me.

Thanks,

+4
source share
1 answer

I managed to solve the problem ... As part of the service, I moved the code from onStartCommand to onBind. I had no problems, since I just use this service in a prohibited state.

Also, I previously stopped Thread inside the service using thread.interrupt (), now I use the flag in time and set it to false on onUnbind and onDestroy.

+3
source

Source: https://habr.com/ru/post/1436033/


All Articles