Total Pageviews

Friday 26 October 2012

用App Inventor 进行android的编程

Drag and drop your way to Android programming.
MIT App Inventor, re-released as a beta service (as of March 5, 2012) by the MIT Center for Mobile Learning after taking over the project from Google, is a visual programming language for developing applications for the Android mobile computing platform. It is based on the concept of blocks, and applications are designed by fitting together blocks of code snippets. This may sound like a very childish way of programming, especially for seasoned readers of Linux Journal. But then again, App Inventor will tickle the child programmer in you and make you chuckle at the ease with which you can develop applications for your Android device. In this article, I describe how to use the camera on the Android device, develop e-mail and text-messaging-based applications and also show how to use location sensors to retrieve your current geographical location. Let's get started.

Getting Started

App Inventor has minimum setup requirements and is completely browser-based. You need a working Java installation on your system, as it uses Java Web Start for its functioning. Point your browser to http://appinventor.mit.edu, and once you sign in with your Google account, you should see a screen as shown in Figure 1. This is called the Projects Page where you can see your existing projects and create new ones.
Figure 1. App Inventor's Projects Page
Now, let's develop and deploy an Android application using App Inventor and in the process learn the basic development-deployment cycle. Create a New Project using the New Project button, and enter a name for your project, say "Project1". Now you should see the Designer window for your project. The Designer window is composed of four sub-components. The Palette on the leftmost side of the window is the placeholder for all the available components for your project. The Viewer is where the application will be designed by placing together various components (this is where you design the user interface for your application). The Components show the currently used components in your project, and the Properties column is where you assign the properties of the components.
First, let me briefly explain the notion of components. An App Inventor project is made up of building blocks called components, such as a text label to display text, a text box to take user inputs, a camera component to click pictures and so on. Currently, you will see a few categories of components—basic components, such as those for user input and display of text to more specialized components, such as those for displaying media and animations, and components acting as an interface to the device sensors. A complete reference for all the components is available at http://appinventor.mit.edu/learn/reference/index.html. Components have associated behavior, methods and properties. Some of the properties can be set; whereas others can be only read.
In this first project, let's use the following components: Camera, Button and Image. The code usually shows it better, but briefly here is what you're going to do: clicking the button starts the camera on your device, which you use to click a picture, which then is displayed using the Image component. Here are the steps:
  1. Drag a Camera component from the palette to the Viewer. It should show up under Non-visible components below the Viewer. By default, it will be named as Camera1, which you can, of course, change to something else.
  2. Drag a Button to the Viewer, and from the Properties, change its Text to "Click".
  3. Drag an Image component onto the Viewer.
  4. You can play around with the Screen properties to set things like title, background color and orientation. For the purpose of this project, set the Title to "Click!".
Figure 2. User Interface for Project1
That completes the design of the user interface (Figure 2). Next, let's program the components using Blocks.
Open the Blocks Editor, which should start downloading the JAR file for the editor. It will ask you for the location of the App Inventor setup commands if you have not installed them in the standard location under /usr/google. The Blocks Editor for the current project will look like Figure 3. Going back to the description for this project, the goal is to activate the device camera when the button is clicked. This is done with the code block "When Button1.click", which you dragged from the Blocks pane on the left. When the button is clicked, you want the device's camera to be activated, so drag the "call Camera1.TakePicture" block inside the previous block. Once the picture is taken, you will want it to be displayed using the Image component. So, insert the block "when Camera1.AfterPicture" into the editor, and then set the "Image1.Picture" to the location of the saved image.
Figure 3. Blocks Editor for Project1
Now that you have designed the user interface and programmed the application's logic, you're ready to test it. Go back to the Designer window, and on the right, click on Package for Phone→Download to this Computer. That should initiate the download of the Android package (.apk file) for your project. Now, transfer this file to your Android device, and install it. Then, try it out.

A Peek under the Hood

