Accessing multiple sensors in non-activity classes - java

I am trying to use multiple sensors like Accelerator,Magnetic Field, Light and so on and for each sensor I wrote an individual class which not an activity , each of them has its SensorEventListener as well. What I want to do is when user chooses one of them I start to show the data on a fragment(on MainActivity) , when user changes the previous sensor should stop and new one should start. However, when I try to stop previous one by unregistering its listener , it doesn't unregister but it registers and works. I want to stop previous listener. What is wrong? Any ideas?
Here is the sensor class;
public class Accelerometer
{
private SensorManager sensorManager;
private Sensor sensor;
public List<ObjAccelerometer> lstData;
ObjAccelerometer currentData;
float lastX,lastY,lastZ;
String currentTime;
int numberOfSamples;
Context context;
public Accelerometer(Context _context,int _numberSample)
{
context=_context;
sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
numberOfSamples=_numberSample;
lstData=new ArrayList<>();
}
public void registerUnregister(boolean register)
{
if(register)
sensorManager.registerListener(mSensorListener, sensor, SensorManager.SENSOR_DELAY_FASTEST);
else
sensorManager.unregisterListener(mSensorListener);
}
Calendar time;
private final SensorEventListener mSensorListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent event) {
if(numberOfSamples>lstData.size()) {
if (currentData != null) {
lastX = currentData.get_x();
lastY = currentData.get_y();
lastZ = currentData.get_z();
}
currentData = new ObjAccelerometer();
time = Calendar.getInstance();
currentTime = time.get(Calendar.HOUR) + ":" + time.get(Calendar.MINUTE) + ":" + time.get(Calendar.SECOND) + ":" + time.get(Calendar.MILLISECOND);
currentData.set_time(currentTime);
currentData.set_x(event.values[0]);
currentData.set_y(event.values[1]);
currentData.set_z(event.values[2]);
Float speed = Math.abs(event.values[0] + event.values[1] + event.values[2] - lastX - lastY - lastZ);
currentData.set_speed(speed);
lstData.add(currentData);
Util.createToaster(context, "X Y Z Time:" + currentData.toString());
}
else
registerUnregister(false);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
Here the code for calling them ;
unRegisterAllSensors();
switch (selectedSensor) {
case Accelerometer:
accelerometer= new Accelerometer(context, DEFAULT_SAMPLE_NUMBER);
accelerometer.registerUnregister(true);
lstAccelerometer = accelerometer.lstData;
break;
case Linear_Accelerometer:
linearAccelerometer= new LinearAccelerometer(context, DEFAULT_SAMPLE_NUMBER);
linearAccelerometer.registerUnregister(true);
break;
....
Here is the unRegisterAllSensors() function code:
if(accelerometer!=null) {
accelerometer.registerUnregister(false);
accelerometer=null;
}
if(linearAccelerometer!=null) {
linearAccelerometer.registerUnregister(false);
linearAccelerometer=null;
}

Sorry about bothering people,it actually works!
I made a few changes including setting SensorManager final parameter and also removing Toast message and add A toaster only for register and unregister of each listener. It worked! I believe the problem was caused by two things;
1-Toasting the message is slower process than sensing because of that even though I unregistered messages were still on the screen for a while.
2- when I didn't define SensorManager final , every time I was getting a new instance of it so size of the listener list was 0.
Still, this can be a good sample for people who want to call sensors from non-activity classes.
Thanks!

Related

Android Studio: TimerTask

I am creating a simple click game that spawns enemies on screen and when the user clicks them, they get points and the enemies are destroyed. I do this with making imageboxs visible and invisible when the user clicks on them. They run on a timer and have a constant loop of spawning.
Currently I want to implement a way the user will start to loose health. So I would like to check if the enemy imagebox is visible, if it is, the player will slowly loose health.
I am confused with creating a timer task that can refresh the UI for this job. I want to be able to check the UI constantly if some images are visible or not. I have made a start on this from my own research but the game crashes when loaded if this is implemented.
Timer to refresh UI:
private Timer mTimer1;
private TimerTask mTt1;
private Handler mTimerHandler = new Handler();
public void onStart() {
mTimer1 = new Timer();
mTt1 = new TimerTask() {
public void run() {
mTimerHandler.post(new Runnable() {
public void run() {
//TODO
final TextView health = (TextView) findViewById(R.id.Health);
health.setText("Health: " + health2);
//Enemy ImageViews
final ImageView enemy1 = (ImageView) findViewById(R.id.enemy1);
final ImageView enemy2 = (ImageView) findViewById(R.id.enemy2);
final ImageView enemy3 = (ImageView) findViewById(R.id.enemy3);
final ImageView enemy4 = (ImageView) findViewById(R.id.enemy4);
//sets imageViews into array
final ImageView[] enemies = new ImageView[4];
enemies[0] = enemy1;
enemies[1] = enemy2;
enemies[2] = enemy3;
enemies[3] = enemy4;
boolean running = true;
while (running) {
if (enemy1.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy2.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy3.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy4.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
}
}
});
}
};
mTimer1.schedule(mTt1, 1, 5000);
}
}
This is the timer task I have created. I would like some clarity to why this crashes my game and how to fix this issue. I have never used timer in this way before so if the problem is obvious that is why I have not noticed it.
I have a lot more code inside the onCreate method and can post if needed. Thank you for all the help and advice for this begineer.
Crash:
Based on the error message you need to call super.onStart()
so you need to add that here:
public void onStart() {
super.onStart();
//your code
}
I assume you know, but just in case super is class you extend, the parent. if you override it's onStart function the normal onStart procedure isn't done, if you don't call the super function.
EDIT: as for your other question, i (as a beginner with java, so i'm not claiming this is the best way to go) would be thinking along the lines of doing something like:
First create a handler and make runnables for the enemies:
Handler handler = new Handler();
Runnable[] eRunnables = new Runnable[enemies.length-1];
for(int i = 0; i < eRunnables.length; i++){
eRunnables[i] = new Runnable(){
public void run(){
if(enemies[i].getVisibility() == View.VISIBLE){
health2--;
health.setText("Health:" + health2);
handler.postDelayed(eRunnables[i], 1000);
}
}
};
}
And then where you initially make the enemies visible (besides setting them to visible) do something like
handler.postDelayed(eRunnable[enemyNr], 1000);
ofcourse replace the 1000 with however many milliseconds you want.
Again i'm not saying this is the best way, just what i thought up.

Call sensor activity object from another class

I am working on a project in which the content on the screen changes with the direction of mobile's axis. For this, I created a class which calculates azimuthal angle by accessing sensor data. This class also has a method setLine which gives back a,b,c in line equation a.x + b.y + c = 0 when supplied gps co-ordinates. This line is the z-axis of mobile.
So I created an object of this class from another class. But whenever I am accessing setLine, By seeing the log I got to know that azimuthal = NULL and oldAzimuthal = Math.PI/180 which is what I set.
I don't understand this. When I created the ViewAngleActivity object, this should have already initialized sensors and I shouldn't be getting NULL for azimuthal .
Earlier when I used ThisViewAngleActivity as the main class I didn't face such issue. I was properly getting azimthal.
Am I missing some concepts? Please help.
I am uploading the code for ViewAngleActivity
public class ViewAngleActivity extends Activity implements SensorEventListener {
Float azimuth;
Float pitch;
Float roll;
float oldAzimuth;
private SensorManager mSensorManager;
Sensor accelerometer;
Sensor magnetometer;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
Log.d("gettingViewAngle:","in onCreateSensor got Created");
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
float[] mGravity;
float[] mGeomagnetic;
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
if (SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic)) {
// orientation contains azimut, pitch and roll
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
oldAzimuth = azimuth;
azimuth = orientation[0];
pitch = orientation[1];
roll = orientation[2];
// at this point, orientation contains the azimuth(direction), pitch and roll values.
Log.d("onSensorChanged:", "azimuth = "+ azimuth);
Log.d("onSensorChanged:", "oldAzimuth = "+ oldAzimuth);
}
}
}
/**
* This method calculates line equation of mobile axis
* #param currentLatitude
* #param currentLongitude
* #return co-efficients of the line a.x + b.y + c = 0
*/
public double[] setLine(Double currentLatitude, Double currentLongitude){
double angle = 1;
double a,b,c;
double[] coEfficients = {1, 1, 0};
Log.d("setLine:", "azimuth = "+ azimuth);
Log.d("setLine:", "oldAzimuth = "+ oldAzimuth);
if(azimuth!= null) {
angle = (float) azimuth;
if (angle == 0){
angle = Math.PI/180;
}
if ( angle%((Math.PI)/2) ==0){
a = 0;
b = 1;
c = ( - currentLongitude);
}
else {
a = -(Math.tan((double) angle));
b = 1;
c = (Math.tan((double) angle) * currentLatitude) - currentLongitude;
}
Log.d("setLine:Using azimuth", "azimuth = "+ angle);
coEfficients[0] = a ;
coEfficients[1] = b ;
coEfficients[2] = c ;
}
else{
angle = (float) oldAzimuth;
if (angle == 0){
angle = Math.PI/180;
}
if ( angle%((Math.PI)/2) ==0){
a = 0;
b = 1;
c = ( - currentLongitude);
}
else {
a = -(Math.tan((double) angle));
b = 1;
c = (Math.tan((double) angle) * currentLatitude) - currentLongitude;
}
Log.d("setLine:UsingOldAzimuth", "oldAzimuth = "+ angle);
coEfficients[0] = a ;
coEfficients[1] = b ;
coEfficients[2] = c ;
}
return coEfficients;
}
}
The object I created from other class is as follows
private ViewAngleActivity viewAngleActivity;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewAngleActivity = new ViewAngleActivity();
//other parts of the code//
}
#Override
public void method1{
method2;
}
public void method1{
double[] coEfficients = viewAngleActivity.setLine(currentLatitude,currentLongitude);
}
You're only creating an instance of ViewAngleActivity, it's never really added to the window.
Your onCreate() and onResume() methods never get called, they are only called when your Activity is added to the window and goes through the Activity Lifecycle
Since you're instantiating your mSensorManager instance inside onCreate(), it never gets created and is still null.
Since onResume() isn't called (see second point up there), then your viewAngleActivity instance (which is also your SensorEventListener interface) never gets registered to mSensorManager, and as such the method onSensorChanged(SensorEvent evt) inside your ViewAngleActivity instance never gets called. Since that's where you're setting azimuth it's still going to be NULL cause that method is never called.
You might want to try a different approach, probably move all the code in your ViewAngleActivity's onCreateView() methods to a constructor like so:
//note the context parameter, pass this one when you create your ViewAngleActivity instance
public ViewAngleActivity(Context context){
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
Log.d("gettingViewAngle:","in onCreateSensor got Created");
//then you use your context to reg.
mSensorManager.registerListener(context, accelerometer, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(context, magnetometer, SensorManager.SENSOR_DELAY_UI);
}
Please read more about Android's Activity Lifecycle and how they are added on screen. Note that with the above approach, you'd have to handle unregistering your SensorEventListener, cause obviously onPause() would never be called in ViewAngleActivity.
//this is how you'd probably go about it:
viewAngleActivty.mSensorManager.unregisterListener(viewAngleActivity);
Or instead, implement what you're trying to do in the new Activity you're using as your MainActivity, that would be even easier.

Android - How do I continuously run a thread, one after another

So i have the following code below which basically takes the initial battery level, waits a certain amount of time, and takes the ending battery level inside of calculateHelper which then finds the difference and prints it.
// Get the initial battery level
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
System.out.println("Initial battery level is: " + level);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
final float batteryPctTemp0 = level / (float) scale;
final float batteryPct0 = batteryPctTemp0 * 100;
int waitTime = 60000 * interval; // 1 minute is 60000 miliseconds
System.out.println("Wait time is " + waitTime);
Runnable r = new Runnable() {
#Override
public void run(){
calculateHelper(batteryPct0,startButton);
}
};
Handler h = new Handler();
h.postDelayed(r, waitTime);
I want to infinitely loop (until program exit) this entire process so that after each successive thread finishes, the next one begins, taking a new initial battery level each time and passing it into the calculateHelper function for calculation of a new difference. I do NOT want threads to stack up. I want one thread at a time. In other words, the loop needs to wait for the thread to finish before starting another one.
I can't for the life of me figure out how to do this! If i put the entire thing into a while, it will just repeatedly open up threads crashing the phone.
If anyone can point me in the right direction on the matter I would be greatly appreciative. Also, if any more code is needed to solve the problem, simply comment and I will reply as soon as I have added it to my question.
Thank you.
Thanks to Whooper, I've added in this method of regulating execution order in a loop. However, for some reason my postExecute() method is never being executed and nothing is happening.
private class BatteryLifeTask extends AsyncTask<Void, Void, Void> {
// Member variables
Context appContext;
float batteryPct0;
Button startButton;
public BatteryLifeTask(Context context, Button start) {
super();
appContext = context;
startButton = start;
}
protected Void doInBackground(Void... params) {
// Get the initial battery level
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = appContext.registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
System.out.println("Initial battery level is: " + level);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
final float batteryPctTemp0 = level / (float) scale;
batteryPct0 = batteryPctTemp0 * 100;
return null;
}
protected void onPostExecute() {
int waitTime = 60000 * interval; // 1 minute is 60000 miliseconds
System.out.println("In postExecute. waitTime is" + waitTime);
Runnable r = new Runnable() {
#Override
public void run(){
System.out.println("An interval has passed.");
calculateHelper(batteryPct0,startButton);
new BatteryLifeTask(appContext,startButton).execute();
}
};
Handler h = new Handler();
h.postDelayed(r, waitTime);
}
}
and my call to the execute method:
// Start the task loop
new BatteryLifeTask(getApplicationContext(), startButton).execute();
I've found the problem:
I forgot to set the #Override annotation, and this answer : https://stackoverflow.com/a/11127996/2247192 states:
"If your params of onPostExecute(Param param) don't match the one you defined with extends AsyncTask<...,...,Param> and you didn't use the #Override annotation, it will never be executed and you don't get a warning from Eclipse."
So I've corrected my postExecute method to:
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
int waitTime = 60000 * interval; // 1 minute is 60000 miliseconds
System.out.println("In postExecute. waitTime is " + waitTime);
Runnable r = new Runnable() {
#Override
public void run(){
System.out.println("An interval has passed.");
calculateHelper(batteryPct0,startButton);
new BatteryLifeTask(appContext,startButton).execute();
}
};
Handler h = new Handler();
h.postDelayed(r, waitTime);
}
All issues are now resolved.
Try using an AsyncTask.
http://developer.android.com/reference/android/os/AsyncTask.html
This way you can execute the task again when onPostExecute() is called.
Something like this:
private class BatteryLifeTask extends AsyncTask<Void, Void, Void> {
protected void doInBackground(Void... params) {
// Get the initial battery level
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
System.out.println("Initial battery level is: " + level);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
final float batteryPctTemp0 = level / (float) scale;
final float batteryPct0 = batteryPctTemp0 * 100;
}
protected void onPostExecute() {
int waitTime = 60000 * interval; // 1 minute is 60000 miliseconds
Runnable r = new Runnable() {
#Override
public void run(){
new BatteryLifeTask.execute();
}
};
Handler h = new Handler();
h.postDelayed(r, waitTime);
}
}
Be aware that this code is untested. But I hope it gives you an idea :-)

Thread reset when resuming application

Please I need help!!
I created an app that reads data from arduino through separate thread (ReadingProcessor) and fillings the values into readings[], then I created another separate thread that checks on the values. In this checking, if it's the first time that a warning occurs then the application sends message, else if there is previous warning readings, the application should wait till passing a warning interval
public class WarningProcessor extends Thread {
float readings[];
float[] min, max;
long elapsedTime;
long[] lastWarningTime;
boolean[] inWarning;
long checkInterval = Long.parseLong(Settings.Swarning) * 60000;
long currentTime;
SerialActivity sa = new SerialActivity();
WarningProcessor(float readings[]) {
this.readings = readings;
}
#Override
public void run() {
sleep_s(2);
synchronized (readings) {
lastWarningTime = new long[readings.length];
inWarning = new boolean[readings.length];
Arrays.fill(inWarning, false);
}
while (true) {
this.readings = ReadingProcessor.readings;
synchronized (readings) {
for (int i = 0; i < readings.length; i++) {
currentTime = Calendar.getInstance().getTimeInMillis();
if (readings[i] > 100) { //here to make boundaries
if (inWarning[i] == false) {
//send warning
for(String number : StartPage.phoneNumbers)
SmsManager.getDefault().sendTextMessage(number,
null,"Warning "+readings[i], null, null);
lastWarningTime[i] = currentTime;
inWarning[i] = true;
} else {
if (currentTime - lastWarningTime[i] > checkInterval) {
//send warning
for(String number : StartPage.phoneNumbers)
SmsManager.getDefault().sendTextMessage(number,
null,"Warning "+readings[i], null, null);
lastWarningTime[i] = currentTime;
}
}
} else {
inWarning[i] = false;
}
}
}
sleep_s(1);
}
}
In case of continuous warning data the program should sends message in interval, and this works well when I'm still on activity and also when I'm onpause() state, but the problem is that after the onpause() when I return to application UI , the program resends messages in case of continuous interval, discarding the waiting till passing the interval
public class SerialActivity extends Activity {
private static ArduinoSerialDriver sDriver;
private static TextView mDumpTextView;
private static ScrollView mScrollView;
String Data[]={"Temperature"};
float[] readings = new float[Data.length];
ReadingProcessor readingProcessor;
WarningProcessor warningProcessor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.serialactivity);
mDumpTextView = (TextView) findViewById(R.id.consoleText);
mScrollView = (ScrollView) findViewById(R.id.demoScroller);}
#Override
protected void onStart() {
super.onStart();
ReadingProcessor rp = new ReadingProcessor(readings,sDriver);
readingProcessor=rp;
WarningProcessor wp = new WarningProcessor(readings);
warningProcessor=wp;
rp.start();
wp.start();
}
#SuppressWarnings("deprecation")
#Override
protected void onDestroy() {
super.onDestroy();
readingProcessor.Stop();
warningProcessor.stop();
}
So please help me, I tried too many solutions like using handler and I got the same problem
onStart is called every time you return the application to the foreground. Your problem is that you have multiple instances of each thread running. If you only want one instance of each thread running, you need to create and start the threads in onCreate instead of onStart. In general, you should only start a thread in onStart if you are going to kill it in onPause.

