Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's the same as the need for synchronization anywhere else in Java or Android - if you have multiple threads accessing the variables you may need synchronized methods to prevent thread interference or you may need to declare the variables as volatile so that each thread gets an up to date copy.</p> <p>The only thing Android specific to note is that the <code>onStartCommand</code> is going to be called by the system on the main thread, so you are blocking the main UI thread unless you make it otherwise. If you use <code>IntentService</code> the <code>onHandleIntent</code> method is called on a different thread, so you can offload your long running task there without worrying about the mechanics of creating and using a separate thread.</p> <p>A place where you might use a volatile instance variable would be if mutate a variable in <code>onHandleIntent</code>, and then access it in <code>onDestroy</code>. Here you want to ensure you have a fresh copy when <code>onDestroy</code> is called.</p> <p>All that can be said of your examples is that in your first example, the value of a at the Log statement is undefined, and in the second example it is 1 if this is a new object.</p> <p>EDIT: The bottom line is you really shouldn't be counting on the value of instance variables to be anything if you are calling startService() multiple times (we don't know if it's even going to be the same instance since it could have been destroyed) and you shouldn't count on the order of calls to startService() to necessarily be the same as the order they executed by the service (even though that seems to be the way it's implemented). </p> <p>Stuff the requests into an array and send them as one call to startService(), or use local variables within the Service if you need such guarantees.</p> <p>If you a more complicated scenario with multi-threading within the Service, you should should post a concrete example of the problem, because without knowing what you're trying to it's impossible to give advice.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload