Pedestrian dead reckoning (PDR), used in state-of-the-art smartphones, calculates pedestrian positions by using built-in inertial sensors. However, the complex and changeable usage modes of smartphones have been obstructing the development of PDR in the field of gait detection. Since the measurement of the sensor is affected by noise, position errors will emerge, needing to be corrected periodically via external measurements. To this end, an optimization-based PDR (OBPDR) method for smartphones is proposed in this study. First, an improved finite state machine (IFSM) gait detection method is designed, which can improve the gait recognition rate and stability compared with the traditional peak detection method. Second, the step detection algorithm proposed in this paper is combined with a heading estimation to obtain the PDR dynamic model. Finally, the measurements of GNSS are fused to the PDR model, based on an adaptive extended Kalman filter (AEKF) algorithm, which can enhance the adaptability of the system to the environment in order to reduce the cumulative errors of PDR. Experiments are carried out to evaluate the performance of the proposed method. The results indicate that compared with the gait detection method, based on peak detection, and the integrated positioning method, based on an extended Kalman filter, the proposed method boasts favorable robustness and a high gait recognition rate, the recognition accuracy being kept between 97.5% and 98.5%; the average position error decreased by more than 67.25%.