<
1
>
public
class
SensorTestActivity
extends
Activity
{
private
SensorManager sm;
private
SensorEventListener accL;
private
Sensor accSensor;
MyView image;
@Override
public
void
onCreate(Bundle savedInstanceState)
{
super
.onCreate(savedInstanceState);
image =
new
MyView(
this
,
null
);
setContentView(image);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
accSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
accL =
new
accListener();
}
@Override
protected
void
onPause()
{
super
.onPause();
if
(sm !=
null
)
{
sm.unregisterListener(accL);
}
}
@Override
protected
void
onResume()
{
super
.onResume();
sm.registerListener(accL, accSensor, SensorManager.SENSOR_DELAY_GAME);
}
private
class
accListener
implements
SensorEventListener
{
private
float
history =
0
;
@Override
public
void
onSensorChanged(SensorEvent event)
{
if
(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
float
x = event.values[SensorManager.DATA_X];
image.move(x,
10
,
10
);
Log.d(
""
,
"x:"
+ x);
}
}
@Override
public
void
onAccuracyChanged(Sensor arg0,
int
arg1)
{
}
}
}
<
2
>
public
class
MyView
extends
View {
private
Drawable image;
private
int
viewWidth;
private
int
viewHeight;
private
int
imageWidth;
private
int
imageHeight;
private
float
x;
private
float
y;
private
float
z;
public
MyView(Context context, AttributeSet attrs) {
super
(context, attrs);
image =
this
.getResources().getDrawable(R.drawable.messages);
}
public
void
move(
float
mx,
float
my,
float
mz)
{
this
.x -= (mx * 4f);
this
.y += (my * 4f);
this
.x += (mz * 4f);
if
(
this
.x <
0
)
{
this
.x =
0
;
}
else
if
((
this
.x + imageWidth) >
this
.viewWidth)
{
this
.x =
this
.viewWidth - imageWidth;
}
if
(
this
.y <
0
)
{
this
.y =
0
;
}
else
if
((
this
.y + imageHeight) >
this
.viewHeight)
{
this
.y =
this
.viewHeight - imageHeight;
}
if
(
this
.z < -
9.8
)
{
Log.i(
"이미지"
,
"작아짐"
);
}
else
if
(
this
.z > -
9.8
)
{
Log.i(
"이미지"
,
"커짐"
);
}
Log.i(
"SENSOR"
,
"move - [this.x]"
+ x +
"[this.y] "
+ y+
"[mx]"
+ mx +
"[my]"
+ my);
this
.invalidate();
}
@Override
protected
void
onSizeChanged(
int
w,
int
h,
int
oldw,
int
oldh) {
this
.viewWidth =
this
.getWidth();
this
.viewHeight =
this
.getHeight();
imageWidth = image.getIntrinsicWidth();
imageHeight = image.getIntrinsicHeight();
this
.x = (
float
)((viewWidth /
2
) - (imageWidth /
2
));
this
.y = (
float
)((viewHeight /
2
) - (imageHeight /
2
));
super
.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected
void
onDraw(Canvas canvas) {
int
xx = (
int
)(
this
.x);
int
yy = (
int
)(
this
.y);
int
zz = (
int
)(
this
.z);
image.setBounds(xx, yy, xx+imageWidth, yy+imageHeight );
image.draw(canvas);
super
.onDraw(canvas);
}
}