Now you have designed and deployed your first Android application, and you have used components (the camera component and the image components), assigned them behavior and set properties. If you are familiar with the idea of event-driven programming, you already will have realized that App Inventor is an event-driven programming framework. The event can be the user clicking a button or the reception of a text message. For example, when the button is clicked, an event is said to have occurred, and in response to this event, the camera is activated. Again, when the camera finishes capturing a picture and saving it, the response code uses the image location to display it using an image component.
Earlier, I mentioned that components have associated behavior, methods and properties. You can find these for a component by clicking the component in the Blocks Editor. For example, Figure 4 shows the method available for the Camera component (Camera1.TakePicture) and the behavior (Camera1.AfterPicture).
Figure 4. Blocks Available for the Camera Component
Besides the blocks associated with components, more fundamental programming blocks are available: Math blocks, Logic blocks, Control blocks and others. (I'll demonstrate using a few of these in one of the projects later in this article.)
Now that you have a basic idea of developing applications using App Inventor, let's look under the hood a bit, starting from the source. Download the source code for "Project1" by going to the Projects Page and selecting Project1 and clicking on More Actions→Download Source. That should start downloading the sources in a zip file. When you unzip the file, you will have two directories: src and youngandroidproject. Under the src directory, you will have a subdirectory called appinventor, which houses the subdirectories, and then ai_droidery/Project1 (note that "droidery" is my Google user name). In this directory, you will see the source files Screen1.blk, Screen1.scm and Screen1.yail. Screen1.blk is an XML-based representation of the visual blocks that was created earlier; Screen1.yail is an intermediate language based on the Scheme language used by App Inventor, which is then fed to Kawa to create the Android package for installation on Android devices. The Screen1.scm file is a JSON representation of the components used in the project with details about the components, such as the version information. If you are keen to understand how App Inventor really works, you also may want to check out App Inventor's source code (see Resources).
Next, let's move on to becoming familiar with sensors and some of the other components available in App Inventor.


Sensing the World Using Sensors

Sensors, true to their names, are the eyes and ears of your Android device. They allow your device to sense the world around it. For example, the location sensor on your device keeps track of your current location information using your mobile and Wi-Fi signal information and GPS data. Other sensors on your Android device include proximity sensors and motion sensors. In this section, let's use the location sensor on your Android device to write two simple applications that can be used on their own or as a starting point for something more useful and customized. In the process, you'll learn to make use of a couple more App Inventor components.

E-mail Your Current Location

Consider a not-so-fictional scenario when you might want to tell your friend exactly where you are at the moment so that she can drive down to meet you. Or, you simply may be lost. Either way, the Location Sensor can help. Let's call this project "LocationOnClickEmail". The user interface for this project looks like the one shown in Figure 5. Besides the basic components, such as text labels and buttons, add the LocationSensor component (found under the Sensors category) and an ActivityStarter component (found under the Other Stuff category). The ActivityStarter component, which has been named "MailAppStarter" will be used to start the e-mail application on the Android device. For details on the ActivityStarter Component, refer to http://appinventor.mit.edu/learn/reference/other/activitystarter.html.
Figure 5. User Interface for the LocationOnClickEmail Project
Now you need to add the project logic using the Blocks Editor as before. Figure 6 shows the final state of the Blocks Editor for this project.
Figure 6. Final Blocks for the LocationOnClickEmail Project
The application logic can be divided into two steps—obtaining the location using the Location Sensor when the Get Location button is clicked. This is done in the "when GetLocationButton.Click" code block. When this button is clicked, the Location Sensor is enabled. Once the Location Sensor has been able to obtain the location information, it invokes the "when LocationSensor1.LocationChanged" method where the text labels are updated with the location data. Next, when the Email Location button is clicked, the MailAppStarter component's DataUri property is set to start the mailing application. Here, the recipient is set to "droidery@gmail.com", the subject to "My Location" and the body of the message to the obtained address. The recipient and subject can be changed in the mailer application on the device.
That completes the current project. For more details on using the Location Sensor and the App Starter components, refer to the App Inventor Reference (see Resources).

Text-Messaging-based Location Sensor Application

In the last application, you initiated the location sending event. What if you want to design an application that will run as a service, such that when it receives a request via text message, it sends your current location to the sender? Even with privacy being such a sensitive issue in today's connected world, such an application can be useful if you want to make sure your not-so-grown-up kid isn't lost, for example. In addition to the Location Sensor component, you will become familiar with the Texting component in this application.
Here is the idea: on receipt of a text message with "location" in its body, the application replies with the current location as a text message. The actions taken upon receipt of a text message are shown in Figure 7. This is the core logic for the application. In the "Texting1.MessageRecieved" procedure, the "number" and "messageText" are available as arguments. If the "messageText" is "location", then check whether the location has been obtained. If yes, then construct a reply using the address and send the text; otherwise, send an error message back as the reply.
Figure 7. Action Taken When a Text Message Is Received
The complete application, along with others, can be downloaded from https://bitbucket.org/amitksaha/articles_code/src. You can upload the source (.zip) archives to App Inventor directly and try out the applications after packaging them. In this article, I have strictly concentrated on using an Android device for testing the applications. For basic uses, you also can use the emulator that is available in App Inventor and also use a live development methodology where you can install the application directly to your device. See the App Inventor Web site to try these out. I tested these applications on my Samsung Galaxy-SII running Android 2.3, but I hope there won't be any issues with running them on other devices running Android 2.2 and higher.

Looking Ahead

I started this article with the intention of having some fun programming for the Android platform, and I hope it has been so thus far. If you're interested in looking into App Inventor further, the first things that you might want to check out, apart from extending the projects to something more fun and useful, are the various other components. Of special note is the Data Store component that allows you to store data on the device, the Web components for interacting with remote Web content, other Sensor components and Media components.
App Inventor is fun, but you might feel that although it's good as a starting point, you would prefer a more traditional programming language as you become more familiar with Android development. Instead of completely throwing your App Inventor project away, consider using the App Inventor Java Bridge to use your App Inventor components while you write Android applications using the more traditional way of programming in Java.
If you feel the need to run your own App Inventor service, the MIT Center for Mobile Learning has made available the App Inventor JARs to enable you to host your own service (see Resources).
If you want to keep exploring App Inventor itself, two excellent books are available: David Wolber, Hal Abelson, Ellen Spertus and Liz Looney's App Inventor: Create your own Android apps (O'Reilly) and Jason Tyler's App Inventor for Android: Build Your Own Apps—No Experience Required! (Wiley).
If you enjoyed App Inventor, you might want to look at some other tools for programming your Android device visually, such as DroidDraw and Corona. And if you want to program Android visually on the device itself, check out Catroid.

