Implement both gyroscope and accelerometer? - java

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;
}
}
}

Related

Starting app when it shakes using broadcast

What I want is that when my app is in background and I shake the phone the app should start and come on foreground!
To achieve this I have used broadcast receiver as follows :
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
mSensorManager = (SensorManager) arg0.getSystemService(arg0.SENSOR_SERVICE);
mSensorManager.registerListener( mSensorIntentListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
}
I have registered it also as follows :
<receiver
android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
Now for shake event I am using this code as given below :
private final SensorEventListener mSensorIntentListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta; // perform low-cut filter
if (mAccel > 12) {
Toast.makeText(getApplicationContext(), "Device has shaken.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
};
Now when I try to run the app and put it on background and shake it doesn't works !
So what is the logical error and how to make my app come foreground on shake ?
One more thing I am using nested classes concept so all classes are in MainActivity class !
code full !
:
package com.example.sensorlist;
public class MainActivity extends ActionBarActivity {
TextView tv1=null;
static File file = null;
private String outputFile = null;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity
Button play,stop,record;
MediaRecorder myAudioRecorder;
public SensorManager mSensorManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.button3);
stop=(Button)findViewById(R.id.button2);
record=(Button)findViewById(R.id.button);
stop.setEnabled(false);
play.setEnabled(false);
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
//Environment.DIRECTORY_DCIM
Environment.DIRECTORY_DCIM + "/Utkarshrecord/"
);
// Make sure the sound directory exists.
if(!path.exists())
{
path.mkdirs();
}
try {
file= File.createTempFile("sound", ".3gp", path);
myAudioRecorder=new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setOutputFile(file.getAbsolutePath());
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
if( mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)!=null){
Toast.makeText(getBaseContext(), "Yes it is there ", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getBaseContext(), "Sry no accelerometer", Toast.LENGTH_LONG).show();
}
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
try{
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
}catch(Exception e){
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
stop.setEnabled(false);
play.setEnabled(true);
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
MediaPlayer m = new MediaPlayer();
try {
m.setDataSource(file.getAbsolutePath());
m.prepare();
}
catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
});
}
private final SensorEventListener mSensorListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta; // perform low-cut filter
if (mAccel > 12) {
Toast.makeText(getApplicationContext(), "Device has shaken.", Toast.LENGTH_LONG).show();
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
record.setEnabled(false);
stop.setEnabled(true);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "recording has started", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
};
private final SensorEventListener mSensorIntentListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta; // perform low-cut filter
if (mAccel > 12) {
Toast.makeText(getApplicationContext(), "Device has shaken.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
};
#Override
protected void onPause() {
mSensorManager.unregisterListener(mSensorListener);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
#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 boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class ShakeRec extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
}
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
mSensorManager = (SensorManager) arg0.getSystemService(arg0.SENSOR_SERVICE);
mSensorManager.registerListener( mSensorIntentListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
}
}
Your <receiver> element will not work. If you were to look at LogCat on a reboot, you would see warnings or errors from Android, saying that it cannot find your BootReceiver class. A manifest-registered receiver cannot be a nested class inside of an activity.
Get rid of the <receiver> element. Get rid of BootReceiver. Register your SensorEventListener in onCreate() of your activity. So long as your process is running (which may not be very long), and so long as the device is turned on, you should receive sensor events.
To capture shakes you should use always-on low power sensors, registered in a wakelocked sticky service. To reach a great amount of devices, your app should find what of that low power sensors are available in the phone. And then use the best combination, minimizing battery power drain. You will need also to ensure your app is whitelisted for battery optimization, so your app can survive in background.

Difficulty making reset button work for pedometer

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?

SensorEventListener in a service

im trying to implement the SensorEventListener but for some reason nothing happend.
ive tired to created a separate class for the listener but its still not working.
the service is running in a separate thread.(in the manifest android:process=":myproces")
public class Servicee extends Service {
private SensorManager sensorManager;
private long lastUpdate;
SensorEventListener listen;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
sensorManager = (SensorManager) getApplicationContext()
.getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
listen = new SensorListen();
return START_STICKY;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Started", 1000).show();
super.onCreate();
}
private void getAccelerometer(SensorEvent event) {
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 >= 7) //
{
if (actualTime - lastUpdate < 2000) {
return;
}
lastUpdate = actualTime;
Toast.makeText(this,
"Device was shuffed _ " + accelationSquareRoot,
Toast.LENGTH_SHORT).show();
Vibrator v = (Vibrator) getApplicationContext().getSystemService(VIBRATOR_SERVICE);
v.vibrate(1000);
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
sensorManager.unregisterListener(listen);
Toast.makeText(this, "Destroy", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
public class SensorListen implements SensorEventListener{
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
what could possibly be wrong with it?
I believe the problem, at least with the code presented is that you never register to receive accelerometer events.
You need code to get the accelerometer sensor and to register; this should go in onStartCommand() right before the return.
Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(listen, accel, SensorManager.SENSOR_DELAY_NORMAL);

Showing my track with Google map api v2 in android

I am trying to make an app that will show my current location and will track me from there with a line.I have been using Google maps Api v2 for android so i was trying to work with polylines to help me show my tracks but its not showing.
Can anyone help me with that..Thankyou.
Total code is provided.
public class MainActivity extends FragmentActivity implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener,
OnMyLocationButtonClickListener, OnClickListener, android.location.LocationListener {
private GoogleMap mMap;
private LocationClient mLocationClient;
private TextView mMessageView;
private boolean setIt;
// These settings are the same as the settings for the map. They will in fact give you updates
// at the maximal rates currently possible.
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location_demo);
mMessageView = (TextView) findViewById(R.id.message_text);
Button b1=(Button)findViewById(R.id.start);
Button b2=(Button)findViewById(R.id.stop);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setUpLocationClientIfNeeded();
mLocationClient.connect();
}
#Override
public void onPause() {
super.onPause();
if (mLocationClient != null) {
mLocationClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(
getApplicationContext(),
this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
/**
* Button to get current Location. This demonstrates how to get the current Location as required
* without needing to register a LocationListener.
*/
public void showMyLocation(View view) {
if (mLocationClient != null && mLocationClient.isConnected()) {
String msg = "Location = " + mLocationClient.getLastLocation();
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (v.getId() == R.id.start) {
setIt = true;
};
if (v.getId() == R.id.stop) {
mMap.clear();
};
}
PolylineOptions rectOptions = new PolylineOptions().width(3).color(
Color.RED);
#Override
public void onLocationChanged(Location location) {
mMessageView.setText("Location = " + location);
rectOptions.add(new LatLng(location.getLatitude(), location.getLongitude()));
if (setIt == true){
mMap.addPolyline(rectOptions);
}
}
#Override
public void onConnected(Bundle connectionHint) {
mLocationClient.requestLocationUpdates(
REQUEST,
this); // LocationListener
}
/**
* Callback called when disconnected from GCore. Implementation of {#link ConnectionCallbacks}.
*/
#Override
public void onDisconnected() {
// Do nothing
}
/**
* Implementation of {#link OnConnectionFailedListener}.
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
// Do nothing
}
#Override
public boolean onMyLocationButtonClick() {
{
setIt = true;
};
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
This is very easy to in Google Map API V2 . If you would like to do this then you can follow this reference link:
Go this stackoverflow link
This man already give useful solution. I have done the same way as this site told.
For your facility I have written the main things:
1.create a list of LatLng points such as:
List<LatLng> routePoints;
2.Add the route points to the list (could/should be done in a loop):
routePoints.add(mapPoint);
3.Create a Polyline and feed it the list of LatLng points as such:
Polyline route = map.addPolyline(new PolylineOptions()
.width(_strokeWidth)
.color(_pathColor)
.geodesic(true)
.zIndex(z));
route.setPoints(routePoints);
Try this and give feedback!!!

Service not stop after click

I've got a service that starts when i click a toggle button. It works well but when i click again the toggle i would expect the service stops but doesn't work. The service still go. This is the button(I'm using the preferences to save the state of the button):
check = (ToggleButton)v.findViewById(R.id.check1);
final SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean tgprefshake = preferences.getBoolean("tgprefshake", false); //default is true
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){ //do this}
Log.d("Service", "onClick: starting srvice");
myService = new Intent(getActivity(), shakeService.class);
//getActivity().startService(new Intent(getActivity(), shakeService.class));
getActivity().startService(myService);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgprefshake", true); // value to store
editor.commit();
} else {
Log.d("Service", "onClick: stopping srvice");
//getActivity().stopService(new Intent(getActivity(), shakeService.class));
getActivity().stopService(myService);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgprefshake", false); // value to store
editor.commit();
}
}
});
if (tgprefshake) //if (tgpref) may be enough, not sure
{
check.setChecked(true);
}
else
{
check.setChecked(false);
}
And the service:
public class shakeService extends Service implements SensorEventListener{
// Sensors
public SensorManager sensorManager;
private long lastUpdate;
public ToggleButton check ;
public Sensor mAccelerometer;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate()
{
Log.d("", "onCreate");
super.onCreate();
}
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
Log.d("Service", "onDestroy");
}
public void onStart(Intent intent, int startId)
{
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
lastUpdate = System.currentTimeMillis();
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getWifiVibrating(event);
}
}
private void getWifiVibrating(SensorEvent event) {
//myVib.vibrate(50);
final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
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 >= 3) {
if (actualTime - lastUpdate < 600) {
return;
}
lastUpdate = actualTime;
wifiManager.setWifiEnabled(true);
Toast.makeText(this, "Wi-fi On", Toast.LENGTH_SHORT)
.show();
}
}
public void onResume() {
// register this class as a listener for the orientation and
// accelerometer sensors
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
public void onPause() {
// unregister listener
sensorManager.unregisterListener(this);
}
Where is the error? It shows me "Service Stopped" when i turn off the toggle but still the service still works.
Call super.onDestroy() in the end of the service's onDestroy() impementation.
Have U think about memory leak? Every time onResume, U register the service as listener.
stopService() can not stop Service right now in android. The system will stop it completely in a proper time.

Categories