本文介绍了Android 加速度传感器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用加速度计传感器.所以我试过这个例子:http://blog.androgames.net/85/android-accelerometer-tutorial/一个>
I am trying to work with Accelerometer Sensor. So i tried thisexample:http://blog.androgames.net/85/android-accelerometer-tutorial/
它完美地工作.但是当我将 AccelerometerManager 活动更改为服务时,它不起作用并且出现错误.
It work perfectly.But when i change AccelerometerManager activity to a service, it doesn't work and i got an error.
//this is the activity that i want change
public class Accelerometer extends Activity
implements AccelerometerListener {
private static Context CONTEXT;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CONTEXT = this;
}
protected void onResume() {
super.onResume();
if (AccelerometerManager.isSupported()) {
AccelerometerManager.startListening(this);
}
}
protected void onDestroy() {
super.onDestroy();
if (AccelerometerManager.isListening()) {
AccelerometerManager.stopListening();
}
}
public static Context getContext() {
return CONTEXT;
}
/**
* onShake callback
*/
public void onShake(float force) {
Toast.makeText(this, "Phone shaked : " + force, 1000).show();
}
/**
* onAccelerationChanged callback
*/
public void onAccelerationChanged(float x, float y, float z) {
((TextView) findViewById(R.id.x)).setText(String.valueOf(x));
((TextView) findViewById(R.id.y)).setText(String.valueOf(y));
((TextView) findViewById(R.id.z)).setText(String.valueOf(z));
}
}
//这是我更改时的服务,我的错误是 hir public
//this is my service when i change it, my error is hir public
class Accelerometer extends Service implements AccelerometerListener{ private static Context CONTEXT;
@Override
public IBinder onBind(Intent intent) {
// TODO Put your code here
return null;
}
@Override
public void onCreate() {
System.out.println("start listening");
// if (AccelerometerManager.isSupported()) { AccelerometerManager.startListening(this);
// }
}
@Override
public void onDestroy() {
System.out.println("start listening");
// if (AccelerometerManager.isListening()) { AccelerometerManager.stopListening();
// }
}
public static Context getContext() {
return CONTEXT;
}
/**
* onShake callback
*/
public void onShake(float force) {
Toast.makeText(this, "Phone shaked niktilha omha ya 3ammi el7ag: " + force, 1000).show(); }
/**
* onAccelerationChanged callback
*/
public void onAccelerationChanged(float x, float y, float z) { System.out.println("x = "+x+" y = "+y+" z = "+z); }
}
感谢您的帮助.
推荐答案
对于 CONTEXT 尝试将其初始化为
For CONTEXT try initializing it as
this.getApplicationContext()
这篇关于Android 加速度传感器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!