Resources

MIT App Inventor: http://appinventor.mit.edu
Setting Up Your Computer: http://appinventor.mit.edu/learn/setup/index.html
App Inventor Reference: http://appinventor.mit.edu/learn/reference/index.html
APK File Format: http://en.wikipedia.org/wiki/APK_%28file_format%29
Under the Hood of App Inventor: http://googleresearch.blogspot.com/2009/08/under-hood-of-app-inventor-for-android.html
App Inventor Open-Source Project: http://code.google.com/p/app-inventor-releases
Activity Starter Component: http://appinventor.mit.edu/learn/reference/other/activitystarter.html
App Inventor Java Bridge Project: http://groups.google.com/group/app-inventor-instructors/browse_thread/thread/10a64e64b7886afb
Running Your Own App Inventor Service: http://appinventoredu.mit.edu/developers-blogs/andrew/2011/nov/running-your-own-app-inventor-service
App Inventor Course: http://sites.google.com/site/appinventorcourse
"Android App Development" presentation by Peter McNeil: http://www.cjugaustralia.org/September+2011
Catroid Project: http://code.google.com/p/catroid
Code for This Article (available in the appinventor_article subdirectory): https://bitbucket.org/amitksaha/articles_code/src
---------------------------------------------------------
Getting started with MIT App Inventor


Article Index
Getting started with MIT App Inventor
First button and textbox
Working with Blocks
Using a real phone

Although App Inventor is sometime described as an educational toy that you can use to get kids interested in programming don't let this fool you into thinking that you can't do real things with it. It makes a very good prototyping facility - as we discover here.

App Inventor is an amazing way to create Android applications. You don't need to be able to program but if you can then all the better.
All I can say is that as a programmer this is the first time in quite a while that a development environment and its associated "language" has brought a smile to my face. It's not perfect, it's still in beta, but if you give it a little room to grown on you might just smile as well.
Although App Inventor is sometime described as an educational toy that you can use to get kids interested in programming don't let this fool you into thinking that you can't do real things with it. It makes a very good prototyping facility and a couple of the prototypes that I have created have actually ended up as final apps that are still in use.

Getting started

The worst part of trying any new programming environment is having to download and install things.
For the App Inventor this is less of a problem because a lot of it is designed as a web application. To use it you need a Google account - if you don't have one it is worth signing up.
However some of the system does run on your local machine - the Android emulator and the  designer. These are both Java applications and so your first task is to make sure that you have an up-to-date Java 6 (also known as 1.6) installation. You can check by clicking on the following link: Java test page.
After checking that you have Java installed you need to download the installer appropriate for your operating system - Windows, Linux or MacOS X. I used the Windows version.
Once the installation is complete you are ready to start using the App Inventor.
If you have had an older version of App Inventor installed on your computer it is a good idea to install the most recent version.
Don't worry at this stage about things like a USB driver for your phone or tablet the simulator is the best way to get started and there are other ways to get  your app onto your real phone without a USB driver.
To get started go to
If you are already signed in to Google you will be able to go straight to MyProjects - if not sign in and click MyProjects. The MyProjects section saves all of the apps you create for further use.
When you are learning a new system there is a lot to be said for the simpler the better. So lets create a Hello World app.