Need help to understand accelerometer code

I have read through a lot of code but I do not understand how you can make an image move using the accelerometer sensor, I understand how to register it but I do not understand how to actually make an image or a shape draw move in sync with the accelerometer axis, I am using android java to do this. Please can someone help me as I am really struggling. Thank you for your time and help.
So, here's the code to register a listener (I know you said you've done this already, but it can never hurt):
private void enableAccelerometerListening() {
sensorManager = (SensorManager) getSystemService(COntext.SENSOR_SERVICE);
sensorManager.registerListener(sensorEventListener), sensorManager.getDefaultSensor(
Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
private void disableAccelerometerListening() {
if (sensorManager != null) {
sesnsorManager.unregisterListener(sensorEVentListener, sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER));
sensorManager = null;
}}
You will need a couple fields just below your class declaration:
private SesnsorManager sensorManager;
private float acceleration;
private float currentAcceleration;
private float lastAcceleration;
private static final int ACCELERATION_THRESHOLD = 15000;
Here is the event handler, which gets very close to what you need help with:
private SensorEventListener sensorEventListener = new SensorEventListener() {
public void onSesnsorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
lastAcceleration = currentAcceleration; //save previous accel value
currentAcceleration = x*x + y*y + z*z;
acceleration = currentAcceleration * (currentAcceleration - lastAcceleration); // calc the change in acceleration
//if the accel is above a certain threshold:
if (acceleration > ACCELERATION_THRESHOLD) {
//MAKE YOUR CODE HERE THAT RESPONDS TO ACCELERATION EVENTS
//Note, your accel threshold should be determined by trial and error on a number of devices
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy {}
};
Also, I'll try to address some of your animation needs, though I am much more spotty in this area. I imagine that what you need to do is make your image move as the accelerometer detects moves. The image will have to be moved via an animation, rather than the accelerometer directly. So say 'spot' is your image, okay? (the code below both adds a spot and sets up its animations(which are not directly tied to the accelerometer, but I hope this will be helpful nonetheless):
public void addSpot() {
int x = random.nextInt(viewWidth - SPOT_DIAMETER);
int y = random.nextInt(viewHeight = SPOT_DIAMETER);
int x2 = random.nextInt(viewWidth - SPOT_DIAMETER);
int y2 = random.nextInt(viewWidth - SPOT_DIAMETER);
final ImageView spot = (ImageView) layoutFinlater.inflate(R.layout.untouched, null);
spot.setLayoutParams(new RelativeLayout.LayoutParams(SPOT_DIAMETER, SPOT_DIAMETER));
spot.setX(x);
spot.setY(y);
Well right here is where I think you could start doing something with the accelerometer events...
As you saw in my other response above,
if (acceleration > ACCELERATION_THRESHOLD) {
spot.animate().x(x2).y(y2).setDuration(animationTime);
animationTime will just be something in milliseconds that you feel is appropriate, and don't forget to take care of importing the necessary packages.

Categories