A small problem with the facebook Android SDK

At Mobialia the lasts weeks I was involved on the development of a social app using , among other social networks APIs, the facebook API.

For me it was easier to implement Twitter API access using only the signpost library, for facebook they recommend to download their Android SDK, and I did so. First we need a class attribute with the Facebook object:

Facebook fb = new Facebook(appId);

The problem is during the autentication process: we must call the fb.authorize method…

fb.authorize(this, PERMISSIONS, ACTIVITY_CODE, this);

And wait for the result of this called activity on our onActivityResult method

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    fb.authorizeCallback(requestCode, resultCode, data);
}

But, here is the problem, under heavy memory requierements (like testing on a old HTC Magic) the caller activity may be killed, and the status of the Facebook object is not maintained so the call to authorizeCallback is going to fail.

Then I need a method to mantain the Facebook object status, and here comes the hack. I added this method to the Facebook object:

public void setStatus(int mAuthActivityCode, DialogListener mAuthDialogListener){
    this.mAuthActivityCode = mAuthActivityCode;
    this.mAuthDialogListener = mAuthDialogListener;
}

And I call this method on my OnActivityResult:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    fb.setStatus(ACTIVITY_CODE, this);
    fb.authorizeCallback(requestCode, resultCode, data);
}

Note that the DialogListener is the same Activity. Other solution may be to avoid killing of the caller activity, but I don’t figure how…


Using two location providers on Android


Android has two kinds of accuracy on location:

  • Fine: provided by the GPS, needs some time to be obtained
  • Coarse: location determined with the cell of the mobile network

This location methods can be enabled or disabled by the user on the preferences or with some widgets.

Initially on our apps we used only one LocationProvider with “Fine” accuracy:

  • If the GPS was disabled it used automatically network-based location
  • But if GPS was enabled, the location used it needing some time to be determined

As the data couldn’t be obtained until the location is determined, the app didn’t showed data, receiving this kind of error reports from some users.

The best solution that I found is to mantain two separated providers, with different precisions and receive location updates using both.

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);       

criteria.setAccuracy(Criteria.ACCURACY_FINE);
String providerFine = manager.getBestProvider(criteria, true);

criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String providerCoarse = manager.getBestProvider(criteria, true);

if (providerCoarse != null) {
    manager.requestLocationUpdates(providerCoarse, 5*60000, 100, this);
}
if (providerFine != null) {
    manager.requestLocationUpdates(providerFine, 5*60000, 100, this);
}

You can also check if providerFine and providerCoarse are the same provider. When receiving location, the one received from providerFine must take precedence over the one from providerCoarse. Location’s provider can be obtained with location.getProvider():

