简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM