Best android questions in April 2011

Android Game Keeps Getting Hacked

59 votes

So we've been through this several times now, we release a game (for cheap) and someone hacks it and puts it up on a mirror. We setup Google Alerts for all our apps, so we get told daily who's doing the hacking. So far, we have implemented the licensing service as Google has suggested, our salt is randomly made each time the license is initiated with the unique device ID. We run the check service once, when the application is started for the first time. We then generate a 512 character hash for the key and the stored value that is compared against in SharedPreferences from there on out.

Now, I know that checking once is probably where the application is being blocked. Our bytecode has most likely been looked at and recompiled without the line that initiates the check.

From here, I don't want to obfuscate our code as I have seen it broken before. I want something a little more solid, and I also want to learn how to do this properly. I am more interested in learning than making money at this point since only 2% of people will ever look for a hacked version.

So far, on my own, I have come up with a random number generator that is placed in several startup areas of the game. When initiated (say, 1 out of 50 times) the license is checked. I know this would make it harder to hack because the cracker would have to eliminate each case, compile, eliminate, compile. This method however, is still crackable...so what do you guys suggest? Again, I am really interested in this process of security, so please educate, don't turn this into a discussion on obfuscation or checking periodically based on a timestamp.

Thanks

My idea isnt hacker proof, but might remove some of the interest for hacking the game.

Freemium model

1) Make the first 5-10 levels free so people can learn the game and have some fun without paying. Less will want to hack the first level and the game will spread even further by Freemium model.

Shareware/clustered levelpacks

2) Let part of the game levels or logic stay online. Eg. when reaching for level 5 or 10 or 15, then download small parts for the game, and every time submit the progress-log from the game and validate this against possible values + hashcodes. This could perhaps make it possible to automatically close down of hacked accounts.

Stealth cheater protection

3) You could also just count "small warning flags" that you place around in the game. Dont just check for the "validation" in the beginning, no build these flags into the game logic itself. Dont make it break the gameplay, because then noone will look for it. Then when the user reached the end of level monster, check if there were any logged warning flags. These will not show up inside the game, so the unknowing user with a hacked edition could be playing for hours/days and suddently realize that he/she couldnt finish the game or advance to next level, because the game had a "bug". What the user didnt know was that this bug only occures on hacked clients.

Conclusion

Be smarter than the crackers. Fool them into thinking the job was done. Make a copyprotection and know that the more advanced crackers will be able to remove it. But they probably dont want to play 50 levels to check if the crack also works all the way.

Once they realize this problem, they might start to crack it too. But if you break the game up into level-packs, you can still validate between each pack download. So once you receive hacked client hash data, then just execute an exeception and crash the game on the client. Whoops the game crashed. Dont tell its because its hacked. A program error can happend. :-)

Again, its not hacker proof. But it might annoy them enough to move on to the next game. Lastly, you could also put out regular updates for the game and only the latest version should be able to "post the records" etc. so the active users would have to update to keep in the loop.

Optimize Android application before release

39 votes

I'm in a "special" situation about effeciency of my program. Now I'm at a phase where I want to maximize my application; being top notch and reducing battery consumption.

Before the question:

Now, I'm curious to hear about developers "special" tricks (fixes) that optimized their application(s). Stuff that users never gonna recognize or pay attention to; but instead increased the battery life or effectively made your application easier to maintain.

So, what's your unique optimizing trick(s)? (e.g. Object Pools? other patterns? unknown things? things that the website forgot to mention?) It doesn't have to be Android specific.

I'm in a particular situation where I'm really looking for knowledge and I think this will be a great opportunity to share developers knowledge about a situation they've all been in.

Please, vote up great answers as that will encourage great developers to share their knowledge.

At some point you are going to get to the point where using known tricks will hit their limits. The best thing to do at this point is profile your code and see what areas are the bottle-necks based on your specific requirements.

Profiling with Traceview and dmtracedump: an article on how to use the tools to profile your application.

Asynchronous programming best practices

28 votes

I have recently written my first Android app which was roughly 8,000-10,000 lines of code. One thing that continuously hindered my use of normal design patterns was android's heavy use of asynchronous calls (opening dialogs, activities, etc). Due to this, my code very quickly began looking "spaghetti" like, and I eventually started to dislike looking at certain classes.

