Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore CU-MCA-SEM-VI-Advanced mobile application development

CU-MCA-SEM-VI-Advanced mobile application development

Published by Teamlease Edtech Ltd (Amita Chitroda), 2021-11-02 12:53:52

Description: CU-MCA-SEM-VI-Advanced mobile application development

Search

Read the Text Version

Give your users a different view of the world with the ability to control the rotation, tilt, zoom, and pan properties of the \"camera\" perspective of the map  Add Street View to your app : Embed Street View into an activity and let your users explore the world through panoramic 360-degree views. Programmatically control the zoom and orientation (tilt and bearing) of the Street View camera, and animate the camera movements over a given duration. 11.2 MAPS  Android allows us to integrate google maps in our application. You can show any location on the map, or can show different routes on the map e.t.c. You can also customize the map according to your choices.  Google Map - Layout file <fragment android:id=\"@+id/map\" android:name=\"com.google.android.gms.maps.MapFragment\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"/>  Google Map - AndroidManifest file The next thing you need to do is to add some permissions along with the Google Map API key in the AndroidManifest.XML file. Its syntax is given below – <!--Permissions--> <uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" /> <uses-permission android:name=\"android.permission.INTERNET\" /> <uses-permission android:name=\"com.google.android.providers.gsf.permission. READ_GSERVICES\" /> <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" /> <!--Google MAP API key--> <meta-data android:name=\"com.google.android.maps.v2.API_KEY\" android:value=\"AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0\" /> 201 CU IDOL SELF LEARNING MATERIAL (SLM)

 Customizing Google Map Adding Marker You can place a maker with some text over it displaying your location on the map. It can be done by via addMarker() method. Its syntax is given below – final LatLng TutorialsPoint = new LatLng(21 , 57); Marker TP = googleMap.addMarker(new MarkerOptions() .position(TutorialsPoint).title(\"TutorialsPoint\"));  Changing Map Type You can also change the type of the MAP. There are four different types of map and each give a different view of the map. These types are Normal,Hybrid,Satellite and terrain. You can use them as below googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);  Example Here is an example demonstrating the use of GoogleMap class. It creates a basic M application that allows you to navigate through the map. To experiment with this example , you can run this on an actual device or in an emulator. Create a project with google maps activity as shown below – Figure 11.1 202 CU IDOL SELF LEARNING MATERIAL (SLM)

It will open the following screen and copy the console url for API Key as shown below: Figure 11.2 Click on continue and click on Create API Key Figure 11.3 203 then it will show the following screen CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 11.4 activity_main.xml. <fragment xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:map=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/map\" android:name=\"com.google.android.gms.maps.SupportMapFragment\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"com.example.tutorialspoint7.myapplication.MapsActivity\" /> content of MapActivity.java. package com.example.tutorialspoint7.myapplication; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; 204 import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; CU IDOL SELF LEARNING MATERIAL (SLM)

import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. * In this case, we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device. * This method will only be triggered once the user has installed Google Play services and returned to the app. */ @Override 205 public void onMapReady(GoogleMap googleMap) { CU IDOL SELF LEARNING MATERIAL (SLM)

mMap = googleMap; // Add a marker in Sydney and move the camera LatLng TutorialsPoint = new LatLng(21, 57); mMap.addMarker(new MarkerOptions().position(TutorialsPoint).title(\"Tutorialspoint.com\")); mMap.moveCamera(CameraUpdateFactory.newLatLng(TutorialsPoint)); } } Following is the content of AndroidManifest.xml file. <?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.tutorialspoint7.myapplication\"> <!-- The ACCESS_COARSE/FINE_LOCATION permissions are not required to use Google Maps Android API v2, but you must specify either coarse or fine location permissions for the 'MyLocation' functionality. --> <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" /> <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" /> <uses-permission android:name=\"android.permission.INTERNET\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:supportsRtl=\"true\" 206 CU IDOL SELF LEARNING MATERIAL (SLM)

android:theme=\"@style/AppTheme\"> <!-- The API key for Google Maps-based APIs is defined as a string resource. (See the file \"res/values/google_maps_api.xml\"). Note that the API key is linked to the encryption key used to sign the APK. You need a different API key for each encryption key, including the release key that is used to sign the APK for publishing. You can define the keys for the debug and release targets in src/debug/ and src/release/. --> <meta-data android:name=\"com.google.android.geo.API_KEY\" android:value=\"AIzaSyAXhBdyKxUo_cb-EkSgWJQTdqR0QjLcqes\" /> <activity android:name=\".MapsActivity\" android:label=\"@string/title_activity_maps\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest> Output: 207 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 11.5 11.3 GPS Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"16dp\" android:gravity=\"center_horizontal\" android:orientation=\"vertical\"> <TextView 208 CU IDOL SELF LEARNING MATERIAL (SLM)

android:id=\"@+id/location\" 209 android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Current GPS Loaction\" android:textSize=\"24sp\" android:textStyle=\"bold\" /> <Button android:id=\"@+id/getLocation\" android:text=\"Get location\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnSuccessListener; import static android.Manifest.permission.ACCESS_FINE_LOCATION; public class MainActivity extends AppCompatActivity { private FusedLocationProviderClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CU IDOL SELF LEARNING MATERIAL (SLM)

setContentView(R.layout.activity_main); requestPermission(); client = LocationServices.getFusedLocationProviderClient(this); Button button = findViewById(R.id.getLocation); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) { return; } client.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener() { @Override public void onSuccess(Location location) { if (location != null) { TextView textView = findViewById(R.id.location); textView.setText(location.toString()); } } }); } }); } private void requestPermission(){ ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1); } } Step 4 − Add the following code to androidManifest.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> 210 CU IDOL SELF LEARNING MATERIAL (SLM)

