Mad 22

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Mad 22

Mainactivity.java
package com.example.practice;

import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements


SensorEventListener {

private SensorManager sensorManager;


private Sensor accelerometer;
private long lastShakeTime;
private static final int SHAKE_INTERVAL = 1000; // Minimum time between
two shake events (in milliseconds)

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);


if (sensorManager != null) {
accelerometer =
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (accelerometer != null) {
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
}

@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long currentTime = System.currentTimeMillis();
if ((currentTime - lastShakeTime) > SHAKE_INTERVAL) {
lastShakeTime = currentTime;
// Detect shake event (you can adjust the threshold as
needed)
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
double acceleration = Math.sqrt(x * x + y * y + z * z);
if (acceleration > 12) { // Adjust the threshold value as
needed
changeBackgroundColor();
}
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Not used, but required to implement SensorEventListener
}

private void changeBackgroundColor() {


RelativeLayout rootLayout = findViewById(R.id.rootLayout);
if (rootLayout != null) {
rootLayout.setBackgroundColor(Color.rgb(
(int) (Math.random() * 256),
(int) (Math.random() * 256),
(int) (Math.random() * 256)
));
}
}

@Override
protected void onDestroy() {
super.onDestroy();
if (sensorManager != null) {
sensorManager.unregisterListener(this);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:gravity="center"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shake your device!"
android:textColor="@android:color/white"
android:textSize="24sp" />

</RelativeLayout>

You might also like