Hello World

Move to My Projects and click the New button. Enter HelloWorld and click the OK button. After a few moments you should see the App Inventor Designer window open. Anything you create using the App Inventor under the project named HelloWorld will be saved under your account for you to use the next time you log in.

MyProjects

Before getting started you need to know that the Designer, as its name suggest is used to design and create the user interface of your application.
If you have used a drag-and-drop designer for any other programming language this will be nothing new to you apart perhaps from the fact that it is hosted on the web.
Notice that the designer doesn't provide any behavior for the user interface you create  - this is all done using the Blocks Editor which is the second member of the team.
So to sum up:
  • the Designer is used to create the User Interface
and
  • the Blocks Editor is used to create the logic of the program, i.e. what the app does.
We will come to the Blocks Editor in a moment. For now let's just design a simple UI - in fact the simplest UI that can be made to do something.

The Designer

The Designer is split into four regions -
  • the Palette where you pick the components you want to use to build the UI. The Palette is divided into sections according to the type of component. For our example we only need to explore the Basic tab.
  • the Viewer which represents the screen of the phone and is used to layout the components of the UI
  • the Components pane which shows you a different view of the components that you have placed on the viewer - why you need a different view will become all too clear later on.
  • the Properties pane which lists all of the settings for the currently selected component. You use this to customize each component.

designer

First button and textbox

To get started all we need to do is place a button and a TextBox on the Viewer.
To do this simply make sure that the Basic tab is selected, click and hold on the button icon and drag it to the viewer and release the button. If this doesn't seem to work for you give the web page a moment or two - it can be slow to respond. Repeat the drag-and-drop for the Textbox.

designer

The components will arrange themselves on the screen. There are ways that you can control the layout but for the moment let's concentrate on getting the example working.
If you select the Button object in the viewer and look at the Properties panel you will see lots of settings that effect the way the Button looks. To change any of these simply type or select a new value. In this case all we need to do is change the Button's text. Scroll down until you find the Text property and enter into the box below  -  Click Me.

properties

When you return to the Viewer you will find that the Button now says "Click Me" - if it doesn't you haven't left the Text entry box. Either press return or click another area of the page.
This completes our very minimal UI!
In a real application you would spend much longer creating a suitable UI including uploading graphics and sound files to use with it. 
You will also go through many iterations of creating and tweaking the UI as you gain experience from using the app for real.

The Blocks Editor

While the Designer is the place that you app gets its look the Blocks Editor is the place your app gets its functionality. This is the place where you "write" the program.
The first problem with using the Blocks Editor is that it runs as a desktop app but it needs a download each time you run it. When you click on the "Open the Blocks Editor" button a Java download is initiated. You may well discover that your browse or operating system pops up messages saying its dangerous to download programs and other similar warnings. Ignore them all and when given any choices make sure you select Open or Run rather than Save.
The download has to execute for you to see the Blocks Editor.
Eventually is should open and you should see something like:

blocks



The Blocks Editor can look a bit mystifying when you first encounter it. All I can say is that once you understand its very simple operating principles and how it is organized it very quickly beings to look simple.
Each block represents some part of a program that you can use to put together a complete program.
The Blocks palette has three tabs - Built-In, My Blocks and Advanced.
Although Built-In has lots of interesting things you will want to use it's My Blocks that holds the blocks that are specific to the UI you created using the Designer and this is usually where you want to start work.
If you select the My Blocks tab you will see each of the components you added in the Designer plus the Screen which is a default object added to the Designer when it starts.

myblocks




Each UI component has a set of blocks associated with it that roughly speaking correspond to the sorts of things it can do.
If you select Button1 then you will see a  selection of blocks that correspond to things that can happen to the button - colored green - and lots of blocks identifying actions that can be performed on properties of the Button - colored blue and blocks corresponding to settings of these properties - color purple.

blocktypes

In general you will always find that a UI component has:
  • a set of green event blocks
  • a set of blue action  blocks
  • a set of purple value blocks.
Now let's see how these fit together - literally fit together!
If you select the Button1.Click block it will appear on the design surface and you can move it around. It doesn't matter where it sits in this instance.
If you look at it carefully you will see that it says
when Button1.Click do
and this is indeed what it is all about.
The block is activated when the button is clicked and what happens all depends on what other block you place within the shaped open area below the caption.

buttonclick