<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\"> <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest> 211 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 11.6 11.4 LOCATION BASED SERVICES  Android location APIs make it easy for you to build location-aware applications, without needing to focus on the details of the underlying location technology.  The Location Object  The Location object represents a geographic location which can consist of a latitude, longitude, time stamp, and other information such as bearing, altitude and velocity.  Get the Current Location To get the current location, create a location client which is LocationClient object, connect it to Location Services using connect() method, and then call its getLastLocation() method. This method returns the most recent location in the form of Location object that contains latitude and longitude coordinates and other information 212 CU IDOL SELF LEARNING MATERIAL (SLM)

as explained above. To have location based functionality in your activity, you will have to implement two interfaces − GooglePlayServicesClient.ConnectionCallbacks GooglePlayServicesClient.OnConnectionFailedListener These interfaces provide following important callback methods, which you need to implement in your activity class – Figure 11.7  Get the Updated Location If you are willing to have location updates, then apart from above mentioned interfaces, you will need to implement LocationListener interface as well. This interface provide following callback method, which you need to implement in your activity class – Figure 11.8  Displaying a Location Address Once you have Location object, you can use Geocoder.getFromLocation() method to get an address for a given latitude and longitude. This method is synchronous, and 213 CU IDOL SELF LEARNING MATERIAL (SLM)

may take a long time to do its work, so you should call the method from the doInBackground() method of an AsyncTask class. The AsyncTask must be subclassed to be used and the subclass will override doInBackground(Params...) method to perform a task in the background and onPostExecute(Result) method is invoked on the UI thread after the background computation finishes and at the time to display the result. There is one more important method available in AyncTask which is execute(Params... params), this method executes the task with the specified parameters. 11.5 SENSORS Sensors can be used to monitor the three-dimensional device movement or change in the environment of the device. Android provides sensor api to work with different types of sensors. Figure 11.9  Types of Sensors Android supports three types of sensors: 1) Motion Sensors: These are used to measure acceleration forces and rotational forces along with three axes. 214 CU IDOL SELF LEARNING MATERIAL (SLM)

2) Position Sensors :These are used to measure the physical position of device. 3) Environmental Sensors :These are used to measure the environmental changes such as temperature, humidity etc.  Android Sensor API: Android sensor api provides many classes and interface. The important classes and interfaces of sensor api are as follows: 1) SensorManager class The android.hardware.SensorManager class provides methods : to get sensor instance, to access and list sensors, to register and unregister sensor listeners etc. You can get the instance of SensorManager by calling the method getSystemService() and passing the SENSOR_SERVICE constant in it. SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE); 2) Sensor class The android.hardware.Sensor class provides methods to get information of the sensor such as sensor name, sensor type, sensor resolution, sensor type etc. 3) SensorEvent class Its instance is created by the system. It provides information about the sensor. 4) SensorEventListener interface It provides two call back methods to get information when sensor values (x,y and z) change or sensor accuracy changes. 215 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 11.10 11.6 LIVE FOLDERS Live folders have been introduced in Android 1.5 and let you display any source of data on the Home screen without forcing the user to launch an application. A live folder is simply a real-time view of a ContentProvider. As such, a live folder can be used to display all your contacts, your bookmarks, your email, your playlists, an RSS feed, etc. The possibilities are endless! Android 1.5 ships with a few stock live folders to display your contacts. For instance, the screenshot below shows the content of the live folders that displays all my contacts with a phone number: Figure 11.11 If a contacts sync happens in the background while I'm browsing this live folder, I will see the change happen in real-time. Live folders are not only useful but it's also very easy to modify your application to make it provider a live folder. In this article, I will show you how to add a live folder to the Shelves application. You can download its source code and modify it by following my instructions to better understand how live folders work. 216 CU IDOL SELF LEARNING MATERIAL (SLM)

