I have two class, one is an activity that can handle Chronometer, another is handle LocationListener.I want to run them together to use stopwatch and to get changed location.
Anyone have any samples or suggestions ? Thanks
Addition:
Sorry for the confuse question. I just need to know how to make chronometer run while keeping location that changed.
Well, you could use the LocationListener to add Location to an array every time it is changed to keep track of location.
Example:
public class MyClass implements LocationListener{
private static List<Location> locationList = new ArrayList<Location>();
#Override
onLocationChanged(Location location){
locationList.add(location);
}
}
Then you could use System.getTimeMillis() (or something akin) when you want to get the start time, and the same method when you want to get the end time. Just subtract the two to get the time difference and how long it took.
Related
My android application retrieves some json data from remote API for each Marker (a Marker shows the position of a real device, there are less than 10 devices to watch) present on the map, and sets status of a device by changing a color of the marker according to some rule working on a given json data. I use AsyncTask to fetch json data and change a status of a device. I keep fetched data in ConcurrentHashMap<Device, Data>. So, I run a number of asynctasks, one for each device. I also use a custom info window (in fact custom InfoWindowAdapter) to show some more data about device. First I draw a markers and keep them in a map HashMap<Device, Marker>. I execute asynctasks one by one using:
new MyAsyncTask(markerMap).execute(device)
My custom InfoWindowAdapter overrides getInfoContents method, where some collected by asynctasks data are used to be shown in InfoWindow, when clicked.
Everything works fine. But now I want to refresh my markers every 10 sec. I have tried to do it using the following approach:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run() {
new MyAsyncTask(markerMap).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, device1);
new MyAsyncTask(markerMap).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, device2);
}}, 0, 10000);
My question is if it is the right/ best way to refresh my map? Or should I use Runnable instead of AsyncTask, and within a Runnable send a message to Handler when fetching json data to update Marker? One more question: should I use Timer or ScheduledExecutorService? I have read some StackOverflow discussions but I dont know the final recommendation. Thanks.
Finally I have solved my problem. In mean time I have rewritten part of my program in order to use ScheduledThreadPoolExecutor with subclassed Runnable (instead of Asynctask). In addition I have added onResume() method where I restart ScheduledThreadPoolExecutor using: mScheduledThreadPoolExecutor.scheduleAtFixedRate(runnable, 0, interval, TimeUnit.MILLISECONDS);
I have situation where I get the nearest location based on checking the distance between current lat and long
public void onLocationChanged(Location loc) {
lat1=loc.getLatitude();
lng1=loc.getLongitude();
Com_Util.check_NearLoc(lat1,lng1);
}
I update a static variable which contains the nearest place from the current location and display in a text view showing the current location in all the activities. I am able to get the nearest place and was able to display it only during onCreate of an activity.
I need a text view showing the current location while using the app. I dont want a thread to be running all the time checking for the location change instead is there any way updating the textviews from the check_NearLoc function itself which is in a nonactivity class.
It want to keep an array (Java generics for example: List) of the last 10 coordinates in order of retrieval so latest coordinates are always at the top of the stack etc. If I ask for this array we can then go back to see what steps the user took by tracing there steps.Please help me here.
Thanks
First you need to read about how to retrive the user GPS location.
http://www.vogella.com/articles/AndroidLocationAPI/article.html
Then make your class implement android.location.LocationListener and in the onLocationChanged() callback just add the location to the list.
#Override
public void onLocationChanged(Location location) {
list.add(location);
}
On developing a painting canvas application in android, i need to track all the points and have to redraw it in another canvas. Now i am able to track all the points, but don't know how to synchronize the point drawing in case of draw and redraw ie the user should redraw the points at the same time gap as in the draw. How can i achieve this?
Not sure if this is the sort of answer you are looking for but I would record the events with a sort of timestamp, really a time difference to the next point. Something like:
class Point {
int x;
int y;
long deltaTime;
}
Its up to you how precise you want to be with the timing. Second to millisecond precision should be good enough. You could interpret deltaTime as either the time until this point should be drawn or the time until the next point should be drawn (I'm going to use the latter in my example).
A few reasons to use a deltaTime instead of a direct timestamp is that it lets you check for really long pauses and you are going to have to compute the delta time anyways in playback. Also using it as a long should give you enough room for really lengthy pauses and lets you use the Handler class which accepts a long integer for the number of milliseconds to wait before executing.
public class Redrawer implements Handler.callback {
LinkedList<Point> points; //List of point objects describing your drawing
Handler handler = new Handler(this); //Probably should place this in class initialization code
static final int MSG_DRAW_NEXT = 0;
public void begin(){
//Do any prep work here and then we can cheat and mimic a message call
//Without a delay specified it will be called ASAP but on another
//thread
handler.sendEmptyMessage(MSG_DRAW_NEXT);
}
public boolean handleMessage(Message msg){
//If you use the handler for other things you will want to
//branch off depending on msg.what
Point p = points.remove(); //returns the first element, and removes it from the list
drawPoint(p);
if (!points.isEmpty())
handler.sendEmptyMessageDelayed(MSG_DRAW_NEXT, p.deltaTime);
public void drawPoint(Point p){
//Canvas drawing code here
//something like canvas.drawPixel(p.x, p.y, SOMECOLOR);
//too lazy to look up the details right now
//also since this is called on another thread you might want to use
//view.postInvalidate
}
This code is far from complete or bullet-proof. Namely you will need to possibly pause or restart the redrawing at a later time because the user switched activities or got a phone call, etc. I also didn't implement the details of where or how you get the canvas object (I figure you have that part down by now). Also you probably want to keep track of the previous point so you can make a rectangle to send to View.postInvalidate as redrawing a small portion of the screen is much faster than redrawing it all. Lastly I didn't implement any clean-up, the handler and points list will need to be destroyed as needed.
There are probably several different approaches to this, some probably better than this. If you're worried about long pauses between touch events simply add a check for the deltaTime if its greater than say 10 seconds, then just override it to 10 seconds. Ex. handler.sendEmptyMessage(MSG_DRAW_NEXT, Math.min(p.deltaTime, 100000)); I'd suggest using a constant instead of a hard coded number however.
Hope this helps
So, I have plotted a GPX route in my MapView, and I am listening for location changes.
Ultimately I want to give my user notification when they are off/on course.
So, I can imagine just brute-force going through all my GPX coordinates and do a Location.distanceTo for each for each of them. But that seems expensive.
I could reduce the cost by doing it infrequently.
I am wondering if someone has a clever idea for achieving this?
You can use the function distanceTo but not inside onLocationChanged (because it is called very frequent) , you should do a timer and check if the user going off course in each 5 seconds (for example), this is how to implement the timer:
1- declare this as global variable:
private Timer myTimer;
2- add this code in your onCreate():
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 5000);
3- add these two functions in your class:
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//do your test for off course here
}
};
Good luck
I would probably keep track of three coordinates: Last, Current, Next. You can calculate the distance and direction from Last to Current and the location and direction the user is going and come up with some algorithm to ensure the user is going the right way (ensure that the user is approaching Current, ensure that they're within some distance of the line from Last to Current, etc.)
Then at some point you need to realize that the user has come as close as they're ever going to towards Current and are now heading for Next. Then you'll shift the points down (Last = Current; Current = Next; Next = ???;). Again there are a number of ways you could make this determination (user has gotten close enough to Current, user is heading towards Next and away from Current, etc.)
You might want to include some look-ahead in case you miss a few points, especially when points are close together, but you don't want to do too much. Test your route with loops in the paths and make sure you don't jump ahead. You'll probably also need to implement some sort of holyExpletiveIHaveNoIdeaWhereTheUserIsGoing() method to recover from the (inevitable) errors.