public void onLocationChanged(Location location) {
     if (location.getProvider().equals(providerFine)) {
     ...

This is a trick that we are using on our Gas Stations Spain app and also on Wikiplaces (open sourced).


Mobialia at LabAndroid

This week I was speaking at LabAndroid, a spanish initiative about Android devices, apps and development.

I developed a special app for this event called “Wikiplaces” and I made the code avaiable as open source on Google Code.

This app shows on a map or on a list places from Wikipedia near your location. I tried to include on it small code snippets for common things like styles on layouts, obtaining location, launching Google Maps Navigation, etc.


Dealing with the “Bitmap Size Exceeds VM Budget” error

One of the most common errors that I found developing Android Apps is the “java.lang.OutOfMemoryError: Bitmap Size Exceeds VM Budget” error. I found this error frecuently on activities using lots of bitmaps after changing orientation: the Activity is destroyed, created again and the layouts are “inflated” from the XML consuming the VM memory avaiable for bitmaps.

Bitmaps on the previous activity layout are not properly deallocated by the garbage collector because they have crossed references to their activity. After many experiments I found a quite good solution for this problem.

First, set the “id” attribute on the parent view of your XML layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:id="@+id/RootView"
>
...

Then, on the onDestroy()  method of your Activity, call the unbindDrawables() method passing a refence to the parent View and then do a System.gc()

@Override
protected void onDestroy() {
	super.onDestroy();

	unbindDrawables(findViewById(R.id.RootView));
	System.gc();
}

private void unbindDrawables(View view) {
	if (view.getBackground() != null) {
		view.getBackground().setCallback(null);
	}
	if (view instanceof ViewGroup) {
		for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
			unbindDrawables(((ViewGroup) view).getChildAt(i));
		}
		((ViewGroup) view).removeAllViews();
	}
}

This unbindDrawables() method explores the view tree recursively and:

  • Removes callbacks on all the background drawables
  • Removes childs on every viewgroup

This solved the problem on many of our Mobialia apps.

UPDATE 2011-03-30:

Today @luiskap from SpartanBits told me another good solution: if you don’t need different layouts for portrait and landscape modes, you can make your activity react to orientation changes (avoiding activity destroy) adding to your activity’s manifest: android:configChanges="keyboardHidden|orientation" and overriding the onConfigurationChanged method, calling setContentView reusing the already created views. There is a good explanation on StackOverflow.


Find Android apps with AppBrain

One of the first things that you can notice after buying an android phone is the great amount of mobile applications (apps) that you can download from the Android Market, but searching for a specific app can be very frustating, and a time-consuming task.

This is due to one of the biggest problems of the Android Market: the lack of a complete web interface to query the applications avaiable, and AppBrain is an independent web (not affiliated with Google) where you can list, search, etc. those apps.

There are many similar webs: Cyrket, Bubiloop, but Appbrain has some features which make the difference:

  • You can sign-in on the web with your Google account
  • Apps can be queried by country, genre (of the user), age range, etc.
  • You can create list of apps and share it with your friends
  • There is an android app (search for AppBrain on the Android Market) to synchronize your mobile with appbrain, and once installed:
  • You can query the installed apps on your mobile
  • You can install apps from the web

And everything with a very simple and pretty interface, so don’t wait to try it:

http://www.appbrain.com


Media center and home cinema with XBMC

I played many years with MythTV and XMBC, and now on our new home and after buying a TV, I finally decided to switch to XBMC. I will explain all my choices for those of you who want to build your own media center:

HARDWARE

  1. Plasma TV 42″ Full HD Panasonic TX42S20: about 630 eur (but I got it by only 460 eur!). Plasma TV’s are now quite cheap and they offer a great image quality (much, much better than any LCD, believe me).
  2. Logitech X-540 5.1 speakers: 94 eur, very affordable. They are an old model but what I like of this is that they are wall mountable. They have only one sound input, so I connected them to the computer and the TV audio output with the Line Input of the computer (with a RCA to mini-jack cable, 2 eur). I needed to make some extension cables with RCA connectors to reach the speakers positions. Theoretically these speakers haven’t enough watts for the room,  but it has great sound quality and makes up for it.
  3. My OLD computer, an Athlon 2 GHz with an ATI Radeon 9550 (with DVI output) and a SB Live 5.1. I needed also a HDMI cable (10 eur) and a DVI to HDMI converter (15 eur).  Curiously this “slow” computer is able to play video to a FullHD 1920×1050 output. I’m planning to get a Home-PC case, at the moment the PC is in a corner of the room.
  4. An Iomega external USB Hard Disk of 1 TB: 95 eur. My old computer hadn’t enough disk space for music & movies. I could have bought a Multimedia Disk, but XBMC is much more pretty and you can also configure it for gaming.
  5. A T-Visto wireless keyboard with touchpad: 30 eur. I could had a a remote TV-like but finally I preferred a complete keyboard.

Total, about 900 eur without the computer.

SOFTWARE

For many years I used MythTV with a TV-tuner card on my computer, but I hadn’t a TV. There are only two features of MythTV not avaiable on XBMC: TV tuning and TV recording: having a TV I need no more the tuning, and I was not using the TV recording (there is nothing enough interesting on TV).

XBMC is a very cool media center available for Windows, Linux and Mac. I installed it over a Debian (because I’m a Linux Fan) but is easy to install on any OS. Is skinnable and has many plugins to add funcionality. Now I am using the default Confluence skin and the Launcher plugin for my games (Performous, Stepmania…) and Emulators (Mame, Mess…). This required some simple bash scripting to create all the launcher config.

Ok, this is a very funny hobby and I spent lots of hours choosing an configuring but the result is very good!


Google DevFest 2010

As many of you know, this year I’m involved on Android with my project Mobialia. On February I was on the Android Developer Lab at Madrid and today I returned for the Google DevFest.

The event started with Dave Burke presenting Google Technologies in general. Many jokes about the iPhone (to show the Chrome2Phone extension he send a page about iPhone unlocking from Chrome to a Nexus One). He made the typical Sunspider Javascript Test comparation between a Nexus One with Froyo and an iPad. It also was quite impressive so see GWT Quake2 Port running on Chrome at 50 FPS and the new voice/camera input fields on HTML5.

Then the sessions where split on two lines, I assisted to the Android, Chrome&HTML5 and Maps related.

Our beloved Reto Meier was speaking at the Android Sessions, much more technical than on February’s Android Developer Lab (good!). On his first session he made a great presentation about good and bad practices developing Android Apps (I suggest every android developer to see it!), on the second he speaked in detail about Cloud to Device Messaging and vice-versa. He gave me lots of app ideas using this feature. Finally he swowed us proudly his new Samsung Galaxy Tab and encouraged us to adapt our applications to the new tablet devices. I even had to buy myself one after hearing how amazing it was. Luckily, I was able to find some pretty good deals online (more right here).

There were also very short presentations of spanish app developers (eAdventure, LibreGeoSocial, Inmobilia, Sicad and great the one of AnderWeb!).

Next, Paul Kinlan speaked about Chrome Apps and Extensions, the App Store and HTML5 on detail. I’m also very happy to see the progression of HTML5 and how Chrome is leaveraging the innovation towards a better web. Quite funny to see a modified Pacman Doodle controlled with the acceleromers of the iBook. There was also a presentation of Fiabee showing their HTML5 app and Chrome extension.

On the last sessions with Josh Livni talking about maps and presenting the Google Maps API v3, I was very impressed with maps customization, Fusion Tables and the new Google Street view API possibiliting the creation of 360º photos and adding them on specific locations (as inside a bar!).

All the sessions where recorded on video and will be avaiable at the Google DevFest Madrid web site.


Tales of a chess engine developer

Chess engine development is one of the most brain-crushing activities I’ve been involved on the last years. Last nigths I was working again on my Carballo Chess Engine with some advances.

First of all I decided to leave Negamax and go with Principal Variation Search (PVS). Also decided to implement separate methods for root nodes, PV nodes and null window searches. On previous experiments PVS was performing worse than Negamax, but I discovered the reason: the aspiration window has some implementation issues with PVS: when the search for a move fails low at the root node the move must be researched enlarging the window.

I was very stranged of why Futiliy Pruning was not working for me, but finally discovered the reason: a simple sign change after evaluation was the reason! Also implemented to store the evaluation values on the Transposition Table (TT).

The next step: why Carballo searched much less depths than other engines, it was due to quiescence search. I was generating checks for the first 4 PLY’s of quiescence, but some other engines not, so this was the reason. I decide to generate only checks on the first PLY of quiescence and only for PV nodes. Also modified a bit the move generation to optimize for quiescence.

During this time also found many interesting bugs, I was storing on the TT the bound and not the score when failing high/low, also on PV nodes is better to use only the TT for ordering and not to return scores from it, this helps avoiding draws. Also found a serious bugs involving time management (was taking as reference opponent’s time) and with contempt factor on IID searches corrupting TT entries. Finally added a Pawn Push Extension and removed the Recapture Extension and now some extensions now depend of the node type.

Running some test tournaments, I hope to get some good results soon and add the improved engine to my Mobialia Chess.