To give the user the option to create a new live folder, you first need to create a new activity with an intent filter who action is android.intent.action.CREATE_LIVE_FOLDER. To do so, simply open AndroidManifest.xml and add something similar to this: <activity android:name=\".activity.BookShelfLiveFolder\" android:label=\"BookShelf\"> <intent-filter> <action android:name=\"android.intent.action.CREATE_LIVE_FOLDER\" /> <category android:name=\"android.intent.category.DEFAULT\" /> </intent-filter> </activity> The label and icon of this activity are what the user will see on the Home screen when choosing a live folder to create: Figure 11.12 11.7 SUMMARY  Android allows us to integrate google maps in our application. You can show any location on the map , or can show different routes on the map e.t.c. You can also customize the map according to your choices.  Adding Marker 217 CU IDOL SELF LEARNING MATERIAL (SLM)

You can place a maker with some text over it displaying your location on the map. It can be done by via addMarker() method. Its syntax is given below – final LatLng TutorialsPoint = new LatLng(21 , 57); Marker TP = googleMap.addMarker(new MarkerOptions() position(TutorialsPoint).title(\"TutorialsPoint\"));  Changing Map Type You can also change the type of the MAP. There are four different types of map and each give a different view of the map. These types are Normal,Hybrid,Satellite and terrain. You can use them as below googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);  The API key for Google Maps-based APIs is defined as a string resource. Note that the API key is linked to the encryption key used to sign the APK..You need a different API key for each encryption key, including the release key that is used to sign the APK for publishing.  Android location APIs make it easy for you to build location-aware applications, without needing to focus on the details of the underlying location technology. 11.8 KEYWORDS  MAPS: a diagrammatic representation of an area of land or sea showing physical features, cities, roads, etc.  GPS: The Global Positioning System (GPS) is a U.S.-owned utility that provides users with positioning, navigation, and timing (PNT) services. This system consists of three segments: the space segment, the control segment, and the user segment.  Service network: as a collection of people and information brought together on the internet to provide a specific service or achieve a common business objective.  Sensor:a device which detects or measures a physical property and records, indicates, or otherwise responds to it...  Folder: the virtual location for applications, documents, data or other sub-folders. Folders help in storing and organizing files and data in the computer. The term is most commonly used with graphical user interface operating systems. 11.9 LEARNING ACTIVITY 1. List features developer can do while interfacing map with android. ___________________________________________________________________________ ___________________________________________________________________________ 218 CU IDOL SELF LEARNING MATERIAL (SLM)

2. Give the google map layout file. ___________________________________________________________________________ ___________________________________________________________________________ 11.10 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. What are the content of AndroidManifest.xml file? while creating MAP 2. List the call back methods in location based services while implementing activity class. 3. How can we get updated location using android programming? 4. Explain the process of displaying live location address. Long Questions 1. Create a Map application which allows you to navigate through MAP. 2. Explain the steps in interfacing GPS with android. 3. Explain sensors in detail. 4. Explain the process of accessing live folders. 5. Explain Android Sensor API B. Multiple Choice Questions 1. After completing google layout file one need to add some permission along with the Google _______ in the AndroidManifest.XML file a. Map API Key b. MAP c. Public Key d. None of these 2. The API key for Google Maps-based APIs is defined as a ________ resource 219 a. constant b. string c. primary CU IDOL SELF LEARNING MATERIAL (SLM)

d. secondary 3. You need a _________ API key for each encryption key. a. public b. same c. different d. private 4. The Location object represents a ________ location a. live b. virtual c. strategic d. geographic 5. Once you have Location object, you can use ________ method to get an address for a given latitude and longitude.. a. Geocoder.getFromLocation() b. Geolocator.getFromLocation() c. Geocoder.getFromMap() d. Geocoder.putFromLocation() Answers 220 1-a, 2-b, 3-c, 4-d, 5-a 11.11 REFERENCES References book  “Professional Android 4 Application Development” by Reto Meier CU IDOL SELF LEARNING MATERIAL (SLM)

 “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart Textbook references  “Professional Android 4 Application Development” by Reto Meier  “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart Website  Introduction to Android: http://developer.android.com/guide/index.html.  Android API: http://developer.android.com/reference/packages.html  Java 6 API: http://docs.oracle.com/javase/6/docs/api/  Android Fundamentals: http://developer.android.com/guide/components/fundamentals.html 221 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 12: ANDROID APPLICATION DEPLOYMENT AND CAMERA STRUCTURE 12.0 Learning Objectives 12.1 Introduction 12.2 Considerations To Use Camera On Android 12.3 Manifest Declarations 12.4 Building A Camera App 12.5 Creating A Preview Class 12.6 Placing Preview In A Layout 12.7 Capturing Pictures 12.8 Capturing Videos 12.9 Media Recorder 12.10 Rendering Previews 12.11 Android Application Deployment On Linux And Windows 12.12 Summary 12.13 Keywords 12.14 Learning Activity 12.15 Unit End Questions 12.16 References 12.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Describe the parameter that need to be considered while using camera with android.  Build a camera app.  Describe the parameter that need to be considered while doing media recording.  Install android on Linux. 12.1 INTRODUCTION  The Android framework includes support for various cameras and camera features available on devices, allowing you to capture pictures and videos in your applications.  Before enabling your application to use cameras on Android devices, you should consider a few questions about how your app intends to use this hardware feature.  Before starting development on your application with the Camera API, you should make sure your manifest has the appropriate declarations to allow use of camera hardware and other resource. 222 CU IDOL SELF LEARNING MATERIAL (SLM)

 One should have knowledge about installing Android on Linux. 12.2 CONSIDERATIONS TO USE CAMERA ON ANDROID  Camera Requirement : Is the use of a camera so important to your application that you do not want your application installed on a device that does not have a camera? If so, you should declare the camera requirement in your manifest.  Quick Picture or Customized Camera : How will your application use the camera? Are you just interested in snapping a quick picture or video clip, or will your application provide a new way to use cameras? For getting a quick snap or clip, consider Using Existing Camera Apps. For developing a customized camera feature, check out the Building a Camera App section.  Foreground Services Requirement: When does your app interact with the camera? On Android 9 (API level 28) and later, apps running in the background cannot access the camera. Therefore, you should use the camera either when your app is in the foreground or as part of a foreground service.  Storage: Are the images or videos your application generates intended to be only visible to your application or shared so that other applications such as Gallery or other media and social apps can use them? Do you want the pictures and videos to be available even if your application is uninstalled? Check out the Saving Media Files section to see how to implement these options 12.3 MANIFEST DECLARATIONS Before starting development on your application with the Camera API, you should make sure your manifest has the appropriate declarations to allow use of camera hardware and other resource.  Camera Permission - Your application must request permission to use a device camera lated features. <uses-permission android:name=\"android.permission.CAMERA\" />  Adding camera features to your manifest causes Google Play to prevent your application from being installed to devices that do not include a camera or do not support the camera features you specify.  If your application can use a camera or camera feature for proper operation, but does not require it, you should specify this in the manifest by including the android:required attribute, and setting it to false: <uses-feature android:name=\"android.hardware.camera\" android:required=\"false\" /> 223 CU IDOL SELF LEARNING MATERIAL (SLM)

 Storage Permission - Your application can save images or videos to the device's external storage (SD Card) if it targets Android 10 (API level 29) or lower and specifies the following in the manifest. <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />  Audio Recording Permission - For recording audio with video capture, your application must request the audio capture permission. <uses-permission android:name=\"android.permission.RECORD_AUDIO\" />  Location Permission - If your application tags images with GPS location information, you must request the ACCESS_FINE_LOCATION permission. Note that, if your app targets Android 5.0 (API level 21) or higher, you also need to declare that your app uses the device's GPS <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" /> ... <!-- Needed only if your app targets Android 5.0 (API level 21) or higher. --> <uses-feature android:name=\"android.hardware.location.gps\" /> 12.4 BUILDING A CAMERA APP The general steps for creating a custom camera interface for your application are as follows:  Detect and Access Camera - Create code to check for the existence of cameras and request access.  Create a Preview Class - Create a camera preview class that extends SurfaceView and implements the SurfaceHolder interface. This class previews the live images from the camera.  Build a Preview Layout - Once you have the camera preview class, create a view layout that incorporates the preview and the user interface controls you want.  Setup Listeners for Capture - Connect listeners for your interface controls to start image or video capture in response to user actions, such as pressing a button.  Capture and Save Files - Setup the code for capturing pictures or videos and saving the output.  Release the Camera - After using the camera, your application must properly release it for use by other applications. 12.5 CREATING A PREVIEW CLASS  A camera preview class is a SurfaceView that can display the live image data coming from a camera, so users can frame and capture a picture or video. 224 CU IDOL SELF LEARNING MATERIAL (SLM)

 The following example code demonstrates how to create a basic camera preview class that can be included in a View layout. This class implements SurfaceHolder.Callback in order to capture the callback events for creating and destroying the view, which are needed for assigning the camera preview input. /** A basic Camera preview class */ public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder mHolder; private Camera mCamera; public CameraPreview(Context context, Camera camera) { super(context); mCamera = camera; // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); // deprecated setting, but required on Android versions prior to 3.0 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, now tell the camera where to draw the preview. try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (IOException e) { Log.d(TAG, \"Error setting camera preview: \" + e.getMessage()); } } 225 CU IDOL SELF LEARNING MATERIAL (SLM)

public void surfaceDestroyed(SurfaceHolder holder) { // empty. Take care of releasing the Camera preview in your activity. } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // If your preview can change or rotate, take care of those events here. // Make sure to stop the preview before resizing or reformatting it. if (mHolder.getSurface() == null){ // preview surface does not exist return; } // stop preview before making changes try { mCamera.stopPreview(); } catch (Exception e){ // ignore: tried to stop a non-existent preview } // set preview size and make any resize, rotate or // reformatting changes here // start preview with new settings try { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (Exception e){ 226 Log.d(TAG, \"Error starting camera preview: \" + e.getMessage()); CU IDOL SELF LEARNING MATERIAL (SLM)

} } }  If you want to set a specific size for your camera preview, set this in the surfaceChanged() method as noted in the comments above. When setting preview size, you must use values from getSupportedPreviewSizes(). Do not set arbitrary values in the setPreviewSize() method. 12.6 PLACING PREVIEW IN A LAYOUT  A camera preview class, such as the example shown in the previous section, must be placed in the layout of an activity along with other user interface controls for taking a picture or video. This section shows you how to build a basic layout and activity for the preview.  The following layout code provides a very basic view that can be used to display a camera preview. In this example, the FrameLayout element is meant to be the container for the camera preview class. This layout type is used so that additional picture information or controls can be overlaid on the live camera preview images. <?xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"horizontal\" android:layout_width=\"fill_parent\" android:layout_height=\"fill_parent\" > <FrameLayout android:id=\"@+id/camera_preview\" android:layout_width=\"fill_parent\" android:layout_height=\"fill_parent\" android:layout_weight=\"1\" /> <Button 227 android:id=\"@+id/button_capture\" CU IDOL SELF LEARNING MATERIAL (SLM)

android:text=\"Capture\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" /> </LinearLayout>  On most devices, the default orientation of the camera preview is landscape. This example layout specifies a horizontal (landscape) layout and the code below fixes the orientation of the application to landscape. For simplicity in rendering a camera preview, you should change your application's preview activity orientation to landscape by adding the following to your manifest. <activity android:name=\".CameraActivity\" android:label=\"@string/app_name\" android:screenOrientation=\"landscape\"> <!-- configure this activity to use landscape orientation --> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity>  In the activity for your camera view, add your preview class to the FrameLayout element shown in the example above. Your camera activity must also ensure that it releases the camera when it is paused or shut down. The following example shows how to modify a camera activity to attach the preview class shown in Creating a preview class. 12.7 CAPTURING PICTURES  Once you have built a preview class and a view layout in which to display it, you are ready to start capturing images with your application. In your application code, you must set up listeners for your user interface controls to respond to a user action by taking a picture. 228 CU IDOL SELF LEARNING MATERIAL (SLM)

 In order to retrieve a picture, use the Camera.takePicture() method. This method takes three parameters which receive data from the camera. In order to receive data in a JPEG format, you must implement an Camera.PictureCallback interface to receive the image data and write it to a file. The following code shows a basic implementation of the Camera.PictureCallback interface to save an image received from the camera private PictureCallback mPicture = new PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE); if (pictureFile == null){ Log.d(TAG, \"Error creating media file, check storage permissions\"); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); } catch (FileNotFoundException e) { Log.d(TAG, \"File not found: \" + e.getMessage()); } catch (IOException e) { Log.d(TAG, \"Error accessing file: \" + e.getMessage()); } } };  Trigger capturing an image by calling the Camera.takePicture() method. The following example code shows how to call this method from a button View.OnClickListener. // Add a listener to the Capture button 229 CU IDOL SELF LEARNING MATERIAL (SLM)

Button captureButton = (Button) findViewById(R.id.button_capture); captureButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // get an image from the camera mCamera.takePicture(null, null, picture); } } ); 12.8 CAPTURING VIDEOS  Video capture using the Android framework requires careful management of the Camera object and coordination with the MediaRecorder class. When recording video with Camera, you must manage the Camera.lock() and Camera.unlock() calls to allow MediaRecorder access to the camera hardware, in addition to the Camera.open() and Camera.release() calls.  Unlike taking pictures with a device camera, capturing video requires a very particular call order. You must follow a specific order of execution to successfully prepare for and capture video with your application, as detailed below. 1. Open Camera - Use the Camera.open() to get an instance of the camera object. 2. Connect Preview - Prepare a live camera image preview by connecting a SurfaceView to the camera using Camera.setPreviewDisplay(). 3. Start Preview - Call Camera.startPreview() to begin displaying the live camera images. 4. Start Recording Video - The following steps must be completed in order to successfully record video: a. Unlock the Camera - Unlock the camera for use by MediaRecorder by calling Camera.unlock(). b. Configure MediaRecorder - Call in the following MediaRecorder methods in this order. For more information, see the MediaRecorder reference documentation. i. setCamera() - Set the camera to be used for video capture, use your application's current instance of Camera. ii. setAudioSource() - Set the audio source, use MediaRecorder.AudioSource.CAMCORDER. 230 CU IDOL SELF LEARNING MATERIAL (SLM)

iii. setVideoSource() - Set the video source, use MediaRecorder.VideoSource.CAMERA. iv. Set the video output format and encoding. For Android 2.2 (API Level 8) and higher, use the MediaRecorder.setProfile method, and get a profile instance using CamcorderProfile.get(). For versions of Android prior to 2.2, you must set the video output format and encoding parameters: a. setOutputFormat() - Set the output format, specify the default setting or MediaRecorder.OutputFormat.MPEG_4. b. setAudioEncoder() - Set the sound encoding type, specify the default setting or MediaRecorder.AudioEncoder.AMR_NB. c. setVideoEncoder() - Set the video encoding type, specify the default setting or MediaRecorder.VideoEncoder.MPEG_4_SP. v. setOutputFile() - Set the output file, use getOutputMediaFile(MEDIA_TYPE_VIDEO).toString() from the example method in the Saving Media Files section. vi. setPreviewDisplay() - Specify the SurfaceView preview layout element for your application. Use the same object you specified for Connect Preview. d. Prepare MediaRecorder - Prepare the MediaRecorder with provided configuration settings by calling MediaRecorder.prepare(). e. Start MediaRecorder - Start recording video by calling MediaRecorder.start(). 5. Stop Recording Video - Call the following methods in order, to successfully complete video recording: a. Stop MediaRecorder - Stop recording video by calling MediaRecorder.stop(). b. Reset MediaRecorder - Optionally, remove the configuration settings from the recorder by calling MediaRecorder.reset(). c. Release MediaRecorder - Release the MediaRecorder by calling MediaRecorder.release(). d. Lock the Camera - Lock the camera so that future MediaRecorder sessions can use it by calling Camera.lock(). Starting with Android 4.0 (API level 14), this call is not required unless the MediaRecorder.prepare() call fails. 6. Stop the Preview - When your activity has finished using the camera, stop the preview using Camera.stopPreview(). 7. Release Camera - Release the camera so that other applications can use it by calling Camera.release(). 12.9 MEDIA RECORDER Configuring MediaRecorder: 231 CU IDOL SELF LEARNING MATERIAL (SLM)

When using the MediaRecorder class to record video, you must perform configuration steps in a specific order and then call the MediaRecorder.prepare() method to check and implement the configuration. The following example code demonstrates how to properly configure and prepare the MediaRecorder class for video recording. private boolean prepareVideoRecorder(){ mCamera = getCameraInstance(); mediaRecorder = new MediaRecorder(); // Step 1: Unlock and set camera to MediaRecorder mCamera.unlock(); mediaRecorder.setCamera(mCamera); // Step 2: Set sources mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); // Step 3: Set a CamcorderProfile (requires API Level 8 or higher) mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); // Step 4: Set output file mediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString()); // Step 5: Set the preview output mediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface()); // Step 6: Prepare configured MediaRecorder try { mediaRecorder.prepare(); } catch (IllegalStateException e) { Log.d(TAG, \"IllegalStateException preparing MediaRecorder: \" + e.getMessage()); 232 CU IDOL SELF LEARNING MATERIAL (SLM)

releaseMediaRecorder(); return false; } catch (IOException e) { Log.d(TAG, \"IOException preparing MediaRecorder: \" + e.getMessage()); releaseMediaRecorder(); return false; } return true; } // Step 3: Set output format and encoding (for versions prior to API Level 8) mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT); Starting and stopping MediaRecorder When starting and stopping video recording using the MediaRecorder class, you must follow a specific order, as listed below. Unlock the camera with Camera.unlock() Configure MediaRecorder as shown in the code example above Start recording using MediaRecorder.start() Record the video Stop recording using MediaRecorder.stop() Release the media recorder with MediaRecorder.release() Lock the camera using Camera.lock() The following example code demonstrates how to wire up a button to properly start and stop video recording using the camera and the MediaRecorder class. private boolean isRecording = false; // Add a listener to the Capture button 233 CU IDOL SELF LEARNING MATERIAL (SLM)

Button captureButton = (Button) findViewById(id.button_capture); 234 captureButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (isRecording) { // stop recording and release camera mediaRecorder.stop(); // stop the recording releaseMediaRecorder(); // release the MediaRecorder object mCamera.lock(); // take camera access back from MediaRecorder // inform the user that recording has stopped setCaptureButtonText(\"Capture\"); isRecording = false; } else { // initialize video camera if (prepareVideoRecorder()) { // Camera is available and unlocked, MediaRecorder is prepared, // now you can start recording mediaRecorder.start(); // inform the user that recording has started setCaptureButtonText(\"Stop\"); isRecording = true; } else { // prepare didn't work, release the camera releaseMediaRecorder(); // inform user } } CU IDOL SELF LEARNING MATERIAL (SLM)

} } ); 12.10 RENDERING PREVIEWS  Rendering is a key aspect of your app that influences your users' perception of quality is the smoothness with which it renders images and text to the screen. It is important to avoid jank and sluggish responsiveness when your app is drawing to the screen.  Rendering Pages from PDFs: final PdfDocument document; // Use this Uri format to access files inside your app's assets. final Uri documentUri = Uri.parse(\"file:///android_asset/shopping-center-plan.pdf\"); // This synchronously opens the document. To keep your app UI responsive, you should do this call // on a background thread or use the asynchronous version of this method instead. document = PdfDocument.openDocument(context, documentUri); final int pageIndex = 0; // Page size is in PDF points (not pixels). final Size pageSize = document.getPageSize(pageIndex); // We define a target width for the resulting bitmap and use it to calculate the final height. final int width = 2048; final int height = (int) (pageSize.height * (width / pageSize.width)); // This will render the first page uniformly into a bitmap with a width of 2048 pixels. final Bitmap pageBitmap = document.renderPageToBitmap(context, pageIndex, width, height); 12.11 ANDROID APPLICATION DEPLOYMENT ON LINUX AND WINDOWS Steps to Install Android Studio 235 Step – 1: Head over to bellow link to get the Android Studio executable or zip file . CU IDOL SELF LEARNING MATERIAL (SLM)

https://developer.android.com/studio/#downloads Step – 2: Click on the download android studio button Figure 12.1 Click on the “I have read and agree with the above terms and conditions” checkbox followed by the download button. Figure 12.2 Click on save file button in the appeared prompt box and the file will start downloading. Step – 3: After the downloading has finished, open the file from downloads and run it . It will prompt the following dialogue box. 236 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 12.3 Click on next. In the next prompt it’ll ask for a path for installation. Choose a path and hit next. Step – 4: It will start the installation, and once it is completed, it will be like the image shown below Figure 12.4 237 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 12.5 Step – 5 : Once “Finish” is clicked, it will ask whether the previous settings needs to be imported [if android studio had been installed earlier], or not. It is better to choose the ‘Don’t import Settings option’ Figure 12.6 This will start the Android Studio. 238 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 12.7 Meanwhile it will be finding the available SDK components . Figure 12.8 Step – 7: After it has found the SDK components, it will redirect to the Welcome dialog box . 239 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 12.9 Click on next . Figure 12.10 240 Choose Standard and click on Next. Now choose the theme, whether Light theme or the Dark one . CU IDOL SELF LEARNING MATERIAL (SLM)

The light one is called the IntelliJ theme whereas the dark theme is called Darcula . Choose as required. Figure 12.11 Click on the Next button Step – 8 : Now it is time to download the SDK components . 241 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 12.12 Click on Finish . Figure 12.13 It has started downloading the components 242 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 12.14 The Android Studio has been successfully configured. Now it’s time to launch and build apps. 243 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 12.15 12.12 SUMMARY  Various parameter that need to e considered while interfacing camera with android was discussed.  The process of media recorder is only possible when CREATING A PREVIEW CLASS and PLACING PREVIEW IN A LAYOUT.  The systematic approach of capturing picture and also interfacing camera using java language was discussed.  The systematic approach of capturing media recorder using java language was discussed.  Installation process of Android on Linux platform and windows was learned in depth. 12.13 KEYWORD  Camera ― an optical instrument that captures a visual image. At a basic level, cameras are sealed boxes (the camera body) with a small hole (the aperture) that allows light in to capture an image on a light-sensitive surface.  Manifest - to show something clearly, through signs or actions  GPS: The Global Positioning System (GPS) is a satellite-based radionavigation system owned by the United States government and operated by the United States Space Force  Surface View: Provides a dedicated drawing surface embedded inside of a view hierarchy. You can control the format of this surface and, if you like, its size; the Surface View takes care of placing the surface at the correct location on the screen.  JPEG:JPEG or JPG (/ˈdʒeɪpɛɡ/ JAY-peg)[2] is a commonly used method of lossy compression for digital images, particularly for those images produced by digital photography. 11.14 LEARNING ACTIVITY 1. What are the points need to be considered while using camera on Android ___________________________________________________________________________ ___________________________________________________________________________ 2. State the procedure for building camera app ___________________________________________________________________________ ___________________________________________________________________________ 244 CU IDOL SELF LEARNING MATERIAL (SLM)

12.15 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. How is camera app build? 2. Explain the procedure to place preview of camera in layout. 3. Explain the procedure of starting and stopping media recorder. 4. Explain the concept of rendering preview. 5. How is media recorder configured? Long Questions 1. Explain the procedure of capturing pictures. 2. Explain the procedure of capturing video. 3. Demonstrate the installation process of Android on Linux. 4. Explain manifest declaration in detail. 5. How preview class is created for camera app? B. Multiple Choice Questions 1. On Android _____, apps running in the background cannot access the camera. a. 7 b. 8 c. 9 and above d. All of the mentioned 2. If your application can use a camera or camera feature for proper operation, but does not require it, you should specify this in the manifest by including the android: required attribute, and setting it to _________ a. True b. False 3. If your app targets Android 5.0 (API level 21) or higher, you also need to declare that your app uses the device's ____________ a. GPS b. Camera c. Media Recorder d. Bluetooth 4. In building camera app we need to set up _______ for capture 245 a. Listner b. Reciever CU IDOL SELF LEARNING MATERIAL (SLM)

c. Sender d. Director 5. If you want to set a specific size for your camera preview, set this in the ________ a. surfaceChanged() b. addlistner() c. getHolder() d. All of these Answers 1-c, 2-b, 3-a. 4-a, 5-a 12.16 REFERENCES References book  Wei - Meng Le, “Beginning Android 4 Applications Development”, John Wiley & Sons, Inc. , 2012.  Reto Meier, “Professional Android 4 Applications Development”, John Wiley & Sons, Inc., 2012  Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, “Programming Android”, O’Reily books, 2011. Website  https://www.javatpoint.com/  https://developer.android.com/reference/android/media/MediaRecorder  https://android-developers.googleblog.com/2020/02/Android-11-developer- preview.html 246 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook