利用加速度传感器实现摇红包
- 布局文件:需要两个,一个用来显示主界面(里面不用加什么组件,加个背影图就可以),一个显示红包的xml(加一个imageView就可以,用AlertDialog来调用)
主:
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:background="#0f0"
android:layout_height="match_parent" tools:context="com.example.acceleratedemo.MainActivity">
</android.support.constraint.ConstraintLayout>
显示红包的xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:src="@drawable/hongbao"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
- 加速度传感器有三个值,分别是xyz轴上的加速度,如果有加速度,就证明你的手机在移动,所以可以用这个来实现摇红包
import android.app.AlertDialog;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SensorEventListener{
private SensorManager sensorManager;
//定义震动器
private Vibrator vibrator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取sensorManager
sensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);
vibrator= (Vibrator) getSystemService(VIBRATOR_SERVICE);
}
//在onResume方法中注册Sensor
@Override
protected void onResume() {
sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_GAME);
super.onResume();
}
@Override
public void onSensorChanged(SensorEvent event) {
int type=event.sensor.getType();
float [] values=event.values;
if (type==Sensor.TYPE_ACCELEROMETER){
if(values[0]>10||values[1]>10||values[2]>20){
Toast.makeText(this, "你正在摇= =", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setView(R.layout.hongbao);
builder.show();
//设置震动的时间0.5s
vibrator.vibrate(500);
sensorManager.unregisterListener(this);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
因为用到了震动器,所以要在MainManifest.xml中获取权限
<uses-permission android:name="android.permission.VIBRATE"></uses-permission>