0
我的英文不是很好 - 所以我很抱歉,如果我的問題聽起來有點混亂;)最好的方式來增加晃動識別到你的應用(Android)
我做了一個活動,用於識別強勁的動作。如果我將該活動作爲應用程序中的單個活動啓動,它確實有效。但是現在,我想將活動添加到其他應用程序。我試圖以一種意圖作爲第二項活動開始這項活動。似乎不可能同時運行兩項活動!我不想將第二項活動的功能複製到我的主要活動中 - 保持主要活動的清潔和功能。請告訴我將我的功能(移動識別和烤麪包)添加到我的應用程序的最佳方式。
所以...這是我想從一個活動... whateverItShouldBe更改代碼...
public class SensorActivity extends Activity
implements SensorEventListener{
//static SensorActivity sensorActivity;
// ToDo: test and ACCELMAX for Smartphones and Glasses
// Glasses should have a lower value
private static final int ACCELMAX = 15;
private SensorManager sensorMan;
private Sensor accelerometer;
private float[] mGravity;
private float mAccel;
private float mAccelCurrent;
private float mAccelLast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//sensorActivity = this;
sensorMan=(SensorManager)
getSystemService(SENSOR_SERVICE);
accelerometer=sensorMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mAccel=0.00f;
mAccelCurrent=SensorManager.GRAVITY_EARTH;
mAccelLast=SensorManager.GRAVITY_EARTH;
}
// for closing activity in an other activity
/*
public static SensorActivity getInstance(){
return sensorActivity;
}*/
@Override
public void onResume() {
super.onResume();
sensorMan.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void onPause() {
super.onPause();
sensorMan.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mGravity = event.values.clone();
// Shake detection
float x = mGravity[0];
float y = mGravity[1];
float z = mGravity[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float)Math.sqrt(x * x + y * y + z * z);
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta;
if (mAccel > ACCELMAX) {
// custom toast warning
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.warning_toast, null);
ImageView imgToast = (ImageView) layout.findViewById(R.id.toastImage);
//imgToast.setImageResource(R.drawable.dontrun);
TextView text = (TextView) layout.findViewById(R.id.toastText);
text.setText(""); // the warning is in the background, so we don't need text atm
Toast dontRunToast = Toast.makeText(getApplication(), "", Toast.LENGTH_SHORT);
dontRunToast.setView(layout);
dontRunToast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
dontRunToast.show();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// required method
}
}
THX它們之間的代碼。這是一個我不知道的好方法,但它不是一個保持模塊化的解決方案。 – DasF
你也可以編寫一個常規類來實現SensorEventListener,並在它的約束函數中給它一個LatoutInflator和Context作爲參數。我認爲這也應該起作用 –