Posts tagged api

Rapid Mobile Application Prototyping with PhoneGap

There is no doubt that carving out a mobile presence is a priority for many companies offering any type of product or service, or for start ups looking to gain rapid exposure. The Apple App Store has over 100,000 apps on it, and the Android platform is gaining ground. Those are just the cool kids – let’s not forget the grandfather of mobile technology, Blackberry. Others in the class include Palm, Symbian and of course, Windows.

Multiple Platforms
With so many platforms available there is a risk of losing focus on developing and producing applications as resources are expended on supporting multiple platforms – a necessary evil as each presents different development environments and eccentricities.
This is why PhoneGap really stands out at the moment as four [1] of the aforementioned platforms share a common factor – a WebKit-based browser. This doesn’t include BlackBerry’s announcement [2] of their new WebKit based browser to come in late 2010, which takes us to five out of the six platforms.

Enter PhoneGap
Where does PhoneGap sit in this picture? Well, it jumps off the canvas and sits in your lap! PhoneGap allows you to develop applications using HTML, CSS and JavaScript and provides a JavaScript API which enables you to interact with a device’s native functionality [3]. In addition to this simple application architecture, PhoneGap comes with build scripts/plugins (PhoneGap extension for XCode) which bundle up your pages into a deployable application.
The packaging and deployment to device for iPhone, Android and Palm was trivial; I can only speculate that the remaining platforms are equally easy to deploy. In light of recent Apple ‘crackdowns’, as of October 7th [4], 2009, it is worth noting that PhoneGap (version 0.8.0 and higher) is Apple approved.

The JavaScript advantage?
Anyone who has used a JavaScript library, Prototype, jQuery, MooTools etc, knows how powerful they can be. Anyone who has not used them can easily pick up JavaScript basics. The guys over at PhoneGap recommend using XUIJS[5] with PhoneGap as it does not contain a lot of cross-browser compatibility overhead and weighs in at < 10kb compared with jQuery at 24kb – although for simple functionality you may want to avoid using a extra library at all.
Due to the fact that we are ultimately aiming to work inside one browser implementation (WebKit), we are not held hostage by the browser compatibility issues that have haunted JavaScript for so many years. That’s not to say that fragmentation in the mobile world is not an issue [6].

Now, I am not going to try to argue that these HTML/JavaScript apps offer greater performance or a better user experience over their native counterparts. However, I will say that PhoneGap will allow the rapid development of an application for multiple platforms, using a single code base [7]. This is ideal for prototyping or for apps that will have a limited life span and do not warrant the time and investment of producing native apps.

Considering all of this in combination with

Speech Input API for Android

Google Android Graphics API Demos on the HTC Touch HD

stahovat.okamzite.eu Google Android Graphics API Demos on the HTC Touch HD

http://www.youtube.com/v/0M29HDWJksY?f=videos&app=youtube_gdata

Android 2D ( A Simple Example )

It has been a long time I wanted to go through Android 2D capabilities and see how that works. and after a little bit of reading and researching about the topic, I developed a simple TicTacToe game which I’m gonna share it with you in this article.
The primary purpose of this example is to dig up some basic Android 2D features and get familiar with some game programming principles. Although TicTacToe is not really an interactive game, I think its simplicity will help us to be focused on what matters most which is actually how to do things in Android rather than how to design and develop an efficient game algorithm for a particular game. (I’m gonna use the same technique that has been used in LunarLandar application, which by the way is a pretty good example in this area).
first of all let’s have a look at how our application will be looking like:



Despite the fact that TicTacToe is a pretty easy game to develop, Graphic wise I mean, and can be simply done by extending View Class, I have actually used ‘SurfaceView’, since apparently it’s a better option for developing interactive games in Android. the most important point about SurfaceView class is that it uses two buffers, a drawing buffer and a displaying buffer, you are not allowed to draw directly on displaying buffer and if you need to draw something you will have to get the drawing buffer , fill it and post it as display buffer. as API documentation has mentioned there is no guarantee that anything gets preserved in drawing buffer and as a result we always need to draw anything we want to be shown without taking any presumption that something is already there from last drawing operation.
OK… now that we learned some basic facts about how SurfaceView works, let’s have a look at my code and see what we have got there :

