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)
Related
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 {
}
I have google searched this with no success and seams very strange to me.
I am building a simple GPS app that send co-ordinates with HttpRequest, though I have noticed when minimising the UI then maximising, It runs a duplicate of the same activity. and doubles up on HttpRequest's
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
processExtraData();
}
private void processExtraData() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
10000, 5, this);
}
#Override
public void onLocationChanged(Location location) {
Bundle extras = getIntent().getExtras();
String driver_id = extras.getString("driverid");
String msg = "Driver:" + driver_id + "\nCurrent Location:\nLatitude: " + location.getLatitude()
+ "\nLongitude: " + location.getLongitude();
new HttpRequestTask(
new HttpRequest("https://www.autoflora.net/driver/gps.php?user_id=" + driver_id + "&latlong=" + location.getLatitude() + "*" + location.getLongitude(), HttpRequest.POST, "{ \"some\": \"data\" }"),
new HttpRequest.Handler() {
#Override
public void response(HttpResponse response) {
if (response.code == 200) {
Log.d(this.getClass().toString(), "Request successful!");
} else {
Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
}
}
}).execute();
String s = calc.getText().toString();
calc.setText(s + "1")
TextView driver = (TextView) findViewById(R.id.driver);
driver.setText("" + driver_id);
TextView Longitude = (TextView) findViewById(R.id.longitude);
// Getting reference to TextView tv_latitude
TextView Latitude = (TextView) findViewById(R.id.latitude);
// Setting Current Longitude
Longitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
Latitude.setText("Latitude:" + location.getLatitude());
// Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
noticed when minimising the UI then maximising
There's neither minimising nor maximizing of UI on Android. You apparently start the activity again via launcher (this is most likely your maximizing thing) which creates new instance of you activity. If you want just single instance allowed no matter what, you must set system so by using android:launchMode in declaration of activity in your manifest file. See docs here for possible options.
#Override
public void onStart() {
super.onStart();
Toast.makeText(getBaseContext(), "start", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(this);
}
#Override
public void onResume() {
super.onResume();
Toast.makeText(getBaseContext(), "resume", Toast.LENGTH_LONG).show();
locationcheck(); // checks permissions
}
#Override
public void onPause() {
super.onPause();
Toast.makeText(getBaseContext(), "pause", Toast.LENGTH_LONG).show();
}
#Override
public void onStop() {
super.onStop();
// locationManager.removeUpdates(this);
Toast.makeText(getBaseContext(), "stop", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getBaseContext(), "destroy", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(this);
finish();
}
Seems to have fixed it..
I am currently making an application where I need to get the user's location when a button is clicked. I am using this sample and it works great as a sample application. My question is, how would I implement it into my application button's onClick event? I don't need it to refresh often, I just need it so that when the user clicks the button, it gets the user's latitude and longitude and saves them to two variables. What would be the best way to do this? I didn't post my own code because all I have is a button with an onClick event.
Follow these steps to get the location on button click:
Implement LocationListener in your activity like:
public class MainActivity Extends AppCompactActivity implements LocationListener
Then create an Instance For LocationManager, longitude, and latitude as below:
LocationManager locationManager; // create global outside all methods
Double currentLattitude, currentLongitude;
Set click event on your button as below:
btnLocation.setOnClickListner( new View.onClickListner
{
#Override
public void onClick(View v)
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
});
Now implement method for LocationListener as below:
#Override
public void onLocationChanged(Location location) {
currentLattitude = location.getLatitude();
currentLongitude = location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
With this, you can get your location via on click of your button.
Main thing to don't forget is to set permission (in your Manifest) as below:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Use fused location API this is the fastest from all others.
public class LocationActivity extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
Button btnFusedLocation;
TextView tvLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_main);
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
btnFusedLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
updateUI();
}
});
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
} else {
Log.d(TAG, "location is null ...............");
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
}
LocationListener provides call back for location change through onLocationChanged.
GoogleApiClient.ConnectionCallbacks provides call back for GoogleApiClient onConnected.
GoogleApiClient.OnConnectionFailedListener provides call back for GoogleApiClient onConnectionFailed.
Source: http://javapapers.com/android/android-location-fused-provider/
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?
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