Are there specific design patterns or programming methodologies which are for systems such as these that anyone would recommend? Are there any suggestions for writing manageable asynchronous code?

  • Use global variables

If you do not want to mess up your code with simple Intent.putExtra() and manage this things for each unique Activity you'll have to use global variables within the application. Extend Application and store data that you need as long your application is alive. To actually implement it, use this excellent answer. This will make dependecies between activities go away. For example, say that you need a "username" for your application during the application's life cycle - this is an excellent tool for just that. No need for dirty Intent.putExtra() calls.

  • Use styles

One common mistake when making the first Android application is that you just start writing your XML views. The XML files will (without problem and very fast) go up to very many lines of code. Although, people just "copy" the behaviour between the different views. Here you can have a solution where you'll just use the style attribute to implement a specific behaviour. For example, consider this piece of code:

values/styles.xml:

<style name="TitleText">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:textSize">18sp</item>
    <item name="android:textColor">#000</item>
    <item name="android:textStyle">bold</item>   
</style>

layout/main.xml:

Now, if you're having, let's say, two TextViews and both of them should have the same behaviour, make them use the TitleText style. Sample code:

<!--- ... -->
<TextView
   android:id="@+id/textview_one"
   style="@style/TitleText" 
/>

<TextView
   android:id="@+id/textview_two" 
   style="@style/TitleText" 
/>
<!--- ... -->

Simple and you don't need to duplicate code. If you really want to look further on these particular subject, please look at Layout Tricks: Creating Reusable UI Components from Android developers website.

  • Use strings

This point is short but I think it is important to mention it. Another mistake that developers might do is to skip the strings.xml and just write UI messages (and attribute names) inside the code (where he will need it). To make your application easier to maintain; just define messages and attributes in the strings.xml file. This will make you win in the long run.

  • Create and use an abstract tool class

When I wrote my first application I was just writing (and duplicating) methods where I needed it. The result? A lot of methods that had the same behaviour between various activities. What I have learned is to make a tool class. For example, let's say you have to make web requests in all of your activities. In that case, skip defining them inside the actual Activity and make a static method for it. Sample code:

public abstract class Tools {

    public static final void sendData(String url, 
              String user, String pass) {
        // URLConnections, HttpClients, etc...
    }

}

Now, you can just use this code below in your Activity that needs to send data towards a server:

Tools.sendData("www.www.www", "user", "pass");

However, you get the point. Use this "pattern" where you need it, it will keep you from messing up your code.

  • Let custom classes define the behaviour where the user needs to interact with your application

This is probably the most useful point. To just define "where the user needs to interact with your application" let's say you have a Menu, which behaviour is very long in terms of lines, why do we keep the Menu's calculations in the same class? Every little item will make your Activity class a painful piece of code longer - your code look like "spaghetti". For example, instead of having something like this:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem item;
    item = menu.findItem(R.id.menu_id_one);
    if(aBooleanVariable) {
        item.setEnabled(true);
    } else {
        item.setEnabled(false);
    }
    // More code...
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem i) {
    // Code, calculations...
    // ...
    // ...
    return super.onOptionsItemSelected(i);
}

redesign it to something like this:

private MyCustomMenuInstance mMenuInstance;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        
    setContentView(R.layout.main);

    mMenuInstance = new MyCustomMenuInstance();
}  

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    mMenuInstance.onPrepareOptionsMenu(menu);
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem i) {
    mMenuInstance.onOptionsItemSelected(i);
    return super.onOptionsItemSelected(i);
}

For example, MyCustomMenuInstance:

public class MyCustomMenuInstance { 

    // Member fields..

    public MyCustomMenuInstance() {
        // Init stuff.
    }

    public void onPrepareOptionsMenu(Menu menu) {
        // Do things..
        // Maybe you want to modify a variable in the Activity 
        // class? Well, pass an instance as an argument and create
        // a method for it in your Activity class.
    }

    public void onOptionsItemSelected(MenuItem i) {
        // Do things..
        // Maybe you want to modify a variable in the Activity 
        // class? Well, pass an instance as an argument and create
        // a method for it in your Activity class.
    }

}

You'll see where this is going. You can apply this to many things, e.g. onClick, onClickListener, onCreateOptionsMenu, the list is long. To learn more "best practices" you can see some sample applications from Google here. Look for how they've implemented things in a nice and correct way.

Last word; keep your code clean, name your variables and methods in a logical manner and especially in a correct way. Always, always understand where you are in your code - that is very important.

