Android Development: Simple collision detection

For my App I need to know when a user drags a specified element on top of another element. For instance when they drag one of their attack cards to the deck of the oponnent. On top of that I also need to know if the current location will result in an attack movement or just in a drag in open space. In both situations the game should do something else. So how can we detect if the current location is resulting in an attack? Simple by using the Rect.intersects method like so

this class implements a few utility methods. They bassicaly to the same thing. They convert the given parameters into two Rect instances and call the intersect method of the first Rect.  With this little tip you can easily integrate some basic collision detection. with this knowledge we can easily find out if the current user is attacking the enemy and which card is being attacked with the following code:

In this example we loop over the enemyfrontline cards and for every card we check if it intersects. If that is the case we break out of the loop and use the found card to do the stuff we want to do with it ( in my case find out which card has ‘won’ and respond accordingly.

 

Android Development: Loading image

In a previous post I talked about loading bitmaps. In this post I will tell something about caching the loaded resources. For this I created a little util class. To give you an example how to use it here is the code. I will explain it step by step.

When the View needs an image it calls the method ‘build’ (3).

It passes a Card object that specifies which card we want to load. We also need to tell the builder which color we need  ( two sides in this game remember? )

It will first check if bitmap belonging to the card specified already has been loaded in the past (20-26).  It therefore will get the correct cache (21-24) ( Yes I have 2 cache’s one for each side ). When the card has not been found in the cache it should be loaded (  5 and 6). Therefore we find the correct drawable (from the R object ) (29-32) and create a bitmap out of it (33-35). We scale it down using a scale matrix and we put the image back in the correct cache (37-41). After that we try to load it again (line 15-16).

By using this approach we asure the app that it will always be using the same instance of a particular bitmap.

I hope this will help you a bit developing your own game apps.

Android Development: Adding touch support

When creating an App users need to somehow interact with your program. Mostly this will include touch support. To set up touch support you need to do the following Warning lots of code !! I will try to explain everything step by step.

Lines 8, 39,73: Listen to the various events.

Line 11-28: When a mouse-down event is detected it means that we are in a new cycle of down->move->up events. In this case it means that we first have find out if the current location was not the previous location and if this is not the case we need to find out if we touched something we are interested in ( 13 ). If so we will do all kinds of stuff with that element and call invalidate. This causes the UI to redraw everything.

Line 39 – 65: If the action_up is detected it means that we are done with our current operation. In this case it means that we have to find out where currently are situated. If that location somehow intersects with another element we are interested in it will cause a change in the ui ( in this case some cards will be redrawn with another image )

73 – 83: Touch support means in most cases drag support. We do this simply by getting our current location and move the current selected element ( a card ) to that new position. Since the x and y coordinates of the event are left/top coordinates we need to change that location so that we don’t touch the top/left corner of that element but somewhat in the middle this feels a bit more natural to the user.

This concludes this little blogpost about touch…

Android development: Loading bitmaps

If you want to add graphics to your application you can use the following information

Create a custom Activity like this

Create your own View ( in this example StrategoGameView)

I personally find it a good practice to call an initialize method in your constructor. This way you can decide if you want to make it public so when needed you can reinitialize easily.

Now if you want to add a Bitmap to your application you need to do the following things

Add a res/drawable directory to your project

create some fancy images and save them in this directory.

After a rebuild you can get a pointer to the using the R.drawable object like this

to draw the bitmap to the screen you need to add a onDraw method to your View like this:

 

Android Development: Responding to a socket request

Warning: Worst Blog post written ever in history!

in my current project, a simple multiplayer game, I need to react on a connection request from another device. Currently both devices start their own service discovery. On one device I go to the list of found services and pick on. On the click the ServiceHelper will try to resolve the chosen device and if successful it will start communication sending a simple ‘gameplayrequest’ string.

the other device reacts to this with a OK response. This response is generated only when the user accepts the ‘invitation’. Ok and now some code 😉

These are some code snippets First we need to connect to the other device after we done that we need to send a response. This has to be done in a separate thread. The reason for this is that Android does not allow any heavy operations in the main thread. When we have notified the device that we are ok with the request the result is notified to all our listeners ( the view in this case )

And now the code to start resolving the chosen service

We get an instance of our service helper and subscribe ourselves to it

We start to resolve the service and logging which thing we clicked.

Now the update code in this activity

the update call first checks if the data that we receive is of the type notifier ( a class created by me to send data and some payload ). after we have resolved succesfully (see previous code snippet) we send a request to the server (first snippet) . The server will respond with an ok response ( or response_connection_allowed in this case ). We will log that for now but in the future this will cause a switch to another activity.

That’s it for now.

Android Development: Starting a server socket

As you already know the application i’m building is using service discovery to connect to other devices. How does this work?

Step 0:  Add activity as observer to the servicehelper class (line 4)

Step 2: Start registering the service to the network (10)

Step 3: If service has been registered successfully update ui and start a server socket that waits for any connection. (line 19)

 

Android development about listeners

For my App I need to use service discovery. Service Discovery is a piece of code that lets your android device search for other devices in the same network that can connect to you. But also it gives you the power to generate your own service so other devices can find you.

I wont go into detail about how to setup all this but it involves a lot of callback listeners. Althrough I like the idea of this I dont like the way some people on the internet, who explain this to people who never done this before, implement it. As stated in my previous android blogpost the standard tutorials work with the idea of putting everything in a activity. And well I just dont like that.

So for the service discovery logic and all listeners (3!) that go with it I created a class called ServiceHelper ( if you take a look at the tutorials from android about service discovery they use the same idea ). This helper is a singleton that registers a certain service on the network and works as its own listener for these type of events. So how is this different from the default approach?

The difference comes when I want to let the activity know that something has happened. I’m using the so called Observer/Observable pattern for this. I create my activity. I retrieve an instance of my servicehelper and add myself as a listener to that helper class.

the only thing I need to do next is to add a method ‘update’ so the helper can inform me about what happened. Why I like this idea better? Simple. If an activity implements a RegisterServiceListener, a ResolveListener, a GetMeSomeCoffeeListener the activity gets poluted with all kinds of ‘listener’ methods such as ‘onCoffeeServed’ or ‘onNoCoffeeAnymore’ methods.

Now I only have 1 method update(source, data) and in this update method I can add the logic to handle all the events I’m interested in. I think it makes the code a bit cleaner and easier to understand.

Android Development

It has been a while since my last dev related posting but here it goes. I decided to pick up android development to see how it goes and if it is as hard as people say it is. This blogpost will give you a little insight in the things I stumbled upon. Be warned. This blogpost is not written in some chronological order. It just a bunch of things I have to remember when doing android development. Therefore this post can be updated in the future.

Continue reading

Java: Reading GPX data from Endomondo

I’ve started using Endomondo as my primary workout application for a couple of weeks now and although it is a great app I want to have more control over my data. Luckily for us endomondo users they offer a export function that exports the workouts in GPX format.

Today I’ve been playing around with this library: https://sourceforge.net/projects/gpxparser/ and get the GPX file from Endomondo to be parsed succesfully..

So first of all I created a new project in my Eclipse and imported the GPX parser from the website into another project. I downloaded a file from my endomondo account and wrote a little code:

As you can see. Nothing to fancy. So now what? If we take a sneak peek at the file http://www.jeroensomhorst.eu/wp-content/uploads/20140816_100357.gpx you will see there is no information whatsoever about distance, speed, average heartrate and so on. We have to add that ourselves. Luckily its GNU license so I can edit the source as I please (or atleast that’s what I make out of the license..).

Let start by refactor the GPXParser class. I want to generate a custom GPX class that implements my interface EndomondoGPX. First create the interface

Nice, isn’t? Next create a new class called EndomondoGPX

The code is pretty simple. There are some util functions there for retrieving all the trackpoints. This method also sorts them by time.

To make this happen I had to make  change to class that is base for all classes in the default GPX parser. The extension class. I had to make it abstract, implement a interface (comparable !) and make a abstract method public int compareTo(Object o1, Object o2).

All other classes such as waypoint should implement the compareTo. For this patch I only need to add the compareTo to the Waypoint class.

After some testing I found out there is a little bug in the GPX parser. When there is more then 1 trkseg node it will overide that node all the time. So you will end up with only the last trkseg node. In this case (see file) it will only contain one trkseg with one trkpt node. Not what we want!

The fix for this is the following method in Track.java

It won’t overwrite all trackpoints for the current track it will add them. For now that is correct but I wont recommend it for all GPX files out there.

So, when that is done. We can start changing our Parser class.

Open up the GPXParser class and add the following method:

and refactor the method signature of parseGPX to

Now add the following method for backwards compatability:

What we have done is pretty simple. First we created a new method to parse given GPX file (using inputstream) to a object of our own. We tell the GPXParser to parse the xml to our own instance of the GPX class. (in our case EndomondoGPX ).

Next, because we added that method we had to change the default method. We made it private, so that nobody can use it behind our back and we added a new parameter an instance of the GPX class. Inside this method we had to remove the  the GPX gpx = new GPX() because we now send it in as a parameter;

Last of but least we had to add a new method for backwards compatability. All this does is creating a new default GPX object and pass it into the changed method. We can now change our first code snippet to :

As you can see we have now full control what type of GPX object we get.

To get this all working by the way you also need to create a new HeartRateExtensionParser class. This class is used to parse extensions that comes with Endomondo.

If you want to code.. let me know. It is still little buggy (the distance calculations seems to be a bit odd compared to endomondo ) but it works.

Prestigio Multipad_4_QUANTUM_9.7

If you ever have the need for buying a Multipad_4_QUANTUM_9.7 from prestigio. Please be aware that you should follow the following instructions when ipgrading your firmware. Because if you don’t you will spend HOURS and HOURS finding out why you’re tablet is not recognized by the ‘splendid’ rkbatcher tool.

oh and just to warn you . If you upgrade you’re firmware you lost all your settings.. and data..

1. Shutdown tablet

2. Remove external SD card (if present)
3. Plugin USB cable into tablet
4. Hold Vol+ and Power and connect USB to computer. When computer detects new device, release buttons (this is typically after 3-4 secs – if you hold longer, you will get to recovery mode (android bot with open belly) and you don’t need to be there => use volume to bring up menu, use volume again to select “reboot” and power button to confirm).  It remains a bit of trial & error…
5. Install driver from rockchip package.  => See below
6. Optional: Shutdown tablet (not necessary in my case, since I can see the device stays connected in Windows Device Manager)
7. Start Rockbatchtool after correcting the config.ini file => see below
8. Press Power & Volume+ to start tablet –> will be recognized by Rockbatch tool (green button at connected devices)
9. Load update image and click Restore … wait until reboot

 

Installing driver goes like this:

1. Windows / Open Control Panel (you wanna have this open before starting the above procedure)
2. Select “System”
3. Open “Device Manager”
4. Watch the list as it will change upon detection of a new device.  It should add something like “Class of Rockchip Devices” near the top of the list. You’ll see a device with a yellowish exclamation mark
5. Right click onto the new device and “Install/Update Driver”
6. Choose the driver from “My Computer”

 

Now: as for the config.ini modification, I found on minixforums a post by user Snurb that does the trick.  You open config.ini (located in the same folder where the .exe file is) and look for this line:

LOGFLAG=TRUE

#SUPPORTLOWUSB=TRUE时,扫描支持full speed usb设备,默认只支持high speed usb设备
SUPPORTLOWUSB=

This you change into:

LOGFLAG=TRUE
#SUPPORTLOWUSB=TRUE时,扫描支持full speed usb设备,默认只支持high speed usb设备
SUPPORTLOWUSB=TRUE
FULLSPEEDUSB=TRUE

Save & close.

Then you start Rockbatch Tool and all of a sudden, I had a green flashing light… ready to flash the new firmware!

 

Hope this helps.  Happy flashing!

 

source: http://xpag.es/?1DBA