javaandroidserviceandroid-servicephone-state-listener

What is the Android PhoneStateListener's Behavior When Called Multiple Times?


My service has a PhoneStateListener that overrides the onCellInfoChanged method. When running on Android Studio, it'll log whenever the method is called. Based on the logs, it seems that sometimes the method gets called consecutively (a couple milliseconds between logs).

public class OnCellChangeService extends Service
{
    // other field declarations

    private PhoneStateListener mPhoneStateListener = new PhoneStateListener()
    {
        @SuppressLint("DefaultLocale")
        @Override
        public void onCellInfoChanged(List<CellInfo> cellInfoList)
        {
            String timeStamp = simpleDateFormat.format(new Date());
            List<CellNetwork> cellNetworks = setCellNetwork(cellInfoList);
            String networkStrength = "";
            int index = 1;
            for (CellNetwork cell : cellNetworks)
                networkStrength += String.format("%s (%d)%s\n", timeStamp, index++, cell.record());

            try {
                writer.write(networkStrength);
                writer.flush();
                Log.d("Phone Listener", "Cell Change");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

   // rest of service

}

All the listener does is take the cellInfoList, calls another method to get a list that contains a list of custom class objects made from a subset of the original list. It writes to a file with a time stamp and other various pieces of information from each list object.

When the listener's method is called again while the same method is executing, does the current method stop and restart for the new call? Does it run in a separate thread of execution? Does it wait for the method to finish executing? If another call does halt or interfere with the same method executing, how could I implement threading and/or synchronization to make sure every called is executed in full while maintaining order?


Solution

  • The callbacks from PhoneStateListener are all made on the main (UI) thread. Therefore, each callback method will run to completion before the next one is called.