public class TicTacToeView extends SurfaceView implements SurfaceHolder.Callback, OnTouchListener {

  .  .  .

        public TicTacToeView(Context context) {            super(context);            getHolder().addCallback(this);        }

        public TicTacToeView(Context context,TicTacToe internalState) {            this(context);            this.tictactoe = internalState;        }

        .        .        .

    class MainThread extends Thread {

        private SurfaceHolder surfaceHolder;        private boolean runFlag = false;        boolean firstTime = true;

        public MainThread(SurfaceHolder surfaceHolder) {            this.surfaceHolder = surfaceHolder;        }

        public void setRunning(boolean run) {            this.runFlag = run;        }

        @Override        public void run() {            Canvas c;

            while (this.runFlag) {

             if(firstTime){                     drawLines();                     firstTime = false;                     continue;                 }

                c = null;                try {

                    c = this.surfaceHolder.lockCanvas(null);                    synchronized (this.surfaceHolder) {                                           doDraw(c);                        updateScores(c);                    }                } finally {

                    if (c != null) {                        this.surfaceHolder.unlockCanvasAndPost(c);

                    }                }            }        }

        .        .        .

    }

   .   .   .}

The first thing we’re gonna need in any game is a Game Thread, The idea here is to constantly call a series of methods which are responsible to update some states and draw something based on those states. as I said before when you are dealing with SurfaceView you need to draw into the draw buffer and then post it on the surface, It can be done by calling lockCanvas() and unlockCanvasAndPost() methods of SurfaceHolder class, you can get the associated SurfaceHolder instance of your SurfaceView by calling getHolder() method. as you can see in the above code I have implemented the SurfaceHolder.Callback interface; this interface provides 3 callback methods for monitoring the life-cycle of the SurfaceView, here is my implementation of these methods:

       .       .       .

       @Override        public void surfaceCreated(SurfaceHolder holder) {

            _thread = new MainThread(getHolder()); 

           if(tictactoe == null)          this.tictactoe = new TicTacToe(new TicTacToeHandler(),false);           else           _thread.firstTime = false;

         Resources resources = getContext().getResources(); 

            this.background = BitmapFactory.decodeResource(resources, R.drawable.background);            this.X_Player   = BitmapFactory.decodeResource(resources, R.drawable.x_pic);            this.O_Player   = BitmapFactory.decodeResource(resources, R.drawable.o_pic);

            Rect rect = holder.getSurfaceFrame();            this.gameTable_height = rect.height()-56;            this.gameTable_sY     = 0;            this.gameTable_width  = rect.width();            this.scoreBox_Height  = 50;            this.scoreBox_Width   = rect.width();            this.scoreBox_sY      = rect.height()-this.scoreBox_Height;            this.squares = new Rect[9];

            final int square_Width  = (int)(gameTable_width-(TABLE_BORDER*4))/3;            final int square_Height = (int)(gameTable_height-(TABLE_BORDER*4))/3; 

            for(int i=0;i<9;i++){              int row    = i%3;              int column = i/3;              int left = ((row+1)*TABLE_BORDER)+(square_Width*row);              int top  = ((column+1)*TABLE_BORDER)+(square_Height*column);              this.squares[i] = new Rect(left,top,left+square_Width,top+square_Height); 

            }

            this.tablePaint.setStyle(Style.STROKE);

            this.tablePaint.setShader(new LinearGradient(0, 0, this.gameTable_height,                                                    this.gameTable_width,                                                     0xFF000000,                                                     0xFF343434,                                                     TileMode.MIRROR));            this.tablePaint.setStrokeWidth(TABLE_BORDER);            this.tablePaint.setAlpha(0xCC);

            this.boxPaint.setStyle(Style.STROKE);         this.boxPaint.setStrokeWidth(BOX_BORDER);         this.boxPaint.setColor(0xFFA90000);

         this.textPaint.setColor(0xFF000000);         this.textPaint.setTextAlign(Align.CENTER);         this.textPaint.setTextSize(14);         this.textPaint.setTypeface(Typeface.createFromAsset(getContext().getResources().getAssets(),"HARLOWSI.TTF"));

         this.contentPaint.setAlpha(0xDF);

            _thread.setRunning(true);            _thread.start();            setOnTouchListener(this);

        }

        @Override        public void surfaceDestroyed(SurfaceHolder holder) {

            boolean retry = true;            _thread.setRunning(false);            while (retry) {                try {                    _thread.join();                    retry = false;                } catch (InterruptedException e) {

                }            }        }

        @Override        public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {        }        .        .        .

