Intent Service getting killed after sometime - android

I have implemented an intent service in my application, the purpose of which is to monitor the device's shake on a continuous basis.According to the requirement,whenever a shake is detected ,this info should be sent to the app server.
When I started this implementation I had a dilemma on whether to use service or intent service but I chose the latter.Currently,I am able to detect the shake and this info is getting relayed to my app server,but sometimes from 15 min to 2 hour(post starting the app) I notice that this intent service no longer seems to detect any shakes(seems its getting killed on its own).
Here is my code:
public class TheftAlertService1 extends IntentService {
/* The connection to the hardware */
private SensorManager mySensorManager;
/* Here we store the current values of acceleration, one for each axis */
private float xAccel;
private float yAccel;
private float zAccel;
/* And here the previous ones */
private float xPreviousAccel;
private float yPreviousAccel;
private float zPreviousAccel;
private static int SyncRunningFlag = 0;
private double latitude; // latitude
private double longitude; // longitude
/* Used to suppress the first shaking */
private boolean firstUpdate = true;
/* What acceleration difference would we assume as a rapid movement? */
private final float shakeThreshold = .75f;
/* Has a shaking motion been started (one direction) */
private boolean shakeInitiated = false;
public TheftAlertService1() {
super("TheftAlertService1");
Log.d("TheftAlertService1", "inside constr");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent arg0) {
mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); // (1)
mySensorManager.registerListener(mySensorEventListener,
mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL); // (2)
Log.d("TheftAlertService1", "Inside shake onHandleEvent");
}
/* The SensorEventListener lets us wire up to the real hardware events */
private final SensorEventListener mySensorEventListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
updateAccelParameters(se.values[0], se.values[1], se.values[2]); // (1)
if ((!shakeInitiated) && isAccelerationChanged()) { // (2)
shakeInitiated = true;
} else if ((shakeInitiated) && isAccelerationChanged()) { // (3)
executeShakeAction();
} else if ((shakeInitiated) && (!isAccelerationChanged())) { // (4)
shakeInitiated = false;
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
};
/* Store the acceleration values given by the sensor */
private void updateAccelParameters(float xNewAccel, float yNewAccel,
float zNewAccel) {
/*
* we have to suppress the first change of acceleration, it results from
* first values being initialized with 0
*/
if (firstUpdate) {
xPreviousAccel = xNewAccel;
yPreviousAccel = yNewAccel;
zPreviousAccel = zNewAccel;
firstUpdate = false;
} else {
xPreviousAccel = xAccel;
yPreviousAccel = yAccel;
zPreviousAccel = zAccel;
}
xAccel = xNewAccel;
yAccel = yNewAccel;
zAccel = zNewAccel;
}
/*
* If the values of acceleration have changed on at least two axises, we are
* probably in a shake motion
*/
private boolean isAccelerationChanged() {
float deltaX = Math.abs(xPreviousAccel - xAccel);
float deltaY = Math.abs(yPreviousAccel - yAccel);
float deltaZ = Math.abs(zPreviousAccel - zAccel);
return (deltaX > shakeThreshold && deltaY > shakeThreshold)
|| (deltaX > shakeThreshold && deltaZ > shakeThreshold)
|| (deltaY > shakeThreshold && deltaZ > shakeThreshold);
}
private void executeShakeAction() {
Log.d("TheftAlertService1", "inside executeShakeAction");
if (SyncRunningFlag == 0)
new SendTheftAlertToBackend().execute();
}
/******************************************************************************************************/
class SendTheftAlertToBackend extends AsyncTask<String, String, String> implements LocationListener{
JSONParser jsonParser = new JSONParser();
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId();
#Override
protected void onPreExecute() {
super.onPreExecute();
SyncRunningFlag = 1;
LocationManager locationManager;
Location location; // location
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("TheftAlertService1", "Latitude - " +latitude + "longitude - "+longitude);
}
}
Log.d("TheftAlertService1", "Sending Theft Alert to app server");
}
protected String doInBackground(String... args) {
String theft_alert_time = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance()
.getTime());
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("device_id", device_id));
params.add(new BasicNameValuePair("theft_alert_time",theft_alert_time));
params.add(new BasicNameValuePair("theft_alert_longitude","lon -" + longitude));
params.add(new BasicNameValuePair("theft_alert_latitude","lat -" + latitude));
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(
AppConstants.url_theft_alert, "POST", params);
try {
Log.d("TheftAlertService1,Response from server : ",
json.toString());
} catch (Exception e1) {
e1.printStackTrace();
SyncRunningFlag = 0;
}
// check for success tag
try {
int success = json.getInt(AppConstants.TAG_SUCCESS);
String tagDeviceId = json.getString(AppConstants.TAG_DEVICE_ID);
if (success == 1 && tagDeviceId.equals(device_id)) {
Log.d("TheftAlertService1",
"Theft Alert successfully logged in server");
SyncRunningFlag = 0;
} else {
Log.d("TheftAlertService1",
"Failed to log Theft Alert in server");
SyncRunningFlag = 0;
}
} catch (Exception e) {
e.printStackTrace();
SyncRunningFlag = 0;
}
return null;
}
protected void onPostExecute(String file_url) {
Log.d("TheftAlertService1", "inside onPost of async task");
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
This is what I have tried till now :
1) I have overridden onStartCommand and gave its return as START REDELIVER INTENT
2) I tried to make the intent service in foreground.
But nethier of these two options have 'sustained' the continuous background monitoring of shake on my device.
Following code I tried but in vain:
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
final int myID = 1234;
//The intent to launch when the user clicks the expanded notification
Intent intentService = new Intent(this, Staff.class);
intentService.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intentService, 0);
//This constructor is deprecated. Use Notification.Builder instead
Notification notice = new Notification(R.drawable.ic_launcher, "Ticker text", System.currentTimeMillis());
//This method is deprecated. Use Notification.Builder instead.
notice.setLatestEventInfo(this, "Title text", "Content text", pendIntent);
notice.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notice);
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("TheftAlertService1","Service got killed");
}
What is it that I am doing wrong? What should I do to make my intent service to run continuously in the background(and sense shakes forever).
Any help is appreciated.Thanks !

As Pankaj Kumar suggested I created my shake detection inside a service instead of an IntentService (as I was trying before,which used to fail to detect the shakes after sometime).I tested my service for 48 hours straight on devices(like nexus4,galaxy grand) and was able to detect shakes for the above tested period whenever the device was shaked.
To make the service live indefinitely I made the service foreground and returned START_STICKY as shown below.Following is the full code:
public class ShakeService extends Service {
/* The connection to the hardware */
private SensorManager mySensorManager;
/* Here we store the current values of acceleration, one for each axis */
private float xAccel;
private float yAccel;
private float zAccel;
/* And here the previous ones */
private float xPreviousAccel;
private float yPreviousAccel;
private float zPreviousAccel;
/* Used to suppress the first shaking */
private boolean firstUpdate = true;
/* What acceleration difference would we assume as a rapid movement? */
private final float shakeThreshold = .75f;
/* Has a shaking motion been started (one direction) */
private boolean shakeInitiated = false;
private BackgroundThread backGroundThread = null;
SensorEventListener mySensorEventListener;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
if (backGroundThread == null) {
backGroundThread = new BackgroundThread();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (backGroundThread == null)
backGroundThread = new BackgroundThread();
if ((backGroundThread.getState() == Thread.State.NEW) || (backGroundThread.getState() == Thread.State.TERMINATED)) {
if (backGroundThread.getState() == Thread.State.TERMINATED)
backGroundThread = new BackgroundThread();
backGroundThread.start();
Notification localNotification = new Notification(R.drawable.ic_launcher, "", System.currentTimeMillis());
localNotification.setLatestEventInfo(this,AppConstants.NOTIFICATION_NAME,AppConstants.NOTIFICATION_DESCRIPTION, null);
localNotification.flags = Notification.FLAG_NO_CLEAR;
startForeground(377982, localNotification);
mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mySensorManager.registerListener(mySensorEventListener,mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL);
Log.d("ShakeService", "Inside shake onStartCommand");
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
BackgroundThread.yield();
backGroundThread = null;
}
class BackgroundThread extends Thread {
#Override
public void run() {
/* The SensorEventListener lets us wire up to the real hardware events */
mySensorEventListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
updateAccelParameters(se.values[0], se.values[1], se.values[2]);
if ((!shakeInitiated) && isAccelerationChanged()) {
shakeInitiated = true;
} else if ((shakeInitiated) && isAccelerationChanged()) {
executeShakeAction();
} else if ((shakeInitiated) && (!isAccelerationChanged())) {
shakeInitiated = false;
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
/* Store the acceleration values given by the sensor */
private void updateAccelParameters(float xNewAccel, float yNewAccel,float zNewAccel) {
/*
* we have to suppress the first change of acceleration, it results from
* first values being initialized with 0
*/
if (firstUpdate) {
xPreviousAccel = xNewAccel;
yPreviousAccel = yNewAccel;
zPreviousAccel = zNewAccel;
firstUpdate = false;
} else {
xPreviousAccel = xAccel;
yPreviousAccel = yAccel;
zPreviousAccel = zAccel;
}
xAccel = xNewAccel;
yAccel = yNewAccel;
zAccel = zNewAccel;
}
/*
* If the values of acceleration have changed on at least two axises, we are
* probably in a shake motion
*/
private boolean isAccelerationChanged() {
float deltaX = Math.abs(xPreviousAccel - xAccel);
float deltaY = Math.abs(yPreviousAccel - yAccel);
float deltaZ = Math.abs(zPreviousAccel - zAccel);
return (deltaX > shakeThreshold && deltaY > shakeThreshold) || (deltaX > shakeThreshold && deltaZ > shakeThreshold) || (deltaY > shakeThreshold && deltaZ > shakeThreshold);
}
private void executeShakeAction() {
Log.d("ShakeService", "inside executeShakeAction");
// Or do something like post the shake status to app server
}
};
}
}
}

newIntent(GcmIntentService.this,TheftAlertService1.class); startService(theftAlertIntent);
replace this with
newIntent(getApplicationContext(),TheftAlertService1.class); startService(theftAlertIntent);

Related

make service unkilled even when app clossed

I m working pedometer app and i have one service class which extends service class .
public class StepService extends Service {
private static final String TAG = "name.bagi.levente.pedometer.StepService";
private SharedPreferences mSettings;
private PedometerSettings mPedometerSettings;
private SharedPreferences mState;
private SharedPreferences.Editor mStateEditor;
private Utils mUtils;
private SensorManager mSensorManager;
private Sensor mSensor;
private StepDetector mStepDetector;
// private StepBuzzer mStepBuzzer; // used for debugging
private StepDisplayer mStepDisplayer;
private PaceNotifier mPaceNotifier;
private DistanceNotifier mDistanceNotifier;
private SpeedNotifier mSpeedNotifier;
private CaloriesNotifier mCaloriesNotifier;
private SpeakingTimer mSpeakingTimer;
private PowerManager.WakeLock wakeLock;
private NotificationManager mNM;
private int mSteps;
private int mPace;
private float mDistance;
private float mSpeed;
private float mCalories;
/**
* Class for clients to access. Because we know this service always
* runs in the same process as its clients, we don't need to deal with
* IPC.
*/
public class StepBinder extends Binder {
StepService getService() {
return StepService.this;
}
}
#Override
public void onCreate() {
// Log.i(TAG, "[SERVICE] onCreate");
super.onCreate();
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
// Load settings
mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mPedometerSettings = new PedometerSettings(mSettings);
mState = getSharedPreferences("state", 0);
mUtils = Utils.getInstance();
mUtils.setService(this);
mUtils.initTTS();
acquireWakeLock();
// Start detecting
mStepDetector = new StepDetector();
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
registerDetector();
// Register our receiver for the ACTION_SCREEN_OFF action. This will make our receiver
// code be called whenever the phone enters standby mode.
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(mReceiver, filter);
mStepDisplayer = new StepDisplayer(mPedometerSettings, mUtils);
mStepDisplayer.setSteps(mSteps = mState.getInt("steps", 0));
mStepDisplayer.addListener(mStepListener);
mStepDetector.addStepListener(mStepDisplayer);
mPaceNotifier = new PaceNotifier(mPedometerSettings, mUtils);
mPaceNotifier.setPace(mPace = mState.getInt("pace", 0));
mPaceNotifier.addListener(mPaceListener);
mStepDetector.addStepListener(mPaceNotifier);
mDistanceNotifier = new DistanceNotifier(mDistanceListener, mPedometerSettings, mUtils);
mDistanceNotifier.setDistance(mDistance = mState.getFloat("distance", 0));
mStepDetector.addStepListener(mDistanceNotifier);
mSpeedNotifier = new SpeedNotifier(mSpeedListener, mPedometerSettings, mUtils);
mSpeedNotifier.setSpeed(mSpeed = mState.getFloat("speed", 0));
mPaceNotifier.addListener(mSpeedNotifier);
mCaloriesNotifier = new CaloriesNotifier(mCaloriesListener, mPedometerSettings, mUtils);
mCaloriesNotifier.setCalories(mCalories = mState.getFloat("calories", 0));
mStepDetector.addStepListener(mCaloriesNotifier);
mSpeakingTimer = new SpeakingTimer(mPedometerSettings, mUtils);
mSpeakingTimer.addListener(mStepDisplayer);
mSpeakingTimer.addListener(mPaceNotifier);
mSpeakingTimer.addListener(mDistanceNotifier);
mSpeakingTimer.addListener(mSpeedNotifier);
mSpeakingTimer.addListener(mCaloriesNotifier);
mStepDetector.addStepListener(mSpeakingTimer);
// Used when debugging:
// mStepBuzzer = new StepBuzzer(this);
// mStepDetector.addStepListener(mStepBuzzer);
// Start voice
reloadSettings();
// Tell the user we started.
Toast.makeText(this, getText(R.string.started), Toast.LENGTH_SHORT).show();
}
#Override
public void onStart(Intent intent, int startId) {
// Log.i(TAG, "[SERVICE] onStart");
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
// Log.i(TAG, "[SERVICE] onDestroy");
mUtils.shutdownTTS();
// Unregister our receiver.
unregisterReceiver(mReceiver);
unregisterDetector();
mStateEditor = mState.edit();
mStateEditor.putInt("steps", mSteps);
mStateEditor.putInt("pace", mPace);
mStateEditor.putFloat("distance", mDistance);
mStateEditor.putFloat("speed", mSpeed);
mStateEditor.putFloat("calories", mCalories);
mStateEditor.commit();
mNM.cancel(R.string.app_name);
wakeLock.release();
super.onDestroy();
// Stop detecting
mSensorManager.unregisterListener(mStepDetector);
// Tell the user we stopped.
Toast.makeText(this, getText(R.string.stopped), Toast.LENGTH_SHORT).show();
}
private void registerDetector() {
mSensor = mSensorManager.getDefaultSensor(
Sensor.TYPE_ACCELEROMETER /*|
Sensor.TYPE_MAGNETIC_FIELD |
Sensor.TYPE_ORIENTATION*/);
mSensorManager.registerListener(mStepDetector,
mSensor,
SensorManager.SENSOR_DELAY_FASTEST);
}
private void unregisterDetector() {
mSensorManager.unregisterListener(mStepDetector);
}
#Override
public IBinder onBind(Intent intent) {
// Log.i(TAG, "[SERVICE] onBind");
return mBinder;
}
/**
* Receives messages from activity.
*/
private final IBinder mBinder = new StepBinder();
public interface ICallback {
public void stepsChanged(int value);
public void paceChanged(int value);
public void distanceChanged(float value);
public void speedChanged(float value);
public void caloriesChanged(float value);
}
private ICallback mCallback;
public void registerCallback(ICallback cb) {
mCallback = cb;
//mStepDisplayer.passValue();
//mPaceListener.passValue();
}
private int mDesiredPace;
private float mDesiredSpeed;
/**
* Called by activity to pass the desired pace value,
* whenever it is modified by the user.
* #param desiredPace
*/
public void setDesiredPace(int desiredPace) {
mDesiredPace = desiredPace;
if (mPaceNotifier != null) {
mPaceNotifier.setDesiredPace(mDesiredPace);
}
}
/**
* Called by activity to pass the desired speed value,
* whenever it is modified by the user.
* #param desiredSpeed
*/
public void setDesiredSpeed(float desiredSpeed) {
mDesiredSpeed = desiredSpeed;
if (mSpeedNotifier != null) {
mSpeedNotifier.setDesiredSpeed(mDesiredSpeed);
}
}
public void reloadSettings() {
mSettings = PreferenceManager.getDefaultSharedPreferences(this);
if (mStepDetector != null) {
mStepDetector.setSensitivity(
Float.valueOf(mSettings.getString("sensitivity", "10"))
);
}
if (mStepDisplayer != null) mStepDisplayer.reloadSettings();
if (mPaceNotifier != null) mPaceNotifier.reloadSettings();
if (mDistanceNotifier != null) mDistanceNotifier.reloadSettings();
if (mSpeedNotifier != null) mSpeedNotifier.reloadSettings();
if (mCaloriesNotifier != null) mCaloriesNotifier.reloadSettings();
if (mSpeakingTimer != null) mSpeakingTimer.reloadSettings();
}
public void resetValues() {
mStepDisplayer.setSteps(0);
mPaceNotifier.setPace(0);
mDistanceNotifier.setDistance(0);
mSpeedNotifier.setSpeed(0);
mCaloriesNotifier.setCalories(0);
}
/**
* Forwards pace values from PaceNotifier to the activity.
*/
private StepDisplayer.Listener mStepListener = new StepDisplayer.Listener() {
public void stepsChanged(int value) {
mSteps = value;
passValue();
}
public void passValue() {
if (mCallback != null) {
mCallback.stepsChanged(mSteps);
}
}
};
/**
* Forwards pace values from PaceNotifier to the activity.
*/
private PaceNotifier.Listener mPaceListener = new PaceNotifier.Listener() {
public void paceChanged(int value) {
mPace = value;
passValue();
}
public void passValue() {
if (mCallback != null) {
mCallback.paceChanged(mPace);
}
}
};
/**
* Forwards distance values from DistanceNotifier to the activity.
*/
private DistanceNotifier.Listener mDistanceListener = new DistanceNotifier.Listener() {
public void valueChanged(float value) {
mDistance = value;
passValue();
}
public void passValue() {
if (mCallback != null) {
mCallback.distanceChanged(mDistance);
}
}
};
/**
* Forwards speed values from SpeedNotifier to the activity.
*/
private SpeedNotifier.Listener mSpeedListener = new SpeedNotifier.Listener() {
public void valueChanged(float value) {
mSpeed = value;
passValue();
}
public void passValue() {
if (mCallback != null) {
mCallback.speedChanged(mSpeed);
}
}
};
/**
* Forwards calories values from CaloriesNotifier to the activity.
*/
private CaloriesNotifier.Listener mCaloriesListener = new CaloriesNotifier.Listener() {
public void valueChanged(float value) {
mCalories = value;
passValue();
}
public void passValue() {
if (mCallback != null) {
mCallback.caloriesChanged(mCalories);
}
}
};
/**
* Show a notification while this service is running.
*/
private void showNotification() {
CharSequence text = getText(R.string.app_name);
Notification notification = new Notification(R.drawable.ic_notification, null,
System.currentTimeMillis());
notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
Intent pedometerIntent = new Intent();
pedometerIntent.setComponent(new ComponentName(this, Pedometer.class));
pedometerIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
pedometerIntent, 0);
/* notification.setLatestEventInfo(this, text,
getText(R.string.notification_subtitle), contentIntent);
mNM.notify(R.string.app_name, notification);*/
}
// BroadcastReceiver for handling ACTION_SCREEN_OFF.
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Check action just to be on the safe side.
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// Unregisters the listener and registers it again.
StepService.this.unregisterDetector();
StepService.this.registerDetector();
if (mPedometerSettings.wakeAggressively()) {
wakeLock.release();
acquireWakeLock();
}
}
}
};
private void acquireWakeLock() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
int wakeFlags;
if (mPedometerSettings.wakeAggressively()) {
wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
}
else if (mPedometerSettings.keepScreenOn()) {
wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK;
}
else {
wakeFlags = PowerManager.PARTIAL_WAKE_LOCK;
}
wakeLock = pm.newWakeLock(wakeFlags, TAG);
wakeLock.acquire();
}
}
ho to make this service live even when app killed also I have to count footstep even when app killed.
I m calling service like this.
startService(new Intent(Pedometer.this,
StepService.class));
#Override
public void onTaskRemoved(Intent rootIntent)
{
super.onTaskRemoved(rootIntent);
startStepService();
}
private void startStepService()
{
startService(new Intent(this,StepService.class));
}

Android - Launching an app with a shake

I'm a newbie to this field of android development. I'm developing an app which I need to be launched by shaking the device. How can I get this thing done? I read many threads and tried out several codes. but non of them worked. Please be kind enough to come up with the full code (from top to bottom) of particular file(or files). So that I'll be able to understand where exactly that I need to change in my code. Thank you!
Try this, First create your Service
public class ShakeService extends Service implements SensorEventListener {
private SensorManager sensorMgr;
private Sensor acc;
private long lastUpdate = -1;
private float x, y, z;
private float last_x, last_y, last_z;
private static final int SHAKE_THRESHOLD = 1100;
#Override
public void onCreate() {
Toast.makeText(this,
"Service Started", Toast.LENGTH_SHORT).show();
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
acc=sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
boolean accelSupported= sensorMgr.registerListener((SensorEventListener) this, acc, SensorManager.SENSOR_DELAY_GAME);
long curTime11 = System.currentTimeMillis();
if (!accelSupported) {
// on accelerometer on this device
sensorMgr.unregisterListener((SensorEventListener) this,acc);
}
super.onCreate();
}
protected void onPause() {
if (sensorMgr != null) {
sensorMgr.unregisterListener((SensorEventListener) this,acc);
sensorMgr = null;
}
return;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
if (sensorMgr != null) {
sensorMgr.unregisterListener((SensorEventListener) this,acc);
sensorMgr = null;
}
stopSelf();
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
// only allow one update every 100ms.
if ((curTime - lastUpdate) > 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
x = sensorEvent.values[SensorManager.DATA_X];
y = sensorEvent.values[SensorManager.DATA_Y];
z = sensorEvent.values[SensorManager.DATA_Z];
float speed = Math.abs(x+y+z - last_x - last_y - last_z) / diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
Log.d("sensor", "shake detected w/ speed: " + speed);
Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show();
Intent myIntent= new Intent(this, MyActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
/ startActivity(myIntent);
////Here start your activity and your application will be started
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}
And make sure to declare your service in manifest
<service
android:name=".ShakeService"
android:enabled="true"
android:exported="true"></service>
Now in your activity start service as
startService(new Intent(MainActivity.this,ShakeService.class));

Updating activity UI from bounded service

I am trying to make an app that calculates taxi/auto fare. The app will run as a background service and will keep updating the ride data like location,fare,distance etc in the background even after the user exits the app. The service will stop when user presses a stop button. Now here my problem is, each time the activty is resumed/restarted its resetting to initial state-as if the service stopped. How do I continuously update the UI so that the activity keeps updated so that whenever user comes to the page updated data is shown. I am runnng a STICKY service.
This is my service
public class LocationManager extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = LocationManager.class.getSimpleName();
double last_lat = -1000.0f;
double last_lon = -1000.0f;
double dist_total = 0.0f;
double fare_total = 0.0f;
long start_time = -1;
private GoogleApiClient mGoogleApiClient;
private Context mContext;
private LocationRequest mLocationRequest;
private boolean mToStartUpdates = false;
private boolean isInited = false;
private long mLastLocationMillis = 0;
private SharedPreferences settings;
String rideTime = "00h:00m:00s";
private IBinder mBinder = new TukTukMeterBinder();
private Timer timer = new Timer();
public LocationManager(){}
public void init(boolean startUpdates) {
mToStartUpdates = startUpdates;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
public class TukTukMeterBinder extends Binder{
LocationManager getBinder(){
return LocationManager.this;
}
}
public double getDistanceTraveled(){
return dist_total;
}
public double getFare_total(){
return fare_total;
}
public double getLast_lat(){
return last_lat;
}
public double getLast_lon(){
return last_lon;
}
public String getRideTime(){
return rideTime;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
mContext = this;
init(true);
}
#Override
public void onConnected(Bundle bundle) {
LogUtil.i("GoogleApiClient connection has Connected");
isInited = true;
if (mToStartUpdates && RequirementHelper.isLocationEnabled(mContext)) {
createLocationRequest();
} else {
createLocationRequestDialog();
}
}
#Override
public void onConnectionSuspended(int i) {
LogUtil.i("Could not connect to googleApiClient" + i);
if (mGoogleApiClient != null) {
mGoogleApiClient.reconnect();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(AppConstants.ACTION.STARTFOREGROUND_ACTION)) {
LogUtil.i("Received Start Foreground Intent ");
buildNotification();
start_time = System.currentTimeMillis();
mHandler.postDelayed(mUpdateTimeTask,1000);
} else if (intent.getAction().equals(AppConstants.ACTION.STOPFOREGROUND_ACTION)) {
stopForeground(true);
stopSelf();
mHandler.removeCallbacks(mUpdateTimeTask);
}
return START_STICKY;
}
private void buildNotification() {
Intent notificationIntent = new Intent(this, TukTukHomeActivity.class);
notificationIntent.setAction(AppConstants.ACTION.MAIN_ACTION);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("TukTuk Meter")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(
Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
startForeground(AppConstants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
isInited = false;
}
/**
* This method will automatically creates a dialog for automatically turning on GPS without navigating to settings activity.
*/
public void createLocationRequestDialog() {
mLocationRequest = LocationRequest.create();
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
LogUtil.d("onResult state:[" + state + "]");
LogUtil.d("onResult status:[" + status + "]");
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS://Already have a location.
if (RequirementHelper.isLocationEnabled(mContext)) {
createLocationRequest();
break;
} else {
}//$fallthrough without break
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
LogUtil.d("showing request loccation dialog");
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(((Activity) mContext), TukTukHomeActivity.REQUEST_ENABLE_GPS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the diaLogUtil.
break;
}
}
});
}
/**
* The dialog to be shown to turn on location is currently disabled.
*/
public void createLocationRequest() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(10 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
requestLocationUpdates();
}
public void requestLocationUpdates() {
if (mGoogleApiClient.isConnected() && RequirementHelper.hasAnyLocationPermission(mContext)) {
LogUtil.d("requestLocationUpdates");
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, LocationManager.this);
}
}
#Override
public void onLocationChanged(Location location) {
LogUtil.d("Fetched AdsLocation" + location);
if (location != null) {
// DataStorePrefManager.getInstance(mContext).saveLastKnownLocation(location);
mLastLocationMillis = SystemClock.elapsedRealtime();
settings = PreferenceManager.getDefaultSharedPreferences(mContext);
double min_fare = settings.getFloat(DataStorePrefManager.KEY_BASE_FARE, 0.0f);
double min_dist = settings.getFloat(DataStorePrefManager.KEY_MIN_DISTANCE, 0.00f);
double rate_per_km = settings.getFloat(DataStorePrefManager.KEY_KM_FARE, 0.00f);
Log.i(TAG, location.getLatitude() + " , " + location.getLongitude());
if (last_lat < -90 || last_lon < -180) {
last_lat = location.getLatitude();
last_lon = location.getLongitude();
} else {
double lat1 = Math.toRadians(last_lat);
double lon1 = Math.toRadians(last_lon);
double lat2 = Math.toRadians(location.getLatitude());
double lon2 = Math.toRadians(location.getLongitude());
double R = 6371.0f;
double dLat = (lat2 - lat1);
double dLon = (lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = R * c;
if (d > 0.05 && location.getAccuracy() < 50) // Add only if delta > 50 m and uncertainty < 50m
{
dist_total += d;
if (dist_total > min_dist) {
fare_total = min_fare + (dist_total - min_dist) * rate_per_km;
} else {
fare_total = min_fare;
}
Log.i("Distance", Double.toString(dist_total));
last_lat = location.getLatitude();
last_lon = location.getLongitude();
}
}
DecimalFormat df = new DecimalFormat("#.0");
df.format(fare_total);
df.format(dist_total);
} else return;
}
public void onDestroy() {
isInited = false;
mHandler.removeCallbacks(mUpdateTimeTask);
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
public boolean isInited() {
return isInited;
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
private Runnable mUpdateTimeTask = new TimerTask() {
#Override
public void run() {
int hrs = 0,min = 0,sec= 0;
if(start_time != -1)
{
int interval = (int) (System.currentTimeMillis() - start_time)/1000;
sec = interval%60;
min = interval/60;
hrs = interval/3600;
rideTime = String.format("%02dh:%02dm:%02ds", hrs,min,sec);
}
if(isInited){
mHandler.postDelayed(this,1000);
}
}};
}
And this is my Activity
public class TukTukHomeActivity extends AppCompatActivity implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener {
LocationManager mLocationManager;
public static final int REQUEST_ENABLE_GPS = 100;
boolean bound = false;
TextView rideDistance, totalFare, rideTotalTime, mapsTv;
private DrawerLayout mDrawerLayout;
double distance = 0;
double fareTotal = 0;
String rideTime = "00h:00m:00s";
boolean isRunning = false;
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocationManager.TukTukMeterBinder mBinder = (LocationManager.TukTukMeterBinder) service;
mLocationManager = mBinder.getBinder();
bound = true;
initUI();
displayDistance();
}
#Override
public void onServiceDisconnected(ComponentName name) {
bound = false;
mLocationManager = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
initUI();
findViewById(R.id.startRide).setOnClickListener(this);
toolbar.setNavigationIcon(R.drawable.menu);
toolbar.setNavigationOnClickListener(this);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(this);
}
private void initUI(){
rideDistance = (TextView)findViewById(R.id.rideDistance) ;
totalFare = (TextView)findViewById(R.id.fareTotal);
rideTotalTime = (TextView)findViewById(R.id.rideTime) ;
mapsTv = (TextView)findViewById(R.id.openMaps);
mapsTv.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.startRide:
startMeterService();
break;
case R.id.drawerLayout:
mDrawerLayout.openDrawer(GravityCompat.START);
break;
case R.id.openMaps:
startActivity(new Intent(this,TukTukMaps.class));
break;
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.items, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
startActivity(new Intent(TukTukHomeActivity.this, TukTukSettings.class));
return true;
}
if(id == R.id.navigation){
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void startMeterService() {
Intent startIntent = new Intent(this, LocationManager.class);
startIntent.setAction(AppConstants.ACTION.STARTFOREGROUND_ACTION);
startService(startIntent);
bindService(startIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
displayDistance();
}
#Override
protected void onResume() {
super.onResume();
initUI();
displayDistance();
}
private void displayDistance() {
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
if (mLocationManager != null) {
distance = mLocationManager.getDistanceTraveled();
fareTotal = mLocationManager.getFare_total();
rideTime = mLocationManager.getRideTime();
}
rideDistance.setText(String.valueOf(distance)+"km");
totalFare.setText(getResources().getString(R.string.min_fare_symbol)+String.valueOf(fareTotal));
rideTotalTime.setText(String.valueOf(rideTime));
handler.postDelayed(this, 1000);
}
});
}
#Override
protected void onStop() {
super.onStop();
if (bound) {
unbindService(mServiceConnection);
bound = false;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_GPS:
switch (resultCode) {
case Activity.RESULT_OK:
startMeterService();
break;
case Activity.RESULT_CANCELED:
break;
}
break;
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.about_us:
startActivity(new Intent(TukTukHomeActivity.this,AboutUs.class));
mDrawerLayout.closeDrawers();
return true;
}
return true;
}
}
To send data from service to activity
Intent i = new Intent();
i.setAction(SOME_ACTION_NAME);
i.setExtra(KEY,VALUE);
context.sendBroadcast(i);
Use a broadcase reciever inside the activity
BroadcastReceiver mBroadcastReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(SOME_ACTION_NAME) {
//read your extra from intent
}
}
}
add your action name to an intent filter and register the broadcast reciever.
Try to use the preference settings and save your values in service class.
Add logs to see whether you're receiving location updates and your values are getting printed or not.
handler.postDelayed(this, 1000); may not be required if your service is updating the values.

How to capture orientation values after a certain time an activity has started

I am trying to read the orientation and accelerometer readings 5 seconds after the Activity has started. I am tracking the sensor readings as they are changing but 5 seconds into the activity, I want to capture certain special readings in a certain position. I want all other processes to work as normal in the meantime. Here is my activity code, Am I doing this right?
public class WorkoutBuddy extends Activity implements SensorEventListener {
TextView t1, t2, t3;
Compass myCompass;
SensorManager sensorManager;;
private Sensor sensorAccelerometer;
private Sensor sensorMagneticField;
private float[] valuesAccelerometer;
private float[] valuesMagneticField;
private float[] startingPositionAccelerometer;
private float[] startingPositionMagneticField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercise_buddy);
t1 = (TextView)findViewById(R.id.textView1);
t2 = (TextView)findViewById(R.id.textView2);
t3 = (TextView)findViewById(R.id.textView3);
myCompass = (Compass) findViewById(R.id.mycompass);
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
sensorAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorMagneticField = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
valuesAccelerometer = new float[3];
valuesMagneticField = new float[3];
matrixR = new float[9];
matrixI = new float[9];
matrixValues = new float[3];
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
sensorManager.unregisterListener(this,sensorAccelerometer);
sensorManager.unregisterListener(this,sensorMagneticField);
super.onPause();
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
float azimuth,pitch,roll;
private float[] matrixR;
private float[] matrixI;
private float[] matrixValues;
boolean startingPosition = false;
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
valuesAccelerometer = lowPass(event.values.clone(), valuesAccelerometer);
} else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
valuesMagneticField = lowPass(event.values.clone(), valuesMagneticField);
}
if (valuesAccelerometer != null && valuesMagneticField != null) {
SensorManager.getRotationMatrix(matrixR, matrixI, valuesAccelerometer, valuesMagneticField);
if(true){
SensorManager.getOrientation(matrixR, matrixValues);
double azimuth = Math.toDegrees(matrixValues[0]);
double pitch = Math.toDegrees(matrixValues[1]);
double roll = Math.toDegrees(matrixValues[2]);
t1.setText("Azimuth: " + String.format("%.4f", azimuth));
t2.setText("Pitch: " + String.format("%.4f", pitch));
t3.setText("Roll: " + String.format("%.4f", roll));
myCompass.update(matrixValues[0]);
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
if(startingPosition == false){
startingPositionAccelerometer= valuesAccelerometer;
startingPositionMagneticField= valuesMagneticField;
startingPosition = true;
}
}
},
5000
);
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
sensorManager.registerListener(this,sensorAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this,sensorMagneticField,SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
}
//Low pass filter used to smooth the sensor readings
protected float[] lowPass( float[] input, float[] output ) {
float ALPHA = 0.25f;
if ( output == null ) return input;
for ( int i=0; i<input.length; i++ ) {
output[i] = output[i] + ALPHA * (input[i] - output[i]);
}
return output;
}
}
You can use a Handler to perform a delayed action.
public void onResume() {
super.onResume();
new Handler().postDelayed(new Runnable() {
public void run() {
//Record readings here.
}
}, 5000);
I would prefer to use ScheduledExecutorService like below...
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); // 2 - number of thread in pool
// run every 5 seconds
executorService.scheduleAtFixedRate(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
// do your UI stuff here..
}
});
}
}, 0, 5, TimeUnit.SECONDS);

