Difficulty making reset button work for pedometer - java

I am working on a pedometer and it runs smoothly. I want to make a button for resetting but its giving me issues.
This is my code below.
public class MainActivity extends Activity implements SensorEventListener {
private TextView textView;
private Button resetButton;
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
private Sensor mStepDetectorSensor;
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.pedometer);
resetButton = (Button) findViewById(R.id.resetButton);
mSensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mStepDetectorSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
int value = -1;
if (values.length > 0) {
value = (int) values[0];
}
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("Step Counter Detected : " + value);
} else if (sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
textView.setText("Step Detector Detected : " + value);
}
}
//check this reset
public void reset(SensorEvent event){
Sensor sensor = event.sensor;
float[] values = event.values;
int value = -1;
if (values.length > 0) {
value = 0;
}
if (sensor.getType() == value) {
textView.setText("Step Counter Detected : " + 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);
}
}
I am connecting the reset method to my button so that when I click it. It resets my pedometer to zero. I have tried different ways but it is not working for me.
I am also unsure because my teacher has taught me to use View v in the parameters. I don't know if that has anything to do with it.

This piece of code is not clear.
if (sensor.getType() == value) {
textView.setText("Step Counter Detected : " + value);
}
Why are you comparing sensor type with value? You have to compare with Sensor.TYPE_STEP_DETECTOR or Sensor.TYPE_STEP_COUNTER.
value is a local variable. So I am assuming you are resetting only for display purpose.
Who is calling reset() function and how is the SensorEvent passed to it?

Related

Cannot resolve method 'registerListener(com.xxx.xxx.MainActivity, android.hardware.SensorManager, int)'

couldn't find a good answer to that problem.
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(MainActivity.this, mSensorManager, SensorManager.SENSOR_DELAY_GAME);
}
Cannot resolve method 'registerListener(com.xxx.xxx.MainActivity, android.hardware.SensorManager, int)'
and I have no idea what to do
Whole activity code:
public class MainActivity extends AppCompatActivity {
private ImageView image, shield;
private float currentDegree = 0f;
private SensorManager mSensorManager;
private TextView tvHeading;
private Location location = new Location("A");
private Location target = new Location("B");
private LocationManager locationManager;
private EditText latitudeInput, longitudeInput;
public GeomagneticField geoField;
private Button setLocationBtn;
Dialog myDialog;
private SensorManager sensorManager;
private Sensor mAccelerometer;
private float[] floatGravity = new float[3];
private float[] floatGeoMagnetic = new float[3];
private float[] floatOrientation = new float[3];
private float[] floatRotationMatrix = new float[9];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.direction);
shield = (ImageView) findViewById(R.id.shield);
tvHeading = (TextView) findViewById(R.id.tvHeading);
setLocationBtn = (Button) findViewById(R.id.button);
myDialog = new Dialog(this);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
//location.setLatitude(54.903535);
//location.setLongitude(23.979342);
target.setLatitude(54.904618);
target.setLongitude(23.978782);
SensorEventListener sensorEventListenerAccelrometer = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
floatGravity = event.values;
SensorManager.getRotationMatrix(floatRotationMatrix, null, floatGravity, floatGeoMagnetic);
SensorManager.getOrientation(floatRotationMatrix, floatOrientation);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
shield.setRotation((float) (-floatOrientation[0] * 180 / 3.14159));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
//mSensorManager.unregisterListener(this); // to stop the listener and save battery
}
//#Override
public void onSensorChanged(SensorEvent event) {
// get the angle around the z-axis rotated
float degree = Math.round(event.values[0]);
degree += geoField.getDeclination();
float bearing = location.bearingTo(target);
degree = (bearing - degree) * -1;
degree = normalizeDegree(degree);
tvHeading.setText("Heading: " + Float.toString(degree) + " degrees");
// create a rotation animation (reverse turn degree degrees)
RotateAnimation ra = new RotateAnimation(
currentDegree,
-degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF,
0.5f);
// how long the animation will take place
ra.setDuration(210);
// set the animation after the end of the reservation status
ra.setFillAfter(true);
// Start the animation
image.startAnimation(ra);
currentDegree = -degree;
}
private float normalizeDegree(float value) {
if (value >= 0.0f && value <= 180.0f) {
return value;
} else {
return 180 + (180 + value);
}
}
public void onSensorChanged2(SensorEvent event) {
// get the angle around the z-axis rotated
float degree = Math.round(event.values[0]);
tvHeading.setText("Heading: " + Float.toString(degree) + " degrees");
// create a rotation animation (reverse turn degree degrees)
RotateAnimation ra = new RotateAnimation(
currentDegree,
-degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF,
0.5f);
// how long the animation will take place
ra.setDuration(210);
// set the animation after the end of the reservation status
ra.setFillAfter(true);
// Start the animation
shield.startAnimation(ra);
currentDegree = -degree;
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// not in use
}
public void ShowPopup(View v) {
myDialog.setContentView(R.layout.popup);
TextView txtclose;
Button setBtn;
txtclose =(TextView) myDialog.findViewById(R.id.exitBtn);
setBtn =(Button) myDialog.findViewById(R.id.setBtn);
txtclose.setText("X");
latitudeInput =(EditText) myDialog.findViewById(R.id.latitudeInput);
longitudeInput =(EditText) myDialog.findViewById(R.id.longitudeInput);
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDialog.dismiss();
}
});
setBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(latitudeInput == null || longitudeInput == null){
Toast.makeText(MainActivity.this, "You did not enter a coordinates", Toast.LENGTH_SHORT).show();
return;
}
else {
target.setLatitude(Double.parseDouble(latitudeInput.getText().toString()));
target.setLongitude(Double.parseDouble(longitudeInput.getText().toString()));
myDialog.dismiss();
}
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
My app should show the direction to a destination like a compass. The user will give a latitude and longitude.
Or maybe you have different ideas about how to make a compass to location
I had faced this problem earlier dealing with the accelerometer. I believe the issue here is that you have not implemented SensorEventListener.
Like this:
public class MainActivity extends AppCompatActivity implements SensorEventListener {
}

