Moving a sprite via a gyroscope - java

So i have 2 questions
first i am curious if its possible to move a sprite via a gyroscope
second if so, do i need to specify the movement of the sprite's X & Y or will that be automatic
and/or do i get the gyro's X & Y movement or is that automatic
#beginner
package com.thejames.thesphere;
import androidx.appcompat.app.AppCompatActivity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ImageView thesphere;
private SensorManager sensorManager;
private Sensor gyroscopeSensor;
private SensorEventListener gyroscopeEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
gyroscopeSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
gyroscopeEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.values(2) > 0.5f) {
//Sphere+Movement
} else if (sensorEvent.values(2) < -0.5f) {
//Sphere-Movement
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
thesphere = findViewById(R.id.thesphere);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(gyroscopeEventListener, gyroscopeSensor, sensorManager.SENSOR_DELAY_FASTEST);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(gyroscopeEventListener);
}
}

Related

Android onCreate of Activity class is not triggered

I am trying to write a plugin for Capacitor. It should pass the accelerometer data to the JavaScript. The bridge works fine.
However, the heading class does not seem to be initialized. The onCreate function does not seem to be executed, so do all the other functions. Nothing is logged to the console.
In AndroidManifest.xml I have requested the following feature:
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
The file looks like this:
package de.example.capmap;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import com.getcapacitor.BridgeActivity;
import de.example.Compass;
public class MainActivity extends BridgeActivity {
private Heading heading;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerPlugin(Compass.class);
heading = new Heading();
}
}
class Heading extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor mAccelerometer;
private static final String TAG = "Heading";
#Override
public final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate: Initializing");
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(Heading.this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onSensorChanged(SensorEvent event){
Log.i(TAG, "onSensorChanged: " + event.values[0]);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.i(TAG, "onAccuracyChanged:" + accuracy);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
}
and the Compass Plugin, which gets executed:
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginHandle;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.Bridge;
#CapacitorPlugin(name = "Compass")
public class Compass extends Plugin {
public static Bridge staticBridge = null;
#Override
public void load() {
staticBridge = this.bridge;
java.lang.System.out.println("Compass successfully started");
}
public static void onMagneticHeading(float magneticHeading){
Compass pushPlugin = Compass.getCompassInstance();
if (pushPlugin != null) {
pushPlugin.sendMagneticHeading(magneticHeading);
}
}
#PluginMethod()
public void getMagneticHeading(PluginCall call) {
String value = call.getString("value");
JSObject ret = new JSObject();
ret.put("magneticHeading", value);
call.resolve(ret);
}
public void sendMagneticHeading(float magneticHeading) {
JSObject data = new JSObject();
data.put("magneticHeading", magneticHeading);
notifyListeners("heading", data, true);
}
public static Compass getCompassInstance() {
if (staticBridge != null && staticBridge.getWebView() != null) {
PluginHandle handle = staticBridge.getPlugin("Compass");
if (handle == null) {
return null;
}
return (Compass) handle.getInstance();
}
return null;
}
}
How come you're extending an Activity instead of just using a plain class? If it's because you want access to a Context, just pass one in through the constructor (you have one when you create the Heading).
If it's because you want the onPause and onResume lifecycle callbacks, so you know when to register/unregister with the SensorManager, there's a couple of things you could do.
First you can just create some methods the activity can call during onPause/onResume:
class Heading(Context context) {
...
public void sleep() {
sensorManager.unregisterListener(this);
}
public void wake() {
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
}
class MainActivity extends BridgeActivity {
...
#Override
protected void onResume() {
super.onResume();
heading.wake();
}
#Override
protected void onPause() {
super.onPause();
heading.sleep();
}
}
The other approach is to make Heading implement DefaultLifecycleObserver, which basically lets you implement onResume and onPause etc like you're doing, and you make it observe the Activity's lifecycle, instead of the Activity having to manually call stuff to be like "hey onPause just happened". I'll just link the example page, but it basically covers what you're doing here (and the earlier, manual example too) as well as some more advanced stuff

onSensorChanged does not called in Emulator

I am using android studio with Android 2.3 emulator. And i cant find why "onSensorChanged" does not called when i change parameters of accelerometer. I searched for the solution through stackoverflow but nothing worked for me.
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor sensor;
private TextView myTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTextView = (TextView) findViewById(R.id.textView3);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this,
sensor,
SensorManager.SENSOR_DELAY_NORMAL);
myTextView.setText("Waiting...");
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor mySensor = event.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
myTextView.setText((int) x);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
As you see i am changing textView3 to the value "Waiting..." and after running the app it is still "Waiting...". Even after i change the parameters of Accelerometer sensor, but it must show the X value.
Update 1
Deleting the "sensorManager.registerListener(this,sensor, SensorManager.SENSOR_DELAY_NORMAL);" in "onCreate" does not solve the problem. And i need exactly Android 2.3
Update 2
Seems like API 9 does not support Accelerometer emulator.
Source: https://stackoverflow.com/a/10612952/7878803

I am working on a simple pedometer app, and it has these errors, for the following code

package com.example.ritwik.letswalk;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SensorEventListener{
TextView tv_steps;
SensorManager sensorManager;
boolean running=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_steps=(TextView) findViewById(r.id.tv_steps);
sensorManager=(SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
#Override
protected void onResume()
{
super.onResume();
running=true;
Sensor countSensor=sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor==null){
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
}
else
Toast.makeText(this, "Sensor Not Found",Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause()
{
super.onPause();
running=false;
}
#Override
protected void onSensorChangeed(SensorEvent event)
{
if(running)
{
tv_steps.setText(String.valueOf(event.values[0]));
}
}
}
the code has the following errors
Error:(21, 15) error: cannot find symbol class TextView
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details. Error:(12, 5) error: cannot find symbol class TextView Error:(43, 37)
error: cannot find symbol class SensorEvent Error:(11, 8) error:
MainActivity is not abstract and does not override abstract method
onAccuracyChanged(Sensor,int) in SensorEventListener Error:(21, 39)
error: package r does not exist Error:(42, 5) error: method does not
override or implement a method from a supertype
SensorEventListener has two abstract methods :
1) onAccuracyChanged(Sensor sensor, int accuracy)
2) onSensorChanged(SensorEvent event)
You need to override onAccuracyChanged method too.
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
This method is called when the accuracy of sensor changes. If you don't wish to do anything here then do not write any code here. But since its abstract you need to implement it.
Hope it helps.
In my pedometer app I did
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
if (values.length > 0) {
value = (int) values[0];
}
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("" + value);
}
}
public void onAccuracyChanged(Sensor sensor,int a){}
If you want the whole code: Here it is:
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class CounterActivity extends Activity implements SensorEventListener {
private TextView textView;
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
private Sensor mStepDetectorSensor;
int value = -1; //Step Counter
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counter_activity);
textView = (TextView) findViewById(R.id.steps);
mSensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mStepDetectorSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}
public void onAccuracyChanged(Sensor sensor,int a){}
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
if (values.length > 0) {
value = (int) values[0];
}
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("" + value);
}
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mStepCounterSensor,
SensorManager.SENSOR_DELAY_FASTEST);
mSensorManager.registerListener(this, mStepDetectorSensor,
SensorManager.SENSOR_DELAY_FASTEST);
}
protected void onStop() {
super.onStop();
mSensorManager.unregisterListener(this, mStepCounterSensor);
mSensorManager.unregisterListener(this, mStepDetectorSensor);
}
}

How can I track how many miles the user has walked?

I have made some java code in android studio to where it counts how many steps someone takes but I'm not sure how I can make it to where it counts how many miles the user walks. Here is the code.
If anyone can tell me how to do it that would be appreciated, Thanks.
package com.example.andyheggis.healthapp;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
TextView tv_steps;
SensorManager sensorManager;
boolean running = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_steps = (TextView) findViewById(R.id.tv_steps);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
#Override
protected void onResume() {
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor != null) {
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(this, "Sensor not found!", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPause() {
super.onPause();
running = false;
//if you unregister the hardware will stop detecting steps
//sensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
if(running) {
tv_steps.setText(String.valueOf(event.values[0]));
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}

Accelerometer application

I must do an application that returns a random number by shaking the phone. I've made it with a button and it works fine. The problems is with the accelerometer. It doesn't works, even though I have no errors.
import java.util.Random;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RandomButtonActivity extends Activity implements SensorEventListener
{
Button tasto1;
TextView testo;
TextView message;
EditText limiteMin;
EditText limiteMax;
Random generator = new Random();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
testo = (TextView) findViewById(R.id.textView1);
limiteMin = (EditText) findViewById(R.id.editText2);
limiteMax = (EditText) findViewById(R.id.EditText01);
}
public void onSensorChanged(SensorEvent event)
{
Sensor sensor = event.sensor;
if (sensor.getType()==Sensor.TYPE_ACCELEROMETER)
{
int j = Integer.parseInt(limiteMin.getText().toString());
int i = Integer.parseInt(limiteMax.getText().toString())-j;
int x = 0;
if(i==0 && j==0)
{
x = generator.nextInt();
while(x<0)
{
x = generator.nextInt();
}
}
else
{
if(j>=i)
{
i = 0;
j = 0;
}
else
{
x = generator.nextInt(i+1)+j;
testo.setText(""+x);
}
}
testo.setText(""+x);
}
else
{
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
}
Looking around the internet this code should work just fine. I've done nothing to the XML file.
EDIT:
I added:
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true"
to Android:manifest but nothing has changed.
It seems that you never add your class as an event listener.
This code works for me:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//This is what you are missing:
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
}
public void onSensorChanged(SensorEvent event)
{
Sensor sensor = event.sensor;
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
/// Do something
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
It is also a good idea to override onResume/onStop/onPause like this
#Override protected void onResume()
{
super.onResume();
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
#Override protected void onStop()
{
sm.unregisterListener(this);
super.onStop();
}
And as ernell mentioned always remember to have the permissions you need in the manifest.

Categories