CategoryJava

Android How to programmatically close an app by pressing back button properly.

Everyone who uses apps knows that they are sometimes rather tough to exit. It’s not always because developers don’t care too much about it. Sometimes the api is tricky. If you want the user to exit your application by pressing the back button you need to override the onKeyDown method in your activity. The default implementation would be moveTaskToBack(true), which basically pauses your app and sends it to the background, right? Wrong! Because it only pauses the ui-thread.

Which means any other asynchronous task running keeps running. It wastes resources, leading to a worse user experience and and eventually to uninstalls. Why? Because it’s a unexpected behaviour. I mean don’t get me wrong, it’s perfectly fine if the app goes to the background because the user is getting interrupted by other apps. However if he wants to exit, he should have a possibility to do so. But what then?

Calling finish() often doesn’t do the trick. In that case you can use killProcess with the app process id.

Done. Just make sure that you have finished all your business before actually killing your app like saving preferences, etc. It will immediatelly close the app.

See also activitys-threads-memory-leaks

How To Get Android OpenGL 1.0 and 2.0 Information and Constrains – Revisited

Some time ago I’ve made a short post (here) about the basics of how to get opengl infos on an android device. For an app I’m currently working on it was required to get all interesting information once more in my android device information application. The basic idea is to add a respective opengl 1.1 or opengl 2.0 and possibly even opengl 3.0+ context to the active view, load all information in the onSurfaceCreate method of the renderer and remove the view afterwards again.

You’d use it appropriatelly like that in your activity:

Here is what I came up with:

Enjoy. (:

Java Enums in C#?

I really love C#! Almost all features like delegates, extensions methods, constraints, lambdas, refs, “magic methods”, etc. are really super convinient to use. It’s totally my favorite language so far and trust me I’ve been around with C/C++, Php, Javascript, Java. I pretty much code all the time in C# nowedays.

Probably one feature that Java did way better than C# is the way to extend enums. As stated on this website especially made for java to c# converting people.

Enums are used to create and group together a list of user defined named constants. Although on the surface the enumerated types in C# and Java seem quite similar there are some significant differences in the implementation of enumerated types in both languages. In Java, enumerated types are a full fledged class which means they are typesafe and can be extended by adding methods, fields or even implementing interfaces. Whereas in C#, an enumerated type is simply syntactic sugar around an integral type (typically an int) meaning they cannot be extended and are not typesafe.

You can use enums in Java as collection of concrecte behaviour implementations:

Or have a concrecte amount of certain Objects of a kind like a represenation of different resolutions.

Sure you can do it with normal classes, readonly attributes in c# too. But i was wondering how much of the functionality you could “port” towards c# with the help of generics, extension methods and injected attributes. So this is a small test i came up with the help of some respective stackoverflow articles.

Conclusion

Well it’s far from elegant/readable or even practically usable. However it’s possible to a certain extend. Feel free to correct me.

Android: OpenGL 1.0 and 2.0 infos

So here I was again, trying to figure out a way to get opengl infos like max texture size, max uniform vectors, max vertex attributes, etc. for several android devices. Technically you could just use a small getter:

The problem was that on many devices the the returned number would always be 0. That’s because there hasn’t been created an opengl context yet. As suggested on Stackoverflow you could create a GLSurfaceView, add a renderer which could read the required infos by adding the glsurfaceview to the actual main active view and simply remove itself when done. In order to get opengles 1.0 and opengles 2.0 infos you would need to create two surfacesviews with different opengl versions. The following example looks a bit complicated, because I use fragments which i need to update on the main thread after I got all the infos I wanted. A full example is on github.

How to get the MAC address on Android

(A test project can be found on github)

Since you can easily get confused with the many permissions provided by google, let me show you two ways to get the mac address on android. The first approach would be to use the WifiManager.getMacAdress().

However there are Disadvantages:

  • Device should have Wi-Fi (where not all devices have Wi-Fi)
  • If Wi-Fi present in device should be turned on otherwise does not report the MAC address
  • And the suspicious permission ACCESS_WIFI_STATE

Another approach is the use the NetworkInterface.getHardwareAddress()

Disadvantage: uses permissions too, although they are required for your app to access the internet anyway and more likely commonly known to the end-user.

Conclusion:

Carring about permissions can be a pain in the butt there are even other ways if you just want identifying app installations, too.

Android libgdx ShaderAssetLoader & StillModelLoader

I totally love how libgdx brings a lot of interfaces for your application to connect to the graphics library. For instance the asset manager is really thought through well in particular. It has some really useful methods like Assets.manager.getProgress(). Especially since you can easily write your own asset loader and be able to utilize the loading progress in your app.

1) Simply add your loader to the asset manager at some point.

