Search code examples
androidmultithreadingsynchronize

Android alarmmanager synchronized


I am referring to http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/AlarmService_Service.html

There the runnable of the thread looks like this

Runnable mTask = new Runnable() 
{        
    public void run() 
    {  
        Log.v("service", "thread is running after 5 min");
        // Normally we would do some work here...  for our sample, we will           
        // just sleep for 30 seconds.            
        long endTime = System.currentTimeMillis() + 15*1000;            
        while (System.currentTimeMillis() < endTime) 
        {                
            synchronized (mBinder) 
            {                    
                try 
                {                        
                    mBinder.wait(endTime - System.currentTimeMillis());      
                } 
                catch (Exception e) 
                {                    

                }                
            }            
        }            // Done with our work...  stop the service!            
        AlarmService_Service.this.stopSelf();     
    }    
}

I admit that I have some problems with the concept of synchronized... The thread runs the while loop to wait 15s, within that loop I have wait for 15s. So how would the runnable look like if I just want to write a log entry e.g. Log.v(TAG,TEXT);? What would change if I want to write a new entry into my own database table?

Thanks, A.


Solution

  • If you just want a log statement then the following will work fine

    Runnable mTask = new Runnable() 
    {        
        public void run() 
        {  
            Log.v("TAG", "Some verbose log message");
        }    
    }
    

    Whether you need to use synchronized on an object depends on whether object is thread-safe or not. If it is not thread-safe, then you will need to ensure that only one thread access the object at a time by using a synchronized block. In your example mBinder is not thread-safe, so in order to call the wait method of the binder you need to ensure that you are the only thread accessing it.

    A runnable is most often used to execute code in a different thread, so that long running operations (such as IO, but in this case just waiting) do not block the UI thread.