-1

我对 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 = nullspeed = 0.0

屏幕旋转,onSaveInstanceState方法显示outState = Bundle[{speed=0.0}],然后2秒后它没有到达onRestoreInstanceStateonCreate再次崩溃

4

2 回答 2

0

将其替换onCreate

@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_debug);

        if(savedInstanceState != null){
            speed = savedInstanceState.getDouble("speed");
        }

        gpsM = new GPSManager();
        gpsM.startListening(getApplicationContext());
        gpsM.setGPSCallback(this);
        conS = new ConvertSpeed();
    }

onSaveInstanceState_

 @Override
    public void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);
        outState.putDouble("speed",speed);
    }

删除这个onRestoreInstanceState

 @Override
    public void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        speed = savedInstanceState.getDouble("speed");
    }

在你这样做之后,它应该可以正常工作

于 2013-11-01T23:11:23.983 回答
0

我更深入地查看了调试日志(在 3075 次谷歌搜索之后......),错误似乎是我没有打电话super.onDestroy()!它现在似乎工作!

于 2013-11-04T16:10:58.003 回答