SensorEventListener in combination with Timer-Thread

I want to write an Android program which lets the user set up a countdown timer. After the user pushes the "Start-Button" the countdown is running. While the countdown is running, the phone should recognize the acceleration of the device.
If time is up, or the device was shaken to much a new activity should be loaded..
At my device (S4) the code is running quite well, only the countdown timer doesn't get closed after the device has been shaken to much, so the run-method will be activated suddenly. On other device (S2) the new activity is started directly after pushing the button. How could this be?
I think I made a mistake with the run-method and I am not sure if I understand the idea about setting threads correctly.
Here is my code:
public class WaitingForBomb extends Activity {
float sensibility = 2.5f;
boolean isOver = false;
private SensorManager mSensorManager;
private float mAccel; // Beschleunigung
private float mAccelCurrent; // aktuelle Beschleunigung (in Verbindung mit
// Erdanziehung)?
private float mAccelLast; // letzte Beschleunigung (in Verbindung mit
// Erdanziehung)?
TextView anzeige;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.waiting);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
// Sleep-Timer
Thread bombTimer = new Thread() {
public void run() {
while (isOver = false) {
try {
// Intent-Übergabe des Counters
Intent mIntent = getIntent();
int counterValue = mIntent
.getIntExtra("pushCounter", 0);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(counterValue);
sleep(counterValue);
isOver = true;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
isOver = true;
}
}
}
};
bombTimer.start();
}
// Verhindert, dass die "Back-Taste" erkannt wird und somit das Spiel
// vorzeitig beendet wird.
#Override
public void onBackPressed() {
}
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
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
boolean checkSense1 = getPrefs.getBoolean("sensi1", true);
boolean checkSense2 = getPrefs.getBoolean("sensi2", false);
if (checkSense1 == true) {
sensibility = 1.25f;
}
if (checkSense2 == true) {
sensibility = 0.75f;
}
// Prüft die Beschleunigung
if (mAccel > sensibility) {
Intent gameOver = new Intent("android.intent.action.BOOM");
startActivity(gameOver);
}
if (isOver == true) {
Intent gameOver = new Intent("android.intent.action.BOOM");
startActivity(gameOver);
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
mSensorManager.unregisterListener(mSensorListener);
super.onPause();
finish();
}
}
Just update your while condition
while (!isOver) {
}

Categories

Resources