Tuesday, September 13, 2011

How to import CameraPreview from Android ApiDemos

Let's say you want to tinker with the CameraPreview class from the Android ApiDemos that you downloaded from the ADT Eclipse plugin, but you don't want to mess up that nice shiny ApiDemos package.

You'll probably want to start a new Android project and then import the CameraPreview.java file into your package namespace under your project's src folder.

Once you do that you'll see you have some errors, so let's clean those up.

Let's start by first retrieving the camera_menu.xml file from the ApiDemos project res/menu folder and importing that into our res/layout folder. This is the menu that will display when you hit the menu key.

We're still missing some strings, so let's add the missing strings from res/values/strings.xml to our res/values/strings.xml file.
 <string name="density_title">Density: Unknown Screen</string>  
 <string name="camera_alert">Device has only one camera!</string>  
 <string name="switch_cam">Switch Camera</string>  

Finally we'll change the location for our camera_menu to it's new location. Change line 109 to
 inflator.inflate(R.layout.camera_menu, menu);  
We've now cleaned up all the errors (hopefully)! But if you launch your new project you'll notice nothing special happens. That's because we haven't called our new CameraPreview activity that we were so careful to import.

Let's add a call in the onCreate() method of our main activity
 startActivity(new Intent(this, CameraPreview.class));  
and then add this activity to our AndroidManifest.xml
 <activity android:name=".CameraPreview"></activity>  
If we launched out activity now, we'd still be jumping the gun and would get a force close. The last thing we should (which probably should have been first!) is to add permission to use the camera by adding this line to our AndroidManifest.xml
 <uses-permission android:name="android.permission.CAMERA" />  
Now if you launch your new sample app you should see the camera preview. Now you're free to tinker as you'd like without disturbing your original copy of the ApiDemos code.

No comments:

Post a Comment