What is your experience with Android webapps (limitations, tips, best practices)?

14 votes

Update:

As François mentioned, there are alternatives such as Phone Gap for a more cross-platform approach. It's a very good suggestion indeed. I'm open to any suggestions and I would really appreciate if I can learn from your experience.
Sidenote: A web-only app is not high on my list of options, since I do want it to be on the android market.


I'm about to start porting a facebook app to android and I'm debating whether I should write it as a native app or as a wrapper for a glorified WebView.

How is your experience? What limitations did you face when writing a webapp? Do you have any advice you may want to share? Maybe you think that a native app is the way to go instead?

To set up a famework for the discussion, the app I want to port right now is a simple fb app, in which the server is hosted in Google App Engine (written in Java, if that matters), and all the client code is html, css and javascript (with a good amount of jQuery).

The app is basically a two player, turn-based game, with a bunch of static images that respond to user clicks, and a very simple chat box (independent of fb chat). It can handle several concurrent games for each user (but to different opponents, not the same).

Do you think is a good fit for an Android webapp?

Thank you in advance.

PS1: By all means, I will appreciate any insight, so please do not limit yourself to this specific example app should you want to be broader in your answer.

PS2: Yes, I read the "Best Practices for Web Apps" page from developer.android.com, and I followed the links there, but it does not say much about speed or reliability of the WebView component, specially in terms of user interaction. The question comes after reading the following paragraphs in the WebView description page, which kind of limits the typical scenarios quite a bit:

A common scenario in which using WebView is helpful is when you want to provide information in your application that you might need to update, such as an end-user agreement or a user guide. Within your Android application, you can create an Activity that contains a WebView, then use that to display your document that's hosted online.

Another scenario in which WebView can help is if your application provides data to the user that always requires an Internet connection to retrieve data, such as email. In this case, you might find that it's easier to build a WebView in your Android application that shows a web page with all the user data, rather than performing a network request, then parsing the data and rendering it in an Android layout. Instead, you can design a web page that's tailored for Android devices and then implement a WebView in your Android application that loads the web page.

Hi,

I have implemented two projects that use webview, one is with jqtouch and other with jquery-mobile frameworks.

You are starting like a breeze and go on, but at last when you look at the application it is very far from native user experience. Android browser is much more slower than iphone browser. Hope it will be resolved later, as a result you will have slower response times when you are dealing with css3 heavy applications. While developing in emulator, webview will make you mad as it is sooo slow.

If you want to implement native like elements or fixed tabbar you are working a lot and at last not getting a good solution when you compare your application with native applications, it just sucks.

At last I have decided to learn native development and being a first class citizen. Of course this will take much more time but the result will satisfy me.

I think native development is not the future, sometime later we will write html-css-js applications again and they will work like native code, but it is not likely to be in 2-3 years according to my opinion.

I can suggest you that, try building web apps, if performance does not satisfies you like me, then switch to native development.

In-App Billing Security and Design questions

13 votes

Hi,

I have a few questions connected to Android In-App Billing:

  1. Is it possible to make a purchase from non-Market app? I understand that it would be a vulnerability, but I have no opportunity to find out if it's possible or not.

  2. How can I get purchase state for a particular product? As far as I understand it can be done using RESTORE_TRANSACTIONS request, but it's not recommended to use very often. That's not a theoretical problem. My application allows users to buy content using in-app billing. Content can be downloaded from a server, and server must allow content downloading only if it was purchased. But it can't check if content was purchased or not without using signed response from Android Market.

  3. How can I get price and description of an item from Android Market? Seems that I know the answer and it's "there's no way it can be done", but maybe I'm wrong. It would be very useful to have a possibility of retrieving item's price.

It's very interesting to me how you solved/are going to solve these problems in your apps. Answer to any of these questions will be appreciated.

In order:

1- Nope. The in-app billing process is part of Market. If the app comes from elsewhere, there's no way for Market to verify the origin/authenticity of the application.

2- It's your responsibility to store the purchase state for a particular product. From the doc:

You must set up a database or some other mechanism for storing users' purchase information.

RESTORE_TRANSACTIONS should be reserved for reinstalls or first-time installs on a device.

3- Unfortunately, at this time you're right. File a feature request!