in surfaceCreated() method I have initialized some variables and objects such as an instance of TicTacToe class (which will actually take care of game's logic and rules), background Image , cross and circle images and Paint objects that all will be used later to draw the game, here is also a good place to create and start our main thread. then we will kill the main thread in surfaceDestroyed() method to make sure no one's gonna make an attempt to draw anything on the surface after it has been destroyed.
now that we have got anything initialized and the main thread running let's see what is happening in each loop of our thread, as you saw in the first chunk of code above we are actually calling 2 methods each time, doDraw() and updateScores() :

     .     .     .

       public void doDraw(Canvas canvas) {

         canvas.drawBitmap(this.background, 0, 0, null);         drawTable(canvas);

         if(this.draw && Xs[0] == Xs[1] && Ys[0] == Ys[1]){                CheckContent();           }         drawContent(canvas);

         }

        /////////        private void updateScores(Canvas canvas){

         final int halfBorder = (int)BOX_BORDER/2;         final Paint paint = textPaint;

         Rect rect = new Rect(halfBorder,                        this.scoreBox_sY-halfBorder,                        this.scoreBox_Width-halfBorder,                        (this.scoreBox_sY-halfBorder)+this.scoreBox_Height);         RectF rectf = new RectF(rect);

         canvas.drawRoundRect(rectf, 15, 15, this.boxPaint);

         canvas.drawText("Your Score : "+this.tictactoe.getYourScore(), 65,this.scoreBox_sY+25,paint);         canvas.drawText("Computer's Score : "+this.tictactoe.getOpponentScore(), 15+(this.scoreBox_Width/3)*2,this.scoreBox_sY+25,paint);

        }  

      private void drawTable(Canvas canvas){

       final Paint paint = this.tablePaint;       final float border = TABLE_BORDER;

       final int cellHeight = (int)(this.gameTable_height-(2*border))/3;       final int cellWidth  = (int)(this.gameTable_width-(2*border))/3;

       final float table_eX = this.gameTable_width-border;       final float table_eY = this.gameTable_height-border;

       canvas.drawLine(this.gameTable_sY+border, cellHeight+border, table_eX, cellHeight+border, paint);       canvas.drawLine(this.gameTable_sY+border, (cellHeight*2)+border, table_eX, (cellHeight*2)+border, paint);

       canvas.drawLine(cellWidth+border, border, cellWidth+border, table_eY, paint);       canvas.drawLine((cellWidth*2)+border, border, (cellWidth*2)+border, table_eY, paint);

       paint.setPathEffect(new CornerPathEffect(20));       canvas.drawRect(border/2, border/2, this.gameTable_width-(border/2),                                      this.gameTable_height-(border/2),                                      paint);

       paint.setPathEffect(null);      }

      private void CheckContent(){

       for(int i=0;i<9;i++){        if(this.squares[i].contains(Xs[1], Ys[1])){         this.tictactoe.move_Request(i);

         this.draw = false;                  return;          }          }      }

      private void drawContent(Canvas canvas){

      for(int i=0;i<9;i++){        int squareContent = this.tictactoe.getContent(i);          if(squareContent == TicTacToe.X_PLAYER)         canvas.drawBitmap(this.X_Player,null,this.squares[i], this.contentPaint);         else if(squareContent == TicTacToe.O_PLAYER)         canvas.drawBitmap(this.O_Player,null,this.squares[i], this.contentPaint);   

      }        }

       @Override public boolean onTouch(View v, MotionEvent event) {

    if(event.getAction() == MotionEvent.ACTION_DOWN){    this.Xs[0] = (int)event.getX();   this.Ys[0] = (int)event.getY();    }    else if(event.getAction() == MotionEvent.ACTION_UP){    this.Xs[1] = (int)event.getX();    this.Ys[1] = (int)event.getY();

    this.draw = true;   }

  return true; }        .        .        .