How Can I count the number of screen unlocks by a user in Android?

I am currently working on an Android App which informs the number of screen unlocks he/she has done over a day. This example can be seen on stock android devices with API Level P or higher in the feature named Digital Wellbeing. I would like to know how does it work.
You can use Event stats to get unlock count. Try the following code snippet
void getdailyUsageStatistics(long start_time, long end_time){
int unlockcount=0;
UsageEvents.Event currentEvent;
UsageStatsManager mUsageStatsManager = (UsageStatsManager)
getApplicationContext().getSystemService(Context.USAGE_STATS_SERVICE);
if (mUsageStatsManager != null) {
UsageEvents usageEvents = mUsageStatsManager.queryEvents(start_time, end_time);
while (usageEvents.hasNextEvent()) {
currentEvent = new UsageEvents.Event();
usageEvents.getNextEvent(currentEvent);
if (currentEvent.getEventType() == UsageEvents.Event.KEYGUARD_HIDDEN)
{
++unlockcount;
}
}
} else {
Toast.makeText(getApplicationContext(), "Sorry...", Toast.LENGTH_SHORT).show();
}
Log.e("UNLOCK COUNT",unlockcount+" ");
}
You can add reciever like this in your Activity :
private LockScreenStateReceiver mLockScreenStateReceiver;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLockScreenStateReceiver = new LockScreenStateReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mLockScreenStateReceiver, filter);
}
public class LockScreenStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// screen is turn off
//("Screen locked");
} else {
//Handle resuming events if user is present/screen is unlocked
count++;
textView.setText(""+count);
//("Screen unlocked");
}
}
}
#Override
public void onDestroy() {
unregisterReceiver(mLockScreenStateReceiver);
super.onDestroy();
}

My step counter does not reset the steps, even after uninstall

