我对 Android 编程相对较新,我被困在一个(可能很简单)问题上。我已经尝试了几个小时的胡闹,但一无所获......
我的代码如下,当设备旋转并重新启动活动时,它会停止应用程序。我使用了 onSaveInstanceState 和 onRestoreInstanceState 方法,但它们对我没有帮助!有人可以看看吗:
public class DebugActivity extends Activity implements GPSCallback{
private GPSManager gpsM=null;
private ConvertSpeed conS =null;
private double speed = 0.0;
@Override
public void onCreate(Bundle savedInstanceState){
if(savedInstanceState != null){
speed = savedInstanceState.getDouble("speed");
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_debug);
gpsM = new GPSManager();
gpsM.startListening(getApplicationContext());
gpsM.setGPSCallback(this);
conS = new ConvertSpeed();
}
@Override
public void onSaveInstanceState(Bundle outState){
outState.putDouble("speed",speed);
super.onSaveInstanceState(outState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
speed = savedInstanceState.getDouble("speed");
}
@Override
public void onDestroy(){
gpsM.stopListening();
gpsM.setGPSCallback(null);
gpsM = null;
}
@Override
public void onGPSUpdate(Location location) {
location.getLatitude();
location.getLongitude();
speed = location.getSpeed();
String speedString = "" + conS.convertSpeed(speed,2);
TextView debug1 = ((TextView)findViewById(R.id.tvSpeed));
debug1.setText(speedString);
}
}
调试:
方法中onCreate
,Activity第一次运行:
if(savedInstanceState != null){
speed = savedInstanceState.getDouble("speed");
它显示outState = null
和speed = 0.0
屏幕旋转,onSaveInstanceState
方法显示outState = Bundle[{speed=0.0}]
,然后2秒后它没有到达onRestoreInstanceState
或onCreate
再次崩溃