In the meantime, one option is to set up a website with appengine, store listings of all your content & pricing there, and then manually sync prices listed on your appengine server with the updated prices in Market. Then have your Android app pull the data from the AppEngine server. This is much better than hardcoding price values into the app itself, since you don't need to have everyone update the app immediately to see accurate pricing whenever you change something. The only caveat of this method is that if the user is in a different country, in-app billing will display an approximated price in their native currency, and there's no way for you to determine exactly what price will be displayed to them.

Related, One of the Android Developer Advocates is giving a talk on LVL/IAP at IO, called "Evading Pirates and Stopping Vampires using License Verification Library, In-App Billing, and App Engine." - It would definitely be worth your while to watch when they release the session videos on the website.

Android word dictionary security issue

13 votes

Whenever you type a word on an Android phone, the word gets remembered. This is a security issue when using things such as security questions/answers. Is there a way to turn this functionality off? So that, when you type a word, the word isn't stored anywhere.

P.S. I know that you can turn off 'word suggestions', i.e. by using the flag TYPE_TEXT_FLAG_NO_SUGGESTIONS. I've done this, however the words that you use still get stored in the background.

Thanks in advance

EDIT: This happens with custom keyboards such as AnySoftKeyboard, Swype and SwiftKey. Even though these keyboards are configurable to remember and store commonly used words - you want there to be exceptions for things like remembering your answer to security questions.

On Android 2.2+ you can use InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD to achieve the desired functionality on any security field. Despite this flag being available for older versions of Android (from Google API 3+), it seems to have no effect in Android 2.1 (API 7) and below.

It seems like you have answered your own question. Google only added support for what you are trying to do in Android 2.2 and above.

If you need to do this on earlier versions, maybe you could add some code after they exit the field that would go out to the user dictionary and remove the words that were entered in the field. I know its a kludge that doesn't completely close the security hole but its a start.

Benefit of using Parcelable instead of serializing object

12 votes

Hi, all.

As I understand, Bundle and Parcelable belongs to the way android performs serialization in. It is used for example in passing data between activities. But I wonder, if there are any benefits in using Parcelable instead of classic serialization in case of saving state of my business objects to the internal memory for example? Will it be simpler or faster than the classic way? Where should I use classic serialization and where better to use bundles?

Thanks.

From "Pro Android 2"

NOTE: Seeing Parcelable might have triggered the question, why is Android not using the built-in Java serialization mechanism? It turns out that the Android team came to the conclusion that the serialization in Java is far too slow to satisfy Android’s interprocess-communication requirements. So the team built the Parcelable solution. The Parcelable approach requires that you explicitly serialize the members of your class, but in the end, you get a much faster serialization of your objects.

Also realize that Android provides two mechanisms that allow you to pass data to another process. The first is to pass a bundle to an activity using an intent, and the second is to pass a Parcelable to a service. These two mechanisms are not interchangeable and should not be confused. That is, the Parcelable is not meant to be passed to an activity. If you want to start an activity and pass it some data, use a bundle. Parcelable is meant to be used only as part of an AIDL definition.

Why are most UI frameworks single threaded?

10 votes

For example, Java swing and android UI both use a single threaded model where a single UI thread is responsible for updating all the UI. What made the framework designers chose one thread model over the other?

Wouldn't multiple threaded UI model potentially give you more performance albeit at the cost of more complexity? I realize that the latter is a big deal because thread related bugs are nasty but I am wondering if there are any other advantages to single threaded model other than simplicity?

What made the framework designers chose one thread model over the other?

From the horse's mouth:

AWT was initially exposed as a normal multi-threaded Java library. But as the Java team looked at the experience with AWT and with the deadlocks and races that people had encountered, we began to realize that we were making a promise we couldn't keep.

This analysis culminated in one of the design reviews for Swing in 1997, when we reviewed the state of play in AWT, and the overall industry experience, and we accepted the Swing team's recommendation that Swing should support only very limited multi-threading.

(Read the whole article, it explains the decision in great detail and states that the exact same problems and eventual move to a single-threaded model had even occured earlier at Xerox PARC - the place where almost everything we consider bleeding edge modern in CS was invented 30 years ago)

Wouldn't multiple threaded UI model potentially give you more performance albeit at the cost of more complexity?

Absolutely not, because drawing the GUI and processing user actions (which is everything the UI thread needs to do) is not going to be the bottleneck in any sane 2D application.

