一、添加Timer、MotionSensor控件
设置Timer1.Interval值为100、开启Vibrate震动权限。
代码:
var x1,x2:integer; //全局变量
uses
Androidapi.Helpers,
Androidapi.JNI.Os,
Androidapi.JNI.JavaTypes,
Androidapi.JNIBridge,
Androidapi.JNI.Provider,
Androidapi.JNI.GraphicsContentViewText;
procedure TMain.Timer1Timer(Sender: TObject);
var
x,y,z:integer; //x,y,z轴取整绝对值
LVibratorObj: JObject;
LVibrator: JVibrator;
begin
LVibratorObj := SharedActivity.getSystemService(TJContext.JavaClass.VIBRATOR_SERVICE);
LVibrator := TJVibrator.Wrap((LVibratorObj as ILocalObject).GetObjectID);
x:=round(Abs(MotionSensor1.Sensor.AccelerationX) * 100);
y:=round(Abs(MotionSensor1.Sensor.AccelerationY) * 100);
z:=round(Abs(MotionSensor1.Sensor.AccelerationZ) * 100);
if Timer1.Tag=0 then
begin
x1:=x + y + z; //取第一次三轴相加值
Timer1.Tag:=1;
end
else
begin
x2:=x + y + z; //取第二次三轴相加值
Timer1.Tag:=0;
end;
if (Timer1.Tag=0) and (Abs(x1 - x2)>280) then //当两次取值相差大于预定值(这个值和Timer.Inteval值需要自己测试一个合适的)时,震动并执行……
begin
LVibrator.vibrate(50);
……
end;
end;