2012-05-12 45 views
0

在您的幫助和互聯網上的一些指南,我設法淘汰這段代碼。但是我發現自己遇到了一些問題,根據我的想法,應用程序應該在電話被震動時啓動媒體播放器,然後啓動一次,但現在每次電話被震動時都會啓動媒體播放器。此外,我想的是,應用工作,在屏幕關閉的時候,手機晃動啓動媒體播放器和屏幕開啓時加速度傳感器和媒體播放器

public class SensorTestActivity extends Activity implements SensorEventListener { 
private SensorManager sensorManager; 
private boolean color = false; 
private View view; 
private long lastUpdate; 
MediaPlayer mMediaPlayer; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
requestWindowFeature(Window.FEATURE_NO_TITLE); 
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
WindowManager.LayoutParams.FLAG_FULLSCREEN); 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
view = findViewById(R.id.textView); 
view.setBackgroundColor(Color.BLUE); 
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 
sensorManager.registerListener(this, 
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
SensorManager.SENSOR_DELAY_NORMAL); 
lastUpdate = System.currentTimeMillis(); 
} 

@Override 
public void onSensorChanged(SensorEvent event) { 
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { 
getAccelerometer(event); 
} 
} 
private void getAccelerometer(SensorEvent event) { 
float[] values = event.values; 
// Movement 
float x = values[0]; 
float y = values[1]; 
float z = values[2]; 

float accelationSquareRoot = (x * x + y * y + z * z)/(SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH); 
long actualTime = System.currentTimeMillis(); 
if (accelationSquareRoot >= 2) // 
{ 
if (actualTime - lastUpdate < 200) { 
return; 
} 
lastUpdate = actualTime; 
Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT).show(); 
if (color) { 
view.setBackgroundColor(Color.GREEN); 

try { 

mMediaPlayer = MediaPlayer.create(getBaseContext(), R.raw.mymusic); 

mMediaPlayer.setLooping(false); 
mMediaPlayer.start(); 
mMediaPlayer.setOnCompletionListener(new 
OnCompletionListener() { 
public void onCompletion(MediaPlayer arg0) { 
// if (mMediaPlayer != null) { 
// mMediaPlayer.release(); 
// mMediaPlayer = null; 
// } 
} 
}); 
} catch (Exception e) { 
if (mMediaPlayer != null) { 
mMediaPlayer.release(); 
mMediaPlayer = null; 
} 
}     
} 
} else { 
view.setBackgroundColor(Color.RED); 
} 
color = !color; 
} 

@Override 
public void onAccuracyChanged(Sensor sensor, int accuracy) { 
} 

@Override 
protected void onResume() { 
super.onResume(); 
// register this class as a listener for the orientation and 
// accelerometer sensors 
sensorManager.registerListener(this, 
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
SensorManager.SENSOR_DELAY_NORMAL); 
} 

@Override 
protected void onPause() { 
// unregister listener 
super.onPause(); 
sensorManager.unregisterListener(this); 
} 
} 

回答

0

可以只接一次啓動的東西,添加一個布爾值。

boolean startOnce = true; 

if (startOnce) { 
.... 
startOnce = false; 
} 
+0

對不起,但在我的代碼中,我必須插入帶「if」結構的布爾變量? – bisssi