The Last thing I would like to handle is the ability to keep the state of the game when user flips the phone and goes to landscape mode or vice versa, so we are gonna have to save current state of the game just before application get killed and then retrieve that state later when the activity get started again which mean our activity class will be something like this:

public class TicTacToeActivity extends Activity{

  private TicTacToeView view;

    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE);

        TicTacToe oldTTT = (TicTacToe)getLastNonConfigurationInstance();        if(oldTTT != null)         this.view = new TicTacToeView(this, oldTTT);        else         this.view = new TicTacToeView(this);

        setContentView(this.view);    }

    @Override    public Object onRetainNonConfigurationInstance(){     return this.view.getInternalState();    }

}

getInternalState() method returns the associated TicTacToe object of the TicTacToeView, as I said before TicTacToe class is just a simple class that holds the game matrix and players' scores and actually that's all we need to save and retrieve each time the configuration gets changed in this example.
I also though it would be interesting to start the game with some sort of animation so I wrote a piece of code to have the game table being drawn when you start the application, something like this I mean :



and here is the code that generates this animation:

      .      .      .

    public void run(){ final int length = lines.length;   for(int i=0;i

I'm not sure if it's the best way to do this but it works just like i want it to work ;) . (since just calling lockCanvas() and unlockCanvasAndPost() alone takes something around 200ms on my emulator - which is of course ridiculous but i have no idea why! - I didn't need to add any delay but on real device it will probably be needed to have some delay).

Automated test in Android by Sikuli

There is a very friendly and pretty cool project called ‘Sikuli‘ and the authors are from Taiwan too. What is Sikuli? I copy these texts from its website. Sikuli is a visual technology to search and automate graphical user interfaces (GUI) using images (screenshots). The first release of Sikuli contains Sikuli Script, a visual scripting API for Jython, and Sikuli IDE, an integrated development environment for writing visual scripts with screenshots easily. Sikuli Script automates anything you see on the screen without internal API’s support. You can programmatically control a web page, a desktop application running on Windows/Linux/Mac OS X, or even an iphone application running in an emulator.

How I use Sikuli for Android? Since we can catch things from screenshots, it means we can run Android emulator in my Ubuntu machine. Furthermore, I can run a vnc server in Android device, then run a vnc viewer in Ubuntu. Therefore, I can see Android HOME screen in my Desktop. What it can do for me? ha, it can run automated tests and then we don’t need SQA to verify phone basic functionalities. Like detect GSM signal, dial out a phone call, enable Bluetooth, connect to WiFi hotspot….etc.

Launch Sikuli IDE editor in Ubuntu

wget http://sikuli.org/dl/Sikuli-IDE-linux-20100104.zipunzip Sikuli-IDE-linux-20100104.zipsh Sikuli-IDE/sikuli-ide.sh

Launch Android in Ubuntu

There is another tool “androidscreencast” I am using for this automated test. It can allow me to control my Android Dev phone remotely. We can have keyboard and mouse input! This is very important for Sikuli scripts, coz I can say “Click” something or “type” something. :)

wget http://androidscreencast.googlecode.com/svn/trunk/AndroidScreencast/dist/androidscreencast.jnlpjavaws androidscreencast.jnlp

Let’s write some examples! Please check these draft videos!

Installing Android problem (failed to rename directory)

Recently I started development on Android platform. When I first installed Android sdk 2.1 through SVD Manager, I encounter a very strange error below. The major problem with this error is that it occurs after taking longer time of downloading the component. For my internet connection it took about 23 min which it requires for downloading the component. After downloading the component it renames the tool folder which causes this error to occur :

Downloading Android SDK Tools, revision 4
Installing Android SDK Tools, revision 4
Failed to rename directory E:android-sdk_r3-windowstools to E:android-sdk_r3-windowstempToolPackage.old01
-= Warning ! =-
A folder failed to be renamed or moved. On Windows this typically means that a program is using that folder (for example Windows Explorer.) Please close all running programs that may be locking the directory ‘E:android-sdk_r3-windowstools’ and try again.
Skipping ‘SDK Platform Android 2.1, API 7, revision 1′; it depends on ‘Android SDK Tools, revision 4′ which was not installed.
Downloading SDK Platform Android 2.1, API 7, revision 1

First I thought that I mistakenly opened tool folder in some other application so I started SVD manager again which took me again 23 min and after that I got the error again. Very frustrating. Since I was using windows 7 so I thing there might be some problem with windows 7. I started googling on this problem and then reviewing few ppls work around I came to know that this is typical problem with Antivirus. So when I turned off my Antivirus the error resolved. Hope my this post would definitly helps to novice you are just entering in the realm of the android development.

2 Really Good Twitter Apps this week

On Saturday I downloaded Xeeku Tweets thanks to @dandroidos And I thought it was love at first site. It’s a very very strong app look for it in the market as Xeeku Tweet.

I didn’t like that it said I was posting from generic API but hey thats on them they should fix the signature to show that it’s coming from Xeeku Tweets. That’s no biggie.

The GUI isn’t as pretty as seesmic or my favorite twitter gui which is Tweeteev but its functionality is actually in some cases better than other programs.

The Pro version (for some rason only available on Droid) is the only way to get multi-account support.

One Really Big Plus is it follows the conversatin on everything without having to click through an extra time like seesmic, it just shows the whole conversation if you pop open the tweet. A++ There.

My personal downsides with Xeeku:

I couldn’t paste on the go I tried to paste a link from href.to and no dice, no paste option into a tweet.

Also the nav bar at the bottom disappears when you’re anywhere but timeline so when I went into @messages I had to use the android back button to get back to timeline to go anywhere else

Otherwise though this is a SOLID tie for number 2.

The other really great twitter app I am testing now is Tweetcaster by Handmark the GUI is Beautiful it has multi account support. The only thing I really don’t like is that it has Native Retweet so if you want to retweet you have to retweet the whole message sometimes I like to retweet a question with my answer in case the original poster doesn’t have a way to see the conversation. This got to be a pain.

Other than that though its reall great one thing I really like about it is it shows you the link at the bottom if there is a link in the twit this is really really useful. Haven’t tried the paste thing and I’ve only had it about a day so look for more but these two are definitely way better than Twidroid.

I’d say my number 1 is still seesmic but tied at number 2 are Xeeku and Tweetcaster. Look for more though because really twitter apps are what i get the most questions about. I did get uno the other day and it was almost as fun as whipping my friends butts in the third grade.

First Six Months of Palm’s App Catalog… How’s Palm Doing?

The first 1000 webOS apps
It’s been six months since the birth of Palm’s resurgence, and here at Totally Palmed, the numbers are in.

RemoteViews as hypertext document

In the previous blog entry I tried to demonstrate, how a web programming construct, the feed can be implemented using LiveFolders. In this entry, I would like to highlight another relatively obscure feature of the Android API, the RemoteViews widget and argue that RemoteViews are similar in nature to another web programming construct, the hypertext document itself.

RemoteViews is the key mechanism behind the AppWidget feature of the Android platform. There are many good introductions to AppWidgets (like this or this) so I will be short. AppWidget is a representation of an Android application on the home screen. The application can decide, what representative information it publishes on the home screen. As the screen estate is limited, the representation is obviously condensed, e.g. an application executing a long-running task can publish the progress indicator as home screen widget. The technical problem is that it is not evident, how to embed functionality (even condensed functionality) from another running application into the Launcher, the default home screen provider. If Launcher delegated the refreshing/redrawing of the views embedded from another application to that application, then malfunction of that application could disrupt the Launcher itself – something to be definitely avoided as the home screen is the last refuge of the users if something goes wrong with apps. Different platforms apply similar strategy. The idea is that the home screen application does not invoke other executables when it draws the home screen, it rather uses some sort of description of the widget UI in data format and displays that. For example that is the reason Symbian forces the programmer to implement widgets as HTML/JavaScript applications and that is the reason Android decoupled the applications from the Launcher view structure

The workhorse behind Android AppWidgets is the RemoteViews widget. RemoteViews is a parcelable data structure (so it can be sent through Android IPC) that captures an entire view structure. The creator of the RemoteViews sets up this data structure, by specifying the base layout and setting field values. This has no effect on the UI and therefore background components like services, broadcast event handlers, etc. can also do it. In fact, AppWidgets are broadcast event receivers, they process broadcasts from Launcher and respond with RemoteViews. When the RemoteViews data structure is received and deserialized, it can be applied to any ViewGroup of the UI and can therefore appear on the UI of another application. From this point of view, it works just like a hypertext document except that RemoteViews describes Android views and not general web controls.

RemoteViews is a powerful construct that can be easily used outside of the context of AppWidgets. I present now a simple Activity and a Service where the Service provides an entire formatted View (and not just the data) that can be displayed easily by the Activity. Even though this is against the Big Book of service-oriented architectures (services should provide raw data and the consumers should care about formatting), there are lot of use cases for this construct. For example the output data of the service may not be so easy to display (e.g. in case of a map application) or you would like to tie the output of the service with advertisement, logo or link to your main application (a PendingIntent in Android parlance). In this case your Service (broadcast receiver, etc.) may just return the View structure you would like the client application to display. In the web world, web widgets are formatted mini webpages to be embedded into other web pages, hence the similarity of this web technology with RemoteViews.

Click here to download the example program.

There are three points to note here.

  • Check ITimeViewService.aidl under the src/aexp/remoteview directory and see how the remote method returns a RemoteViews instance.
  • Check TimeViewService.java and see how the RemoteView is constructed and updated. To make the point of returning formatted views as opposed to raw data, I added two formatted TextViews and a ProgressBar embedded into two LinearLayouts to the view structure returned by the service.
  • Check RemoteView.java and see how the RemoteView is applied to the view structure of that Activity. Everything under the “Get view data” button comes from the service when the RemoteViews is inflated into the view structure of the Activity.


RemoteViews has disadvantages, however. It cannot serialize any Views, e.g. it cannot serialize an EditText view. I am aware of only this article about the restrictions of views the RemoteViews can serialize/deserialize.

Google and Spring Design Alliance Gives Alex eReader Direct Access to One Million Google Books on Android Platform

Browse and Download Google Books from Google Bookstore Directly to Alex eReader


Spring Design, developers of the dual screen multimedia Alex eReader, have entered into an agreement with Google that gives Alex users access to more than one million Google Books online or downloaded using Alex’s integrated Android Web browser and search applications.
Alex is the first and only open Google Android-based eReader platform with full featured Internet browsing, WiFi connectivity, audio and video playback and image viewing in popular formats, and the ability to run a growing number of Google Android applications. With the Alex touch screen browser, users can access the Internet to search and read eBooks directly on Alex’s eReader’s 6” EPD (Electronic Paper Display) screen while browsing in full color on the Internet simultaneously. Users can click on hyperlinks within online books that lead to relevant web-based information or multimedia content found online to enrich their reading experience. EPUB digital books can be searched and downloaded using Google API applications provided by Alex’s eReader.

“We are pleased to work with Spring Design and the Alex, which is an exciting new reading device, that combined with a wealth of free public domain books from Google, provides great value to eReaders,” said Google Product Manager, Brandon Badger. “Our relationship with Spring Design is helping to expand the number of ways people access eBooks and search for information online, whether for business, education or entertainment.”
“Our agreement and strategic alliance with Google opens the doors to more readers around the world,” said Dr. Priscilla Lu, CEO of Spring Design. “We are excited to be part of Google’s initiative to digitize and deliver the world’s books and look forward to the markets and opportunities these efforts will open up for readers as well as independent authors.”

Related articles by Zemanta

Reblog this post [with Zemanta]