I'm creating my own version of the api example (http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/Compass.html) to create a compass. The only diff开发者_运维技巧erence between my code and the api example is that the sensorEventListener is created in an activity instead of the imageView itself. Can that be the cause why the sensorEventListener isn't working? The widget works, only the onsensorChanged is never called.
My Custom Widget Class:
package be.helloworld.widgets;
import android.content.Context;
import android.graphics.Canvas;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.AttributeSet;
import android.util.Config;
import android.util.Log;
import android.widget.ImageView;
public class Compass extends ImageView{
private static final String TAG = "Compass";
private SensorManager mSensorManager;
private Sensor mSensor;
// private SampleView mView;
private float[] mValues;
private final SensorEventListener mListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent event) {
if (Config.DEBUG) Log.d(TAG, "sensorChanged (" + event.values[0] + ", " + event.values[1] + ", " + event.values[2] + ")");
mValues = event.values;
/* if (mView != null) {
mView.invalidate();
}*/
invalidate();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
public CarPassCompass(Context context) {
super(context);
initSensor(context);
}
public CarPassCompass(Context context, AttributeSet set) {
super(context, set);
initSensor(context);
}
public void initSensor(Context context) {
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
/*mView = new SampleView(this);
setContentView(mView);*/
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
int w = canvas.getWidth();
int h = canvas.getHeight();
int cx = w / 2;
int cy = h / 2;
canvas.translate(cx, cy);
if (mValues != null) {
canvas.rotate(-mValues[0]);
}
}
}
my xml-file:
<be.helloworld.widgets.Compass
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/kompas_arrow"
/>
That should not be the cause. One important line I do not see in your code is:
mSensorManager.registerListener(mListener, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_GAME);
Also, do not forget to unregister it as well. You should put them in onResume()/onStop() pair.
精彩评论