September 2011
53 posts
2 tags
Part 135: Using C/C++ in Droid
The NDK allows you to use JNI to use C/C++ code in your Java classes. So knowledge of JINI issues is essential. Nevertheless, this should get you started. First, download the NDK. I downloaded r6b, the latest. Then, create a C file in a new ‘jni’ directory in your projects root. And place this C file, test.c, there. #include <jni.h> jint...
Sep 30th
9 notes
3 tags
Part 134: Using a WebView for HTML5 apps
We can wrap our website in a WebView, which is basically the phone’s browser, but with our controls. First make a WebView in your XML layout file. <WebView  xmlns:android=”http://schemas.android.com/apk/res/android”     android:id=”@+id/webview”     android:layout_width=”fill_parent”     android:layout_height=”fill_parent”    ...
Sep 28th
1 note
3 tags
Part 133: Writing a View to a Bitmap
You can get a Bitmap representation of a View by setting the view to use caching, and then return that Bitmap cache: LinearLayout ll = (LinearLayout) findViewById(R.id.YOURLAYOUTITEM);        ll.setDrawingCacheEnabled(true); ll.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); ll.buildDrawingCache(); Bitmap b1 = ll.getDrawingCache(); You get a View item, enable its drawing cache, then...
Sep 23rd
30 notes
4 tags
Part 132: Shape Drawable / SVG buttons
These allow you to make simple vector shapes, with gradients, rounded corners and strokes etc. It’s a nice alternative to a 9patch button, as you can set the gradient in various ways, and use that drawable as the button’s background. You place a file like this in one of your drawable directories: <?xml version=”1.0” encoding=”utf-8”?> <selector    ...
Sep 20th
26 notes
2 tags
Part 131: Snake SDK sample, p5 TileView class
TILEVIEW CLASS This is used to draw the tiles to the screen.  It defines a mTileSize for the number, the dimensions of each tile. mX/YTileCount this is calculated in the onSizeChanged() method as the canvas width and height respectively divided by the mTileSize. The the mOffsetX/Y is calculated later as the difference between all the tiles and the canvas width. Then there’s a hash of...
Sep 20th
7 notes
2 tags
Part 130: Snake SDK sample, p4 main logic
SNAKEVIEW CLASS:  Now we’ve finished describing most of the initialisation methods, setMode() is worth a look, as the main Activity calls that. Depending on if it’s send READY, PAUSED etc it will update the SnakeView’s TextView with the appopriate info. If it’s send RUNNING, and it wasn’t before, it will hide the TextView and update the screen. It’s send...
Sep 20th
6 notes
3 tags
Part 129: Snake SDK sample, p3 constructors etc of...
SNAKEVIEW CLASS:  Now we’ve looked at its large number of variables, here are the constructors and boring utility methods. The two constructor methods simply pass the Context and the AttributeSet and defStyle from the XML declaration to its super class—the TileView which we’ll look at later. Both of the constructors call initSnakeView(). initSnakeView() sets this View to...
Sep 20th
7 notes
4 tags
Part 128: Snake SDK sample, p2 variables
SNAKEVIEW CLASS:  The class starts off by defining various static int used to reference various states, some arrays to store the snake location and various other bits. The state i.e. PAUSE, READY, RUNNING, LOSE and the member variable for that is mState. It’s initially READY. The direction i.e .NORTH, EAST, SOUTH, WEST and mDirection for the current direction and mNextDirection for the...
Sep 20th
25 notes
3 tags
Part 127: Snake SDK sample, p1
This series is going to be detailing the Snake SDK example in the Android docs. More for my edification than anything else. Hope it helps someone. MAIN ACTIVITY: In its onCreate() method it finds a custom view, a SnakeView, from the layout. And then gives that object a reference to a TextView from the layout. That will be used to display game info. Then if there’s no savedInstanceState...
Sep 20th
7 notes
4 tags
Part 126: Using speech recognition
We can use Android’s speech recognition to return a list of possibilities of what was spoken. First we need to make sure the system has this capability. Most should. The emulator doesn’t. PackageManager pm = getPackageManager(); List<ResolveInfo> activities = pm.queryIntentActivities(                 new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); if...
Sep 18th
9 notes
4 tags
Part 125: Using a SeekBar
You can define a horizontal seek bar fairly easily. Vertical is not yet supported. There are few attempts at it on the net though.     <SeekBar android:layout_height=”wrap_content”      android:indeterminate=”false”     android:thumb=”@drawable/icon”     android:id=”@+id/seekBar1”      android:layout_width=”match_parent”>    ...
Sep 18th
26 notes
4 tags
Part 124: Using the AudioManager to control volume
This manager allows you to set the volume for various sound types. We’ll set the music in this case. First get an AudioManger from the system.  AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); This has various methods, such as getting the max and current volume: int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); int curr =...
Sep 18th
12 notes
3 tags
Part 123: Text-To-Speech
The first thing you need to do in your onCreate() is check the phone needs to download support. The emulator didn’t, but my phone had to. You do this by calling an Intent which returns to you whether all went well or not. Intent checkIntent = new Intent(); checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkIntent, 1001);   This will return an...
Sep 18th
8 notes
5 tags
Part 122: SurfaceView for 2D graphics
Although our previous 2D graphics method worked, as it’s using the View system, it can be a little slow depending on what you’re doing. The SurfaceView gives us direct access to the 2D surface. First define a class that extends the SurfaceView. And make it implement Runnable, as the drawing method will run in its own Thread: public class GraphicClass extends SurfaceView implements...
Sep 18th
7 notes
2 tags
Part 121: Widgets p5: Config Activity
(This follows on from this set). You can make an Activity appear when the user goes to add your Widget to their screen for configuration purposes. First say you’ll be creating a configuration Activity in your manifest XML file:         <activity android:name=”.WidgetConfig”>          <intent-filter>          <action...
Sep 17th
4 notes
7 tags
Part 120: XML SAX parsing in Android
Unlike the simple JSON parsing function (you just put a string of JSON in a JSONArray object), XML is a little more involved. URL url = new URL(“http://www.google.com/ig/api?weather=Paris,France”); InputSource is = new InputSource(url.openStream()); is.setEncoding(“ISO-8859-1”); We first get a usual URL, and then put it into a SAX InputSource. We set its encoding to...
Sep 17th
13 notes
4 tags
Part 119: Using google maps p8: Using the...
We previously found the home location using the MyLocationOverlay class, and we can even listen on that to get a new location. There’s another way, however, and this one gives you access to the Provider information, including the ability to specify the accuracy of provider information.          lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);         Criteria c = new...
Sep 16th
30 notes
2 tags
Part 118: Using google maps p7: Streetview and...
Once you’ve got your MapView, it’s easy to switch between street and satellite view: if(mv.isSatellite()) {      mv.setSatellite(false);   mv.setStreetView(true); } else {    mv.setSatellite(true);    mv.setStreetView(false); } This simply switches to whatever not set currently.
Sep 16th
12 notes
6 tags
Part 117: Using google maps p6: Map clicks and...
If we want to do something when a user clicks on a map, we need to define our own overlay: class OurOverlay extends Overlay {   @Override   public boolean onTouchEvent(MotionEvent e, MapView mapView) {    } } This just extends an Overlay class and implements the onTouchEvent() that will be called on each click. We’d add that overlay to our MapView as we’ve done with the other...
Sep 16th
28 notes
3 tags
Part 116: Using google maps p5: animating and...
To animate and zoom to a point on the map, we need a MapController. We’ll use the coordinates of our previous MyLocationOveraly to zoom and animate to that point. Make sure this variable is now ‘final’ as we’ll be using from inside an inner class:        final MapController mController = mv.getController();                 myLocationOverlay.runOnFirstFix(new Runnable()...
Sep 16th
7 notes
4 tags
Part 115: Using google maps p4: finding device...
You can find the device’s location using the MyLocationOverlay object. MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mv); overlayList.add(myLocationOverlay);  myLocationOverlay.enableMyLocation(); We pass MyLocationOverlay the current Context (‘this’ as I’m running this in the onCreate method) and a MapView found previously. We then add that to the...
Sep 16th
6 notes
5 tags
Part 114: Using google maps p3: adding an overlay
You can add points on the map using an Overlay. First add a GeoPoint with the location’s coords, and add that to an OverlayItem, along with the Item’s title and body text: GeoPoint point = new GeoPoint(19240000,-99120000); OverlayItem overlayitem = new OverlayItem(point, “Hola, Mundo!”, “I’m in Mexico City!”);  Then we’re going to get a Drawable...
Sep 16th
10 notes
3 tags
Part 113: Using google maps p2: Pan and zoom
In your MapView tag (which must be the full name incidentally): <com.google.android.maps.MapView                android:id=”@+id/mapview1”                android:clickable=”true”                   android:layout_width=”fill_parent”                  android:layout_height=”fill_parent”           android:apiKey=”0VZ7vR3dpXD6p0KTdbQ1Dmlsdsdfsdfsdf4PUBRYb9sdfsdf” />  ...
Sep 15th
6 notes
4 tags
Part 112: Using google maps p1: setup
First off, make sure you have the Google Maps package: Google APIs from Google. Open up the AVD Manager and go to Installed packages. If it’s not there. Go to Available packages. Choose Third-party. Choose a Google APIs By Google Inc package. I’m using Android API 10. Then install it. After that, start a new project, and for its Build Target, choose Google APIs. And make sure its...
Sep 15th
9 notes
3 tags
Part 111: Using the accelerometer
The accelerometer will give you new x, y and z values based on how the device is tilted. First get the system service, check it has at least 1 accelerometer and then get that: mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); if(mSensorManager.getSensorList(             Sensor.TYPE_ACCELEROMETER).size()!=0) {     Sensor s = mSensorManager.getSensorList(                        ...
Sep 15th
9 notes
4 tags
Part 110: Updating the images/media index on the...
Previously we states that the Cursor to the images in the device wouldn’t see the most recently added images, or any recently added media for that matter. This is because we need to tell the system to update its list of media: to search for them again. We can do this two ways. The first is simple and simply sends an Intent to the system to update its list of images: sendBroadcast(new...
Sep 15th
59 notes
4 tags
Part 109: Accessing the Images/media on a device
To access all the images on your device, you can use a cursor: Cursor mImageCursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,                 null, null, null, null ); if(mImageCursor.moveToFirst())      do {         String s[] = mImageCursor.getColumnNames();         int column = mImageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);         String filename =...
Sep 15th
106 notes
3 tags
Part 108: ExternalStorage variables
You can access various pieces of information about the sdcard: where the external storage, sdcard is, if it’s mounted read only, where the pictures directory is, etc String state = Environment.getExternalStorageState(); This will return one of the Environment.MEDIA_* variables. Environment.MEDIA_MOUNTED tells you it’s there and mountable. Environment.MEDIA_MOUNTED_READ_ONLY tells...
Sep 15th
17 notes
4 tags
Part 107: App file I/O
File I/O is similar to standard Java. The difference is that Android allows you to set the file as only available to the application (and the application’s user) or set it world writable/readable. You’ll generally use this when you’re handling more than what can be dealt with in the Preferences system and it’s not suitable for the database. If you’re wanting to save...
Sep 15th
24 notes
5 tags
Part 106: Using a SlidingDrawer
The Sliding Drawer is a nice widget, but with some gotchas. Here’s the XML. Note the SlidingDrawer is referencing two element ID ‘drawbutton’ and ‘main_layout’ within it and its handle and content. We’re also setting the ‘allowSingleTap’, ‘orientation’ and ‘animateOnClick’ attributes which should be self-explanatory.    ...
Sep 15th
27 notes
4 tags
Part 105: Sound effects with SoundPool
Instead of using the AudioManager as before to play sounds, we can use the SoundPool. This allows us to play the same effect simultaneously.  mSp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0); mExplosion = 0; mExplosion = mSp.load(YourActivity.this,R.raw.explosion, 1); The SoundPool object takes the number of streams—how many channels to open to play the music. If you have only one,...
Sep 14th
8 notes
3 tags
Part 104: Adding a WakeLock
You may not want to device to sleep, or for the screen to turn off, during a game, for example. To do this you need to request a wake lock. First you need to ask for permission to create a wake lock in your AndroidManifest.xml file:   <uses-permission android:name=”android.permission.WAKE_LOCK”></uses-permission> Then get the POWER_SERVICE from the system services,...
Sep 14th
3 notes
6 tags
Part 103: Adding a Truetype font
To add a different font when you’re drawing text on a Canvas, you must first place a TTF file (or OpenFont I hear) in the assets/ folder in your root directory. That is, above the res/ directory, on the same level as src/. Then load in your font: Font mFont = Typeface.createFromAsset(c.getAssets(), “DroidSansMono.ttf”); You use the Typeface class to load the font in assets/....
Sep 12th
15 notes
5 tags
Part 102: View Animations
View Animations allow us to tween, translate, stretch, rotate etc a View. The animation is specified in XML, it’s then loaded in Java and the View class’s startAnimation() method then takes that. The XML takes in many elements—see here—but here’s one that scales, then simultaneously scales and rotates. It lives in res/anim/myanim.xml <?xml...
Sep 12th
2 notes
4 tags
Part 101: TransitionDrawable
A TransitionDrawable is a XML drawable with two states, above and below. Once you say start the transition, the bottom layer fades to the front. The XML in res/drawable-<whatever>/trans.xml: <?xml version=”1.0” encoding=”utf-8”?> <transition xmlns:android=”http://schemas.android.com/apk/res/android”>     <item...
Sep 12th
10 notes
6 tags
Part 100: Creating simple Canvas graphics on a...
You can create simple graphics—rectangles, text, bitmaps etc—on a normal View. This isn’t as efficient as a way we’ll see later, but for non intensive graphics, it works fine. You extend a new and separate View class, and override the draw(Canvas canvas). Using that canvas object you then draw to the screen.  The extended View class must be passed to the setContentView()...
Sep 12th
14 notes
6 tags
Part 99: Saving a Bitmap to the filesystem
Say you have a bitmap called ‘b’. We first create a ByteArrayOutputStream to hold it. Then we compress the Bitmap to it: ByteArrayOutputStream bytes = new ByteArrayOutputStream(); b.compress(Bitmap.CompressFormat.JPEG, 40, bytes); File f = new File(Environment.getExternalStorageDirectory()                                 + File.separator + “test.jpg”); try {  ...
Sep 12th
7 notes
7 tags
Part 98: LayerList drawable + conversion to a...
We can have a layer-list, which is a bunch of drawables layered upon each other. Create this in your res/drawable-mdpi/layerlist.xml (or whatever drawable dir you want). <?xml version=”1.0” encoding=”utf-8”?> <layer-list xmlns:android=”http://schemas.android.com/apk/res/android”>     <item>       <bitmap...
Sep 12th
8 notes
4 tags
Part 97: Altering your layout based on orientation...
You must set up a default layout file, let’s say that’s called main.xml in res/layout/. <LinearLayout  xmlns:android=”http://schemas.android.com/apk/res/android”     android:id=”@+id/main_layout”     android:layout_width=”fill_parent”     android:layout_height=”fill_parent”>     <TextView        ...
Sep 12th
13 notes
4 tags
Part 96: Accessing the camera, large images
To grab a image from the camera, but this time fetch a larger image, we need to use the Uri. The Android docs state that this method, specifying a EXTRA_OUTPUT, will gain you a larger image. But on my HTC 2.3 I see no difference. This may just be my device, however. Intent camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); try {   mTemp =...
Sep 11th
4 notes
4 tags
Part 95: Accessing the camera
To access a small sized picture from the camera, start an Intent without any extra data: Intent camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)  startActivityForResult(camera,0); We’re starting the Intent for a result, the result will have our Bitmap in it. We’re giving it a response int of 0 for brevity.     @Override     protected void...
Sep 11th
3 notes
4 tags
Part 94: Finding and playing MP3 files with...
It’s fairly easy to both find and play MP3s in Android.     private List<String> songs = new ArrayList<String>();     File home = Environment.getExternalStorageDirectory();     File f[] = home.listFiles(new Mp3Filter());     if (f!=null && f.length > 0) {                     for (File file : f) {                             songs.add(file.getAbsolutePath());  ...
Sep 10th
15 notes
5 tags
Part 93: Using a dimension XML file with different...
If you code in a dimension in dp, sp or whatever, you’ll need to adjust that for the main screen resolutions of android. Wikipedia has a list of resolutions with devices that use them. 480x800 is quite common at the moment. The HTC Desire and Nexus One use that. Our default resolutions will be 480x800, and we’ll also deal with 320x480, which is used in the HTC Hero. In our...
Sep 9th
32 notes
3 tags
Part 92: Using AsyncTask (with ProgressDialog)
We previously used a Handler/Message method to update a ProgressDialog. But we can use a AsyncTask instead. It’s a little cleaner, too. This can be used for any background task, too. It’s geared towards updating the main UI thread though, for that is not thread-safe. First setup your ProgressDialog         mProgress = new ProgressDialog(this);        ...
Sep 8th
5 notes
3 tags
Part 91: Hiding the soft keyboard
I’ve found I’ve needed to hide the soft keyboard after I’ve ran setText() on a AutoCompleteTextView.  You first need to get the a InputMethodManager, which is the interface between your app and the app’s input device. You get this via the getSystemService Activity method, passing INPUT_METHOD_SERVICE. InputMethodManager imm =...
Sep 8th
9 notes
4 tags
Part 90: Launching a specific phone app
Instead of using Intent chooser as before, we can launch a specific application on the phone. We do this by first looping through all the applications in the system, and getting the ResolveInfo for that application. From there, we can start the Intent.        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);         emailIntent.setType(“text/html”);               ...
Sep 7th
37 notes
3 tags
Part 89: Getting screen information
You can get information on the screen size using the Display class. You use the getWindowManager() Activity method to getDefaultDisplay().         Display display = getWindowManager().getDefaultDisplay();         display.getWidth(); You can also get the rotation of the device via getRotation(), which will return a Surface global. Surface.ROTATION_190 is as expected. Pixel formate and refresh...
Sep 7th
19 notes
5 tags
Part 88: ViewPager aka Homescreen fling/swipe.
If you want the kind of swipe or fling you get on the homescreen, you need to use the ViewPager element. This is in the compatibility pack, if you’re not using 3.0. You can download this in the Android SDK and ADK manager. If you may already have it. If not, check the available and installed tabs and download it. Then, in Eclipse, load that by going to Project -> Properties -> Java...
Sep 6th
8 notes
6 tags
Part 87: Gestures: SimpleOnGestureListener
If you want Android to detect when you swipe the screen, you first need to listen for a Touch event. This gives you access to a MotionEvent, with information about the stop, start, distance etc of the touch. You can pass this to a SimpleOnGestureListener to act on particular swipes.         mViewFlipper.setOnTouchListener(new OnTouchListener() {             @Override             public boolean...
Sep 5th
3 notes
4 tags
Part 86: Using a ViewFlipper
A ViewFlipper allows us to flip between views, or view groups. <ViewFlipper android:id=”@+id/ViewFlipper01”             android:layout_width=”wrap_content”             android:layout_height=”wrap_content”>       <TextView android:id=”@+id/TextView01”             android:layout_width=”fill_parent”            ...
Sep 5th
5 notes