有两种方法可以轻松做到:
第一种方式:为类使用全局变量:
String SubPos;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mAccVals = new Number3d();
Bundle extras = getIntent().getExtras();
SubPos = extras.getString("subposition1"); //note that I've deleted the 'String'
}
2n方式:将变量传递给方法:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mAccVals = new Number3d();
Bundle extras = getIntent().getExtras();
String SubPos = extras.getString("subposition1");
otherMethod(SubPos);
}
public void otherMethod(String s) {
//do stuff.
}
我认为也许你想在另一个类中使用这个变量,然后你可以添加这个函数(在类中将 String SubPos 作为全局):
String SubPos;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mAccVals = new Number3d();
Bundle extras = getIntent().getExtras();
SubPos = extras.getString("subposition1"); //note that I've deleted the 'String'
}
public String getSubPos() {
return SubPos;
}
这样,您可以在任何其他具有该实例的类中调用 instanceOfTheClass.getSubPos()。