2) load your assets at required places, e.g. loading screen
(Note: SHADER_PHONG = “data/Graphics/Shader/Phong”; and MODEL_TEAPOT = “data/Graphics/Shader/teapot.obj”)

3) get your shader or model wherever you need them

4) free the resource by unloading when you’re done with them (e.g. disposing your app; changing screens)

That’s the shader asset loader for loading custom shaders in libgdx. (Note: adapt your extensions)

And here is the StillModel loader for loading 3D meshes:

Conclusion: assets are handled well in libgdx :D

Android: Saving Screenshots in OpenGLES

1) Get your helper methods:

2) get a queue ready

3) add new filepath the the queue via e.g. events:

4) IMPORTANT! save the screen at the end of the opengl render process. (Note: If try to capture somewhere in the middle you might end up with a black screen or any other funny effects.)

My top 10 inspiring teachers at the Beuth University of Applied Sciences Berlin for B.a. Media Computing

In school and noticed there are bad and really amazing teachers. They are as different as day and night. At the beuth university of applied sciences I had the luck to have some really awesome teacher and I’d like to credit them at some point. Thanks for your hard work, to learn from you is probably the reason people study in the first place.

#1 Stephan Rehfeld – Computer Graphics 1 (homepage, facebook, script)

#2 Prof. PhD.-Eng. Hartmut Schirmacher – Computer Graphics 2 (homepage, script)

#3 Siamak Haschemi – Advanced Concepts in Programming- and Program Architecture (homepage, blog, twitter, youtube, github)

#4 Prof. PhD. Martin Oellrich – Math 1 and 2 (homepage, script)

#5 Prof. PhD.-Eng. Joachim Schimkat – Programming 1 and 2 (homepage)

#6 John Gordon – Presenting in English

#7 Dipl.-Inform. Thomas Ziemer – Software Engineering 2 (homepage)

#8 Dipl.-Inform. Ilse-Renate Schmiedecke – Human Computer Interaction (homepage, script)

#9 PhD. Sabine Vollmert-Spiesky – Comunication and interaction at profession (homepage)

#10 Prof. PhD.-Eng. G. Awad – Distributed Networks (homepage)

How to swap two variables without a temp variable

In C

In Java

In Assembler

Fun fact: fastest is still with temp variable. (:

Extra python:

How to iterate over a java map

Since I’ve been asked this a lot lately …

Extracted from Reference link (original Sergiy Kovalchuk): How to Iterate Over a Map in Java

There are several ways of iterating over a Map in Java. Lets go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement Map interface, following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)

Method #1: Iterating over entries using For-Each loop.

This is the most common method and is preferable in most cases. Should be used if you need both map keys and values in the loop.

Note that For-Each loop was introduced in Java 5 so this method is working only in newer versions of the language. Also For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.

Method #2: Iterating over keys or values using For-Each loop.

If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.

This method gives slight performance advantage over entrySet iteration (about 10% faster) and is more clean.

Method #3: Iterating using Iterator.

Using Generics:

Without Generics:

You can also use same technique to iterate over keySet or values.

This method might look redundant but it has its own advantages. First of all it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling iterator.remove(). If you try to do this during For-Each iteration you will get “unpredictable results” according to javadoc.

From performance point of view this method is equal to For-Each iteration.

Method #4: Iterating over keys and searching for values (inefficient).

This might look like a cleaner alternative for method #1 but in practice it is pretty slow and inefficient as getting values by a key might be time consuming (this method in different Map implementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.
Conclusion

If you need only keys or values from the map use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration you have to use method #3. Otherwise use method #1.