この例は役立つかもしれません..
例によるより良い学習
package com.commonsware.android.shaker;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;
public class ShakerDemo extends Activity
implements Shaker.Callback {
private Shaker shaker=null;
private TextView transcript=null;
private ScrollView scroll=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
transcript=(TextView)findViewById(R.id.transcript);
scroll=(ScrollView)findViewById(R.id.scroll);
shaker=new Shaker(this, 1.25d, 500, this);
}
@Override
public void onDestroy() {
super.onDestroy();
shaker.close();
}
public void shakingStarted() {
Log.d("ShakerDemo", "Shaking started!");
transcript.setText(transcript.getText().toString()+"Shaking started\n");
scroll.fullScroll(View.FOCUS_DOWN);
}
public void shakingStopped() {
Log.d("ShakerDemo", "Shaking stopped!");
transcript.setText(transcript.getText().toString()+"Shaking stopped\n");
scroll.fullScroll(View.FOCUS_DOWN);
}
}
package com.commonsware.android.shaker;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.SystemClock;
import java.util.ArrayList;
import java.util.List;
public class Shaker {
private SensorManager mgr=null;
private long lastShakeTimestamp=0;
private double threshold=1.0d;
private long gap=0;
private Shaker.Callback cb=null;
public Shaker(Context ctxt, double threshold, long gap,
Shaker.Callback cb) {
this.threshold=threshold*threshold;
this.threshold=this.threshold
*SensorManager.GRAVITY_EARTH
*SensorManager.GRAVITY_EARTH;
this.gap=gap;
this.cb=cb;
mgr=(SensorManager)ctxt.getSystemService(Context.SENSOR_SERVICE);
mgr.registerListener(listener,
mgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
public void close() {
mgr.unregisterListener(listener);
}
private void isShaking() {
long now=SystemClock.uptimeMillis();
if (lastShakeTimestamp==0) {
lastShakeTimestamp=now;
if (cb!=null) {
cb.shakingStarted();
}
}
else {
lastShakeTimestamp=now;
}
}
private void isNotShaking() {
long now=SystemClock.uptimeMillis();
if (lastShakeTimestamp>0) {
if (now-lastShakeTimestamp>gap) {
lastShakeTimestamp=0;
if (cb!=null) {
cb.shakingStopped();
}
}
}
}
public interface Callback {
void shakingStarted();
void shakingStopped();
}
private SensorEventListener listener=new SensorEventListener() {
public void onSensorChanged(SensorEvent e) {
if (e.sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
double netForce=e.values[0]*e.values[0];
netForce+=e.values[1]*e.values[1];
netForce+=e.values[2]*e.values[2];
if (threshold<netForce) {
isShaking();
}
else {
isNotShaking();
}
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// unused
}
};
}