I use Sensor.TYPE_STEP_COUNTER I know it only resets when rebooting. Is there an alternative way to reset the steps to 0 when pressing a button?
Please see my code, you will find the Runactivity.class
Maybe I can do it in another way which resets the steps.
without having me to reboot every time.
public class RunActivity extends AppCompatActivity implements SensorEventListener{
private SensorManager sensorManager;
private TextView count;
boolean activityRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
final String naam = bundle.getString("naam");
TextView NaamView = null;
Button stopRun = (Button) findViewById(R.id.stopRun);
count = (TextView) findViewById(R.id.countView);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
NaamView = (TextView) findViewById(R.id.naamRunText);
NaamView.setText(naam);
stopRun.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String countValue = count.getText().toString();
Log.d("countVAL", String.valueOf(countValue));
Intent myIntent = new Intent(RunActivity.this, HomeScreenActivity.class);
Bundle bundle = new Bundle();
bundle.putString("naam", naam);
sensorManager.flush(RunActivity.this);
sensorManager.unregisterListener(RunActivity.this);
count.setText("0");
onStop();
myIntent.putExtras(bundle);
startActivity(myIntent);
}
});
}
#Override
protected void onResume() {
super.onResume();
activityRunning = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor != null){
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
}else{
Toast.makeText(this, "Jouw apparaat heeft geen sensor!", Toast.LENGTH_LONG) .show();
}
}
#Override
public void onSensorChanged(SensorEvent event) {
if(activityRunning){
count.setText(String.valueOf(event.values[0]));
}else{
event.values[0] = 0;
}
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
activityRunning = false;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
protected void onDestroy() {
super.onDestroy();
}
}
When you click the reset button in the app save the current step count to SharedPreferences. And you'll need a way to find out when was the last reboot because every time you reboot the saved count number gets invalid.
private Integer stepsInSensor;
private Integer stepsAtReset;
void onCreate() {
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
stepsAtReset = prefs.getInt("stepsAtReset", 0);
}
public void onClick(View v) {
stepsAtReset = stepsInSensor;
if (stepsAtReset != null) {
SharedPreferences.Editor editor =
getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("stepsAtReset", stepsAtReset);
editor.commit();
}
// you can now display 0:
count.setText(String.valueOf(0));
}
#Override
public void onSensorChanged(SensorEvent event) {
if(activityRunning){
stepsInSensor = Integer.valueOf(event.values[0]);
if (stepsAtReset = null) {
stepsAtReset = stepsInSensor;
}
int stepsSinceReset = stepsInSensor - stepsAtReset;
if (stepsSinceReset < 0) {
stepsAtReset = stepsInSensor;
stepsSinceReset = 0;
}
count.setText(String.valueOf(stepsSinceReset));
}else{
event.values[0] = 0;
}
}
I searched on it and tried to do it with different ways. Nothing Helped.
Then I found the most simple way possible.
In onSensorChanged() just add the counter so when ever onSensorChanged() will be called (it will be called on every step), counter will simply count the steps then show this counter to your UI instead of showing the value of event.values[0]
on your Reset button make the counter 0 again.
Nope, based on the Sensor API
A sensor of this type returns the number of steps taken by the user
since the last reboot while activated. The value is returned as a
float (with the fractional part set to zero) and is reset to zero only
on a system reboot.
It can only be reset when the system is rebooted

Implement both gyroscope and accelerometer?

I want to get the values of the gyroscope and accelerometer in the phone.
The following is my code
public class MainActivity extends Activity implements SensorEventListener{
private SensorManager sensorManager;
private long lastUpdate;
private GPSTracker gpss;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER && event.sensor.getType() == Sensor.TYPE_GRAVITY) {
getAccelerometer(event);
}
}
private void getAccelerometer(SensorEvent event) {
// TODO Auto-generated method stub
float[] values = event.values;
// Movement
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 10) //
{
if (actualTime - lastUpdate < 200) {
return;
}
lastUpdate = actualTime;
gpss = new GPSTracker(MainActivity.this);
if(gpss.canGetLocation()){
double latitude = gpss.getLatitude();
double longitude = gpss.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpss.showSettingsAlert();
}
}
}
#Override
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
Sensor gsensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
Sensor asensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this,
gsensor,
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this,
asensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
// unregister listener
super.onPause();
sensorManager.unregisterListener(this);
}
}
The code works fine if I use
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
But when I include the *TYPE_GRAVITY* it doesn't work. I think I am making the mistake in the getType() function. Could someone tell me the correct syntax to detect two events simultaneously?
In your code here:
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER
&& event.sensor.getType() == Sensor.TYPE_GRAVITY) {
getAccelerometer(event);
}
}
You're getting the value for the event's type and asking if it's two different things at once. It's no different than having:
int a = 1;
if (a == 1 && a == 2) { ... }
Every SensorEvent is going to have exactly one type. If you want to call your method in either case, use || instead of && in your conditional.
If you want to act independently then you need to have two checks. switch() is a good way to go:
#Override
public void onSensorChanged(SensorEvent event) {
switch(event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
getAccelerometer(event);
break;
case Sensor.TYPE_GRAVITY:
doSomethingDifferent();
break;
}
}
}

Xperia light sensor [Xperia PRO]

public class MainActivity extends Activity implements SensorEventListener {
final String tag = "myLogs";
SensorManager sm = null;
Sensor lightSensor;
float lightQuantity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
lightSensor = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
if(lightSensor == null)
Log.d(tag, "no sensor:(");
else
Log.d(tag, "GOT IT!");
}
#Override
protected void onResume() {
super.onResume();
sm.registerListener((SensorEventListener)this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
sm.unregisterListener((SensorEventListener)this);
super.onStop();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(tag,"onAccuracyChanged: " + sensor.getType() + ", accuracy: " + accuracy);
}
public void onSensorChanged(SensorEvent event) {
lightQuantity = event.values[0];
Log.d(tag,"onSensorChanged: " + event.sensor.getType() + ", result: " + lightQuantity);
}
}
I can't get light sensor stats with this code.
"no sensor:(" message always.
getSensorList() method doesn't show light sensor either.
My device: Xperia PRO (mk16i). SE light sensor test works good
The problem is that Xperia doesn't have the sensor implemented in a standard Android way through drivers.
There's only a proprietary implementation which can be used through reading the kernel variables as detailed below. (c)

Categories