How do NFC payments work?

10 votes

As far I know NFC tags are quite simple. They contain small amount of data, from several bytes to few kilobytes. NFC / RFID readers receive that data. They can also write back some data to read it later.

I thought that NFC payments are more secure than traditional magnetic cards where whole security is based on one secret number.

So how do NFC payments are implemented? I am especially interested in implementations which we'll have on Android devices. Please describe only high level algorithm.

On a bit lower level NFC works using so-called NDEF protocol (NFC data exchange format). Basically NDEF consisting message->record->payload. Payload where application specific information goes. It depends solely on application which kind of data/encryption will be in those payload.

So there's no standard payment method implementation. Everything will depend on vendors. For example how Google and Visa guys will establish data exchange protocols and implement it.

What certifications are there for Android?

10 votes

Are there any certifications for Android specifically?

I am already doing the SCJP and SCMAD. Is there any similar certification that primarily focuses on Android?

I found this Android Programmer Certification. I am not sure about the validity of the certification, can anyone tell if it is good to have this certification?

There are currently no certification schemes for the Android platform. In my opinion the ultimate 'certification' is to have a couple of apps out on the marketplace, not necessarily successful apps - it is more important that they are robust and good quality.

Android plurals treatment of "zero"

10 votes

If have the following plural ressource in my strings.xml:

   <plurals name="item_shop">
        <item quantity="zero">No item</item>
        <item quantity="one">One item</item>
        <item quantity="other">%d items</item>
   </plurals>   

I'm showing the result to the user using:

textView.setText(getQuantityString(R.plurals.item_shop, quantity, quantity));

It's working well with 1 and above, but if quantity is 0 then I see "0 items". Is "zero" value supported only in Arabic language as the documentation seems to indicate? Or am I missing something?

The Android resource method of internationalisation is quite limited. I have had much better success using the standard java.text.MessageFormat.

Basically, all you have to do is use the standard string resource like this:

<resources>
    <string name="item_shop">{0,choice,0#No items|1#One item|1&lt;{0} items}</string>
</resources>

Then, from the code all you have to do is the following:

String fmt = resources.getText(R.string.item_shop);
textView.setText(MessageFormat.format(fmt, amount));

You can read more about the format strings in the javadocs for MessageFormat

How to access Letter Recognizer API in Android?

10 votes

Hi all,

I am creating a gesture application. In the Gesture class docs http://developer.android.com/reference/android/gesture/Gesture.html) it reads:

"A user-defined gesture can be recognized by a GestureLibrary and a built-in alphabet gesture can be recognized by a LetterRecognizer."

So how do you use the LetterRecognizer and where is the docs on it? There's no API for that in the docs, I've also searched android's code itself, and besides the same comment above in the code there's nothing.

I've implemented a letter recognizer manually by drawing the ABC letters to a gesture raw file and using the regular mLibrary.recognize(gesture) API, but the success rate is not very high, not even close to Google's gesture search app.

Any help on this matter would be appreciated. Thanks

*EDIT: Letter Recognizer is a future release. It is not yet available

I would look at the code on this page:

http://www.anddev.org/gesture_recognizer_and_character_recognition-t2998.html

He says the source code for his character recognizer is in the SVN, too. You might find some helpful tidbits.

Javascript console.log() on HTC Android devices and adb logcat

9 votes

I am developing the application in HTML which is calling the console.log() from Javascript to provide me logs during the development about what happens in the web page code.

Unfortunately when I use the adb logcat command to check logs I can see output from all other applications, but not the output from my JavaScript code. I can see even the log from web browser that the page is loaded, but not console.log() output from my JavaScript code executed in the web browser.

According to information on this page (http://developer.android.com/guide/webapps/debugging.html) it should work.

I am testing on HTC WildFire and HTC Desire HD.

I have been using three different HTC phones, almost exclusively, and have never had this issue. Here are a few things to check:

  1. Make sure USB debugging is enabled.
  2. Make sure your Webview has a WebChromeClient set. The browser used in Webview does not implement console.log().
  3. It should be easy to see the output of adb logcat, but to make it easier, filter the output.

Turn on USB debugging:

  1. Disconnect your device from your computer.
  2. Go to Settings -> Applications -> Development -> Select "Enable USB Debugging"
  3. Plugin to computer. (Make sure you have the correct drivers installed to use ADB - more info here: http://developer.android.com/guide/developing/device.html)

Set a WebChromeClient that overrides onConsoleMessage():

//Set the output prefix so you can filter adb logcat results later
public static final String TAG = "Your-Application-Name";

myWebView = (WebView) findViewById(R.id.webview);

//Not going to have much luck running JS without this:
myWebView.getSettings().setJavaScriptEnabled(true);

//Override onConsoleMessage() to output to the Log.
myWebView.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onConsoleMessage(ConsoleMessage cm) {
        Log.d(TAG, cm.message() + " -- From line "
        + cm.lineNumber() + " of "
        + cm.sourceId() );
        return true;
    }
});

More info on onConsoleMessage() here: http://developer.android.com/reference/android/webkit/WebChromeClient.html#onConsoleMessage(java.lang.String, int, java.lang.String)

More info on debugging in general here: http://developer.android.com/guide/webapps/debugging.html

Filter the output of adb logcat:

adb logcat tag-name:log-level *:S

tag-name matches the string specified in Log.x log-level matches the log level you indicated when calling Log.x <---

Example relating to code above:

adb logcat Your-Application-Name:D *:S

This will show all d level logs for the matching tag, Your-Application-Name, and silence everything else.

More info on adb filtering here: http://developer.android.com/guide/developing/tools/adb.html#logcat

Hope it helps! I know it was a bit of summarizing of the other answers, but, the fact is, it takes all of the steps to make it work. :)

Why is this shell script calling itself as python script?

9 votes

Obviously this shell script is calling itself as a Python script:

#!/bin/sh
## repo default configuration
##
REPO_URL='git://android.git.kernel.org/tools/repo.git'
REPO_REV='stable'

magic='--calling-python-from-/bin/sh--'
"""exec" python -E "$0" "$@" """#$magic"
if __name__ == '__main__':
  import sys
  if sys.argv[-1] == '#%s' % magic:
    del sys.argv[-1]
del magic
:
:

(Whole script: http://android.git.kernel.org/repo)

Can anyone explain

  • the purpose of calling it this way?
    Why not having #!/usr/bin/env python in the first line so it gets interpreted as Python script from the beginning?

  • the purpose of adding that magic last command line argument, that is removed afterwards in the beginning of the Python code?

Your first question: this is done to fix unix systems (or emulations thereof) that do not handle the #! correctly or at all. The high art is to make a script that is coreect in shell as well as in the other language. For perl, one often sees something like:

exec "/usr/bin/perl"
   if 0;

The exec is interpreted and executed by the shell, but the perl interpreter sees a conditional statetment (.... if ...) and does nothing because the condition is false.

Haskell interpreter on Android?

8 votes

Is there a Haskell interpreter (with standard libraries) that can be installed on Android?

So that someone with an Android device can do some Haskell exercises on an Android device: write and run some example code in Haskell.

Taking a note from imz, all you need is

  • ConnectBot or similar
  • A remote machine with
    • Vim, Emacs, or similar
    • runghc / ghci / hugs / yourfavoritehaskellinterpreterorcompiler

It's not as solid as a dedicated app or scripting layer would be, but honestly, for your use cases, it would provide almost exactly the same functionality as those options (if not more). And it would be just as "mobile" as a website (depends only on the uptime of the host and the connectivity of the client).

Launching an Android Emulator from Python-Django

4 votes
def start_test(request):
    os.system('echo Starting emulator...')
    os.system('./android-sdk-linux_x86/tools/emulator -avd testavd &')
    return HttpResponse("OK")

Here is the barebones code of what I am trying to do.
When this code gets executed, the server stops responding while running the emulator. Any help appreciated.
I am using the django development server. Here is the server output:

Django version 1.1.1, using settings 'Cloust.settings'
Development server is running at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
Starting emulator...
[21/Apr/2011 02:00:06] "GET /start_test/a.apk/ HTTP/1.1" 200 5
emulator: warning: opening audio output failed

emulator: emulator window was out of view and was recentred

I still haven't gotten around to properly solving this problem, but using subprocess.Popen allows me to perform commands on the emulator afterwards:

print 'Starting emulator...'
subprocess.Popen(['emulator', '-avd', 'testavd'])
os.system('adb wait-for-device')
os.system('Perform whatever adb commands you need')

It's worth noting that this is using the django development server, which has been started using sudo, so obviously this is far from ideal.