The block that you place inside the Click block has to fit so you can't put blocks together in a way that doesn't make sense - but if you are following how things work there is little chance you will even try.
What we would like to do is to set the TextBox's content to say "Hello World" when the button is clicked.
If you think about it for a moment this suggests that we need a block that involves an action on the TextBox. If you click on TextBox1 in the My Blocks tab list you will see that there is a blue property block that says:
set TextBox.Text to

textboxtext

This is the property action we are looking for - the Text property being what the TextBox displays.
Clicking on the block places it on the design surface and you can now drag-and-drop it into the space in the Button1.Click box. When you do this you will hear a satisfying click - this development environment knows how to keep you happy.

buttontext
This looks good but notice that you have an empty socket and this  won't actually be used if you try and run the program.
This is quite reasonable as the clump is incomplete. Currently it says
When Button1.Click do
 Set TextBox1.Text To
but To what?

Built-in blocks

We need a value block and in this case we need a simple text value from the Built-In blocks. These are used so often that a mini-menu appears when you click on the design surface. Select Text and drag the block that appears to the clump and connect it with the To socket.

text

Now we have a complete clump of blocks but the text value is set to its default "text" .
If you click on it you will discover that a text entry box opens and you can type in your message Hello World.

textentry

Now we have a complete program ready to run.
But how?
We have two choices you can run the program on a real Android device connected to the machine you are working on via a USB cable or you can use the emulator.
In most cases it is easier to use the emulator. This does take time to load and it is slower to use than a real phone but it does take time to download to a real phone and initially at least the emulator has the edge.
To run your program on the emulator simply click the "New emulator" button:

emulatorbuttons

The emulator does take time to open but once it is loaded you can keep it open and the Blocks Editor will detect that it is running and reuse it for future testing sessions.  In other words you only have to wait once for the emulator to load.
It is important that you wait until the emulator is showing the usual welcome screen before you try to use it.

emulator2

The emulator is very accurate and you even have to unlock the the phone in the usual way before you can use it.  (If you have never used an Android before you start it off by dragging the green padlock symbol to the right of the screen.)
All you have to do to see your application in action is to click the Connect to  Device button. When you do this you will see a list of devices that you can select to install your program on. If you have any real Android devices connected these will be in the list as well as the emulator.
If you now select the emulator your app will be downloaded to the emulator and all you have to do is run it as you would any app installed on an Android device. 
Notice that it takes time to download even a program this simple - be patient.
The device icon at the top of the screen shows yellow and an arrow while the app is downloading
download
and a steady green when the download has completed:
downloaded
Once the download is complete you can move to the emulator and unlock it as if it was a real phone and you should see your app ready to use
. In this case it isn't very exciting but it is the start of something very exciting. Click the button and see the message appear.

running

It really is this easy and simple.
If you don't want to modify the UI you can simply return to the Blocks Editor, make the changes and connect to the device again selecting Restart app to see the changes in action. If you need to change the UI go back to the Designer and start the Blocks Editor when you are ready.

Using a real phone

If you want to see your application on a real phone you can simply select the phone from the list of connected devices. This will only work if your Phone has a suitable USB driver install and you have set the phone to USB Debugging and Stay Awake using the Applications, Development menu in Settings.
If the USB device driver isn't included with the App Inventor then you can usually get it from the phone manufacturers website. It is installed if you make use of any synchronizing or phone management software that comes with the phone. The device must also have an SD card installed to work. You can find more information on the App Inventor web site.
If your phone is connected to your local WiFi network or you have a phone network connection  then there is a much easier way to get the app installed.
Return to the Designer and click on the Package for Phone button and select Show Bar Code. When the barcode appears hold your phone up to the screen and using a barcode scanning app (there are a number of free ones) scan the code.
This takes your phone to the App Inventor site and if you log in with the same Google account you used to create the app it will be automatically downloaded to the phone.

barcode

You can also opt to download the app to the desktop computer or directly to a phone's SD card via a USB cable - in this case no driver is required.

From here using App Inventor is a matter of exploring what UI components you have to create the look of your app and what blocks to give it the behavior you want. It isn't difficult but sometimes it can be a challenge to find what you are looking for. 
It is also worth knowing that this sort of approach to creating programs i.e. using blocks isn't unique to App Inventor - see the Scratch programming language for example.
Far from being just something educational App Inventor has enough power to allow you to build a wide range of apps. It's a serious design tool - that also just happens to be a whole lot of fun.
Look out for further explorations of the App Inventor in future articles on I Programmer.

More Information

http://appinventor.mit.edu

Related Articles

 

from http://www.i-programmer.info/programming/mobile/1789-getting-started-with-android-app-inventor.html