archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Implementing Video Playback on Android using the VideoView and MediaController Classes - Techotopia
    Eclipse and create a new Android Application project named VideoPlayer using the appropriate Android SDK versions and package name and including a blank activity named VideoPlayerActivity with corresponding layout and fragment files named activity video player and fragment video player Designing VideoPlayer Layout The user interface for the main activity will simply consist of an instance of the VideoView class If the Graphical Layout tool is not already displayed use the Package Explorer panel to locate the res layout fragment video player xml file and double click on it Within the layout canvas delete the Hello world TextView Switch to the XML view and remove the padding properties from the layout so that the XML reads as follows RelativeLayout xmlns android http schemas android com apk res android xmlns tools http schemas android com tools android layout width match parent android layout height match parent tools context com example videoplayer VideoPlayerActivity PlaceholderFragment RelativeLayout Switch back to the Graphical Layout view and from the Images Media section of the Palette panel drag and drop a VideoView instance onto the center point of the layout so that the user interface resembles that of Figure 37 1 Figure 37 1 Save the layout before proceeding Configuring the VideoView The next step is to configure the VideoView with the path of the video to be played and then start the playback This will be performed when the main activity has initialized so select the VideoPlayerActivity java file and override the OnStart method as outlined in the following listing package com example videoplayer package com example videoplayer import android app Activity import android app ActionBar import android app Fragment import android os Bundle import android view LayoutInflater import android view Menu import android view MenuItem import android view View import android view ViewGroup import android os Build import android widget VideoView public class VideoPlayerActivity extends Activity Override protected void onStart super onStart final VideoView videoView VideoView findViewById R id videoView1 videoView setVideoPath http www ebookfrenzy com android book movie mp4 videoView start All that this code does is obtain a reference to the VideoView instance in the layout set the video path on it to point to an MPEG 4 file hosted on a web site and then start the video playing Adding Internet Permission An attempt to run the application at this point would result in the application failing to launch with an error dialog appearing on the device that reads Unable to Play Video Sorry this video cannot be played This is not because of an error in the code or an incorrect video file format The issue would be that the application is attempting to access a file over the internet but has failed to request appropriate permissions to do so To resolve this edit the AndroidManifest xml file for the project and add a line to request internet access eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication in eBook 9 99 or Print

    Original URL path: http://www.techotopia.com/index.php/Implementing_Video_Playback_on_Android_using_the_VideoView_and_MediaController_Classes (2016-02-13)
    Open archived version from archive


  • Video Recording and Image Capture on Android using Camera Intents - Techotopia
    final int IMAGE CAPTURE 102 Intent intent new Intent MediaStore ACTION IMAGE CAPTURE startActivityForResult intent IMAGE CAPTURE As with video capture the intent may be passed the location and file name into which the image is to be stored or left to use the default location and naming convention Creating an Example Video Recording Project In the remainder of this chapter a very simple application will be created to demonstrate the use of the video capture intent The application will consist of a single button which when touched by the user will launch the video capture intent Once video has been recorded and the video capture intent dismissed the application will simply display the path to the video file as a Toast message The VideoPlayer application created in the previous chapter will then be modified to play back the recorded video Begin the application creation process by launching Eclipse and creating a new Android Application project named CameraApp using the appropriate Android SDK versions and package name and including a blank activity named CameraAppActivity with corresponding layout and fragment files named activity camera app and fragment camera app respectively eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Designing the User Interface Layout Within the Graphical Layout tool delete the default Hello World text view from the fragment camera app xml layout file and replace it with a Button view positioned in the center of the display canvas Change the text on the button to read Record Video and assign an onClick property to the button so that it calls a method named startRecording when selected by the user google ADSDAQBOX FLOW google Figure 40 2 Finally change the ID of the button to recordButton The corresponding XML in the fragment camera app xml file should approximately resemble the following listing RelativeLayout xmlns android http schemas android com apk res android xmlns tools http schemas android com tools android layout width match parent android layout height match parent android paddingBottom dimen activity vertical margin android paddingLeft dimen activity horizontal margin android paddingRight dimen activity horizontal margin android paddingTop dimen activity vertical margin tools context CameraAppActivity Button android id id recordButton android layout width wrap content android layout height wrap content android layout centerHorizontal true android layout centerVertical true android onClick startRecording android text string button string RelativeLayout Save the layout file before proceeding Checking for the Camera Before attempting to launch the video capture intent the application first needs to verify that the device on which it is running actually has a camera For the purposes of this example we will simply make use of the previously outlined hasCamera method this time checking for any camera type In the event that a camera is not present the Record Video button will be disabled Select the CameraAppActivity java

    Original URL path: http://www.techotopia.com/index.php/Video_Recording_and_Image_Capture_on_Android_using_Camera_Intents (2016-02-13)
    Open archived version from archive

  • Android Audio Recording and Playback using MediaPlayer and MediaRecorder - Techotopia
    AudioAppActivity with corresponding layout and fragment files named activity audio app and fragment audio app respectively Designing the User Interface Once the new project has been created select the fragment audio app xml file from the Project Explorer panel and within the Graphical Layout tool select the Hello world TextView and delete it from the layout Drag and drop three Button views onto the layout The positioning of the buttons is not of paramount importance to this example though Figure 41 1 shows a suggested layout Configure the buttons to display string resources that read Record Play and Stop and give them view IDs of recordButton playButton and stopButton respectively Figure 41 1 Right click on the Play button and select the Other Properties All by Name OnClick menu option to configure the button to call a method named playAudio when selected by the user Repeat these steps to configure the remaining buttons to call methods named recordAudio and stopClicked respectively Once the user interface design phase is complete save the file Checking for Microphone Availability Attempting to record audio on a device without a microphone will cause the Android system to throw an exception It is vital therefore that the code check for the presence of a microphone before making such an attempt There are a number of ways of doing this including checking for the physical presence of the device An easier approach and one that is more likely to work on different Android devices is to ask the Android system if it has a package installed for a particular feature This involves creating an instance of the Android PackageManager class and then making a call to the object s hasSystemFeature method In this case the feature of interest is PackageManager FEATURE MICROPHONE For the purposes of this example we will create a method named hasMicrophone that may be called upon to check for the presence of a microphone Within the Package Explorer panel locate and double click on the AudioAppActivity java file and modify it to add this method package com example audioapp import android app Activity import android app ActionBar import android app Fragment import android os Bundle import android view LayoutInflater import android view Menu import android view MenuItem import android view View import android view ViewGroup import android os Build import android content pm PackageManager public class AudioAppActivity extends Activity protected boolean hasMicrophone PackageManager pmanager this getPackageManager return pmanager hasSystemFeature PackageManager FEATURE MICROPHONE eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Performing the Activity Initialization The next step is to override the onStart method of the activity to perform a number of initialization tasks Remaining within the AudioAppActivity java file add the method as follows package com example audioapp import java io IOException import android app Activity import android app

    Original URL path: http://www.techotopia.com/index.php/Android_Audio_Recording_and_Playback_using_MediaPlayer_and_MediaRecorder (2016-02-13)
    Open archived version from archive

  • Working with the Google Maps Android API - Techotopia
    OK in the browser window followed by Finish in the Import Projects window On completion of a successful import the google play services lib project should appear in the Project Explorer panel Adding the Google Play Services Library to a Project Build Path The Google Play services library project will need to be added to the build path of any Eclipse project requiring Google Maps functionality To add map support to a project locate the project within the Eclipse Package Explorer panel right click on the project name and select the Properties option from the resulting menu Within the Properties dialog select the Android category from the left hand panel and within the right hand panel click on the Add button in the Library section This will display the Project Selection dialog Figure 42 3 with the previously imported google play services lib library project listed Figure 42 3 With the google play services lib project selected click on OK to close the selection dialog followed by the Apply button in the properties panel The library project should then be listed within the Library section of the properties panel as illustrated in Figure 42 4 Figure 42 4 Obtaining Your Developer Signature Before an application can make use of the Google Maps Android API it must first be registered within the Google APIs Console Before an app can be registered however the developer signature also referred to as the SHA 1 fingerprint associated with your development environment must be obtained This can be found from within the Eclipse Preferences dialog Access this dialog by selecting the Eclipse Window Preferences menu option Once loaded click on the small right facing arrow next to Android in the left hand panel to unfold the Android sub categories From this list select the Build item to display the build settings as shown in Figure 42 5 Figure 42 5 The SHA1 fingerprint is listed under the default debug keystore path next to the SHA1 fingerprint label and consists of 20 sets of 2 digit hexadecimal numbers separated by colons Registering the Project in the Google APIs Console The next step is to create a project in the Google APIs Console and enable it to make use of the Google Maps Android API service The Google APIs Console can be accessed using the following URL where you will be required to sign in using your existing Google account information https code google com apis console If this is the first time you have created a project in the console begin by clicking on the Create project button With the newly created project selected click on the APIs option listed under the APIs auth heading in the left hand panel Figure 42 6 to display an alphabetical list of APIs and services available to the project At this point the Services tab should be selected Figure 42 6 displaying an alphabetical list of APIs and services available to the project Figure 42 6 Scroll down the list of services until the Google Maps Android API v2 entry comes into view Change the position of the switch from the off to the on position Figure 42 7 and agree to the terms of service agreement that will subsequently appear Figure 42 7 Once the API has been enabled scroll to the top of the page and select the Credentials option from the left hand navigation panel which will display the page shown in Figure 42 8 Figure 42 8 Click on the CREATE NEW KEYreate new Android key button and in the resulting panel select the Android key button In the resulting Create an Android key and configure allowed Android applicationsConfigure Android Key for API Project dialog paste the previously obtained SHA 1 fingerprint into the text box making sure that you place a semi colon at the end of the key Immediately after the semi colon enter the package name of the application that will require access to the Google Maps Android API For example 5B AC 37 4E 87 66 2A 1A 9D 23 DE DD BA AF E2 B9 60 D1 C4 99 com example AndroidTest Once the fingerprint and key have been entered click on the Create button to create the key at which point the Credentials API Access screen will update to include the new Key for Android applications including a line listed as API key Figure 42 9 Currently the generated API key in this example is configured only for use with an application with the package name of com example AndroidTest Additional applications may be added to the API key by clicking on the Edit allowed Android applications link and entering additional lines consisting of the SHA 1 fingerprint and the application package name At this point the development environment is set up to enable maps to be used within a specific application The next step is to set up the application itself to use maps This begins with making some additions to the application s Android manifest file Adding Map Support to the AndroidManifest xml File Before maps can be used in an application some additional entries need to be added to the application s Android Manifest file Within Eclipse locate the AndroidManifest xml file for the project for which maps support is required and for which the package name was used when generating the API key Immediately before the application tag enter the following lines where api key is replaced by the API Key generated for your development system and application in the API Console meta data android name com google android maps v2 API KEY android value api key meta data android name com google android gms version android value integer google play services version In addition a number of permissions need to be added to the manifest file The following permissions are mandatory where package name is replaced by the application package name for example com example AndroidTest permission android name package name permission MAPS RECEIVE android protectionLevel signature uses permission android name package name permission MAPS RECEIVE uses permission android name android permission INTERNET uses permission android name android permission ACCESS NETWORK STATE uses permission android name android permission WRITE EXTERNAL STORAGE uses permission android name com google android providers gsf permission READ GSERVICES The following permissions are optional but are necessary if the application is required to obtain the current location of the device uses permission android name android permission ACCESS COARSE LOCATION uses permission android name android permission ACCESS FINE LOCATION Finally an entry needs to be added to the manifest file to indicate that the maps features are only available when the application is running on a device that supports OpenGL ES version 2 or later uses feature android glEsVersion 0x00020000 android required true Bringing these settings together a typical AndroidManifest xml file with Google Maps support might therefore read as follows xml version 1 0 encoding utf 8 manifest xmlns android http schemas android com apk res android package com example AndroidTest android versionCode 1 android versionName 1 0 permission android name com example AndroidTest permission MAPS RECEIVE android protectionLevel signature uses permission android name com example AndroidTest permission MAPS RECEIVE uses permission android name android permission INTERNET uses permission android name android permission ACCESS NETWORK STATE uses permission android name android permission WRITE EXTERNAL STORAGE uses permission android name com google android providers gsf permission READ GSERVICES uses permission android name android permission ACCESS COARSE LOCATION uses permission android name android permission ACCESS FINE LOCATION uses feature android glEsVersion 0x00020000 android required false uses sdk android minSdkVersion 19 android targetSdkVersion 19 application android allowBackup true android icon drawable ic launcher android label string app name android theme style AppTheme activity android name com example AndroidTest AndroidTestActivity android label string app name intent filter action android name android intent action MAIN category android name android intent category LAUNCHER intent filter activity meta data android name com google android maps v2 API KEY android value api key meta data android name com google android gms version android value integer google play services version application manifest Checking for Google Play Services Support Since the use of the Google Maps Android API requires that the target device support Google Play services it is important that the application check to make sure those services are available and enabled on a device before attempting to render a map This can be achieved by making a call to the isGooglePlayServicesAvailable method contained within the GooglePlayServicesUtil package When called this method will return a status value indicating whether the service is available missing invalid disabled or requires an update Some of the error states are categorized as being user recoverable Whether or not the error is recoverable or not can be identified by a call to the GooglePlayServicesUtil isUserRecoverableError method passing through the status value as an argument In the event that the failure is user recoverable a call to the getErrorDialog method will display a dialog to the user providing the option either to enable Google Play on the device or if necessary download and install the Google Play services package from the Google Play Store eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Understanding Geocoding and Reverse Geocoding It is impossible to talk about maps and geographical locations without first covering the subject of Geocoding Geocoding can best be described as the process of converting a textual based geographical location such as a street address into geographical coordinates expressed in terms of longitude and latitude Geocoding can be achieved using the Android Geocoder class An instance of the Geocoder class can for example be passed a string representing a location such as a city name street address or airport code The Geocoder will attempt to find a match for the location and return a list of Address objects that potentially match the location string ranked in order with the closest match at position 0 in the list A variety of information can then be extracted from the Address objects including the longitude and latitude of the potential matches The following code for example requests the location of the National Air and Space Museum in Washington D C double latitude double longitude List Address geocodeMatches null try geocodeMatches new Geocoder this getFromLocationName 600 Independence Ave SW Washington DC 20560 1 catch IOException e TODO Auto generated catch block e printStackTrace if geocodeMatches isEmpty latitude geocodeMatches get 0 getLatitude longitude geocodeMatches get 0 getLongitude Note that the value of 1 is passed through as the second argument to the getFromLocationName method This simply tells the Geocoder to return only one result in the array Given the specific nature of the address provided there should only be one potential match For more vague location names however it may be necessary to request more potential matches and allow the user to choose the correct one The above code is an example of forward geocoding in that coordinates are calculated based on a text location description Reverse geocoding as the name suggests involves the translation of geographical coordinates into a human readable address string Consider for example the following code List Address geocodeMatches null String Address1 String Address2 String State String Zipcode String Country try geocodeMatches new Geocoder this getFromLocation 38 8874245 77 0200729 1 catch IOException e TODO Auto generated catch block e printStackTrace if geocodeMatches isEmpty Address1 geocodeMatches get 0 getAddressLine 0 Address2 geocodeMatches get 0 getAddressLine 1 State geocodeMatches get 0 getAdminArea Zipcode geocodeMatches get 0 getPostalCode Country geocodeMatches get 0 getCountryName In this case the Geocoder object is initialized with latitude and longitude values via the getFromLocation method Once again only a single matching result is requested The text based address information is then extracted from the resulting Address object It should be noted that the geocoding is not actually performed on the Android device but rather on a server to which the device connects when a translation is required and the results subsequently returned when the translation is complete As such geocoding can only take place when the device has an active internet connection Adding a Map to an Application The simplest way to add a map to an application is to specify it in the user interface layout XML file for an activity The following example layout file shows a MapFragment instance added as the child of a RelativeLayout view RelativeLayout xmlns android http schemas android com apk res android xmlns tools http schemas android com tools android layout width match parent android layout height match parent tools context AndroidTestActivity fragment android id id map android layout width match parent android layout height match parent android name com google android gms maps MapFragment RelativeLayout Assuming that the onCreate method for the activity contains the standard code to load the layout resource file the application should run and display a map Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity maps demo In the event that a map is not displayed check the following areas If the application is running on an emulator make sure that the emulator is running a version of Android that includes the Google APIs Check the LogCat output for any areas relating to authentication problems with regard to the Google Maps API This usually means the API key was entered incorrectly or that the application package name does not match that specified when the API key was generated Verify that the correct entries and permissions have been added to the Manifest file including all references to the package name and API key Verify within the Google API Console that the Google Maps Android API has been enabled in the Services panel Displaying the User s Current Location The user s current location may be displayed on the map by obtaining a reference to the GoogleMap object associated with the displayed map and calling the setMyLocationEnabled method of that instance passing through a value of true The following code for example obtains a reference to the GoogleMap object from the previous example verifies that the map instance exists and then enables the My Location Layer import com google android gms maps MapFragment GoogleMap map map MapFragment getFragmentManager findFragmentById R id map getMap if map null map setMyLocationEnabled true Changing the Map Type The type of map displayed can be modified dynamically by making a call to the setMapType method of the corresponding GoogleMap object passing through one of the following values GoogleMap MAP TYPE NONE An empty grid with no mapping tiles displayed GoogleMap MAP TYPE NORMAL The standard view consisting of the classic road map GoogleMap MAP TYPE SATELLITE Displays the satellite imagery of the map region GoogleMap MAP TYPE HYBRID Displays satellite imagery with the road maps superimposed GoogleMap MAP TYPE TERRAIN Displays topographical information such as contour lines and colors The following code for example switches a map to Terrain mode map setMapType GoogleMap MAP TYPE TERRAIN Alternatively the map type may be specified in the XML layout file in which the map is embedded using the map mapType property together with a value of none normal hybrid satellite or terrain In order to be able to use this directive however it is first necessary to add the map namespace to the XML resource file in which the directives are being used xmlns map http schemas android com apk res auto For example xml version 1 0 encoding utf 8 fragment xmlns android http schemas android com apk res android xmlns map http schemas android com apk res auto android id id map android layout width match parent android layout height match parent map mapType hybrid android name com google android gms maps MapFragment Displaying Map Controls to the User The Google Maps Android API provides a number of controls that may be optionally displayed to the user consisting of zoom in and out buttons a my location button and a compass Whether or not the zoom and compass controls are displayed may be controlled either programmatically or within the map element in XML layout resources In order to configure the controls programmatically a reference to the UiSettings object associated with the GoogleMap object must be obtained UiSettings mapSettings mapSettings map getUiSettings The zoom controls are enabled and disabled via calls to the setZoomControlsEnabled method of the UiSettings object For example mapSettings setZoomControlsEnabled true Alternatively the map uiZoomControls property may be set within the map element of the XML resource file map uiZoomControls false The compass may be displayed either via a call to the setCompassEnabled method of the UiSettings instance or through XML resources using the map uiCompass property The My Location button will only appear when My Location mode is enabled as outlined earlier in this chapter The button may be prevented from appearing even when in this mode via a call to the setMyLocationButtonEnabled method of the UiSettings instance Handling Map Gesture Interaction The Google Maps Android API is capable of responding to a number of different user interactions These interactions can be used to change the area of the map displayed the zoom level and even the angle of view such that a 3D representation of the map area is displayed for certain cities Map Zooming Gestures Support for gestures relating to zooming in and out of a map may be enabled or disabled using the setZoomControlsEnabled method of the UiSettings object associated with the GoogleMap instance For example the following code enables zoom gestures for our example map UiSettings mapSettings mapSettings map getUiSettings mapSettings setZoomGesturesEnabled true The same result can be achieved within an XML resource file by setting the map uiZoomGestures property to true or false When enabled zooming will occur when the user makes pinching gestures on the screen Similarly a double tap will

    Original URL path: http://www.techotopia.com/index.php/Working_with_the_Google_Maps_Android_API (2016-02-13)
    Open archived version from archive

  • Printing with the Android Printing Framework - Techotopia
    the Android 4 4 SDK provides a number of options for incorporating print support into Android applications These options can be categorized as follows Image Printing As the name suggests this option allows image printing to be incorporated into Android applications When adding this feature to an application the first step is to create a new instance of the PrintHelper class PrintHelper imagePrinter new PrintHelper context Next the scale mode for the printed image may be specified via a call to the setScaleMode method of the PrintHelper instance Options are as follows SCALE MODE FIT The image will be scaled to fit within the paper size without any cropping or changes to aspect ratio This will typically result in white space appearing in one dimension SCALE MODE FILL The image will be scaled to fill the paper size with cropping performed where necessary to avoid the appearance of white space in the printed output In the absence of a scale mode setting the system will default to SCALE MODE FILL The following code for example sets scale to fit mode on the previously declared PrintHelper instance imagePrinter setScaleMode PrintHelper SCALE MODE FIT Similarly the color mode may also be configured to indicate whether the print output is to be in color or black and white This is achieved by passing one of the following options through to the setColorMode method of the PrintHelper instance COLOR MODE COLOR Indicates that the image is to be printed in color COLOR MODE MONOCHROME Indicates that the image is to be printed in black and white The printing framework will default to color printing unless the monochrome option is specified as follows imagePrinter setColorMode PrintHelper COLOR MODE MONOCHROME All that is required to complete the printing operation is an image to be printed and a call to the printBitmap method of the PrintHelper instance passing through a string representing the name to be assigned to the print job and a reference to the image in the form of either a Bitmap object or a Uri reference to the image Bitmap bitmap BitmapFactory decodeResource getResources R drawable oceanscene imagePrinter printBitmap My Test Print Job bitmap Once the print job has been started the Printing framework will display the print dialog and handle both the subsequent interaction with the user and the printing of the image on the user selected print destination eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Creating and Printing HTML Content The Android Printing framework also provides an easy way to print HTML based content from within an application This content can either be in the form of HTML content referenced by the URL of a page hosted on a web site or HTML content that is dynamically created within the application To enable HTML printing the WebView

    Original URL path: http://www.techotopia.com/index.php/Printing_with_the_Android_Printing_Framework (2016-02-13)
    Open archived version from archive

  • An Android HTML and Web Content Printing Example - Techotopia
    Figure 50 1 Print to a physical printer if you have one configured save to Google Drive or alternatively select the option to save to a PDF file Once the print job has been initiated check the generated output on your chosen destination Note that when using the Save to PDF option the system will request a name and location for the PDF file The Downloads folder makes a good option the contents of which can be viewed by selecting the Downloads icon located amongst the other app icons on the device Figure 50 2 for example shows the PDF output generated by the Save to PDF option viewed on an Android device Figure 50 2 Creating the Web Page Printing Example The second example application to be created in this chapter will provide the user with an Overflow menu option to print the web page currently displayed within a WebView instance Within the Eclipse environment begin this example by selecting the File New Android Application Project menu option Name the application and project WebPrint enter a suitable package name or com example webprint if you do not yet have a domain name and select API 19 or later for the SDK settings As with the HTML example request the creation of a blank activity and the use of the default launcher icons On the New Blank Activity screen of the New Android Application wizard set the Activity Name to WebPrintActivity and the Layout Name and Fragment Layout Name to activity web print and fragment web print respectively Designing the User Interface Layout Load the fragment web print xml layout resource file into the Graphical Layout editor if it has not already been loaded and select and delete the Hello World TextView object Switch to the XML view by clicking on the fragment web print xml tab located along the lower edge of the editor panel and remove the padding properties from the file so that the WebView will extend to the edges of the display when added to the layout RelativeLayout xmlns android http schemas android com apk res android xmlns tools http schemas android com tools android layout width match parent android layout height match parent tools context WebPrintActivity RelativeLayout Switch back to the graphical layout view and from the Composite section of the palette drag and drop a WebView object so that it fills the entire layout canvas as outlined in Figure 50 3 Figure 50 3 Right click on the newly added WebView instance select the Edit ID menu option and change the name of the view to myWebView before clicking on OK to commit the change Before proceeding to the next step of this tutorial an additional permission needs to be added to the project to enable the WebView object to access the internet and download a web page for printing Add this permission by locating the AndroidManifest xml file in the Project Explorer panel and double clicking on it to load it into the

    Original URL path: http://www.techotopia.com/index.php/An_Android_HTML_and_Web_Content_Printing_Example (2016-02-13)
    Open archived version from archive

  • An Android Custom Document Printing Tutorial - Techotopia
    CancellationSignal cancellationSignal LayoutResultCallback callback Bundle metadata myPdfDocument new PrintedPdfDocument context newAttributes pageHeight newAttributes getMediaSize getHeightMils 1000 72 pageWidth newAttributes getMediaSize getWidthMils 1000 72 if cancellationSignal isCanceled callback onLayoutCancelled return if totalpages 0 PrintDocumentInfo Builder builder new PrintDocumentInfo Builder print output pdf setContentType PrintDocumentInfo CONTENT TYPE DOCUMENT setPageCount totalpages PrintDocumentInfo info builder build callback onLayoutFinished info true else callback onLayoutFailed Page count is zero Clearly this method is performing quite a few tasks each of which requires some detailed explanation To begin with a new PDF document is created in the form of a PdfDocument class instance One of the arguments passed into the onLayout method when it is called by the Printing framework is an object of type PrintAttributes containing details about the paper size resolution and color settings selected by the user for the print output These settings are used when creating the PDF document along with the context of the activity previously stored for us by our constructor method myPdfDocument new PrintedPdfDocument context newAttributes The method then uses the PrintAttributes object to extract the height and width values for the document pages These dimensions are stored in the object in the form of thousandths of an inch Since the methods that will use these values later in this example work in units of 1 72 of an inch these numbers are converted before they are stored pageHeight newAttributes getMediaSize getHeightMils 1000 72 pageWidth newAttributes getMediaSize getWidthMils 1000 72 Although this example does not make use of the user s color selection this property can be obtained via a call to the getColorMode method of the PrintAttributes object which will return a value of either COLOR MODE COLOR or COLOR MODE MONOCHROME When the onLayout method is called it is passed an object of type LayoutResultCallback This object provides a way for the method to communicate status information back to the Printing framework via a set of methods The onLayout method for example will be called in the event that the user cancels the print process The fact that the process has been cancelled is indicated via a setting within the CancellationSignal argument In the event that a cancellation is detected the onLayout method must call the onLayoutCancelled method of the LayoutResultCallback object to notify the Print framework that the cancellation request was received and that the layout task has been cancelled if cancellationSignal isCanceled callback onLayoutCancelled return When the layout work is complete the method is required to call the onLayoutFinished method of the LayoutResultCallback object passing through two arguments The first argument takes the form of a PrintDocumentInfo object containing information about the document to be printed This information consists of the name to be used for the PDF document the type of content in this case a document rather than an image and the page count The second argument is a Boolean value indicating whether or not the layout has changed since the last call made to the onLayout method if totalpages 0 PrintDocumentInfo Builder builder new PrintDocumentInfo Builder print output pdf setContentType PrintDocumentInfo CONTENT TYPE DOCUMENT setPageCount totalpages PrintDocumentInfo info builder build callback onLayoutFinished info true else callback onLayoutFailed Page count is zero In the event that the page count is zero the code reports this failure to the Printing framework via a call to the onLayoutFailed method of the LayoutResultCallback object The call to the onLayoutFinished method notifies the Printing framework that the layout work is complete thereby triggering a call to the onWrite method Implementing the onWrite Callback Method The onWrite callback method is responsible for rendering the pages of the document and then notifying the Printing framework that the document is ready to be printed When completed the onWrite method reads as follows package com example customprint import java io FileOutputStream import java io IOException import android app Activity import android app ActionBar import android app Fragment import android os Bundle import android view LayoutInflater import android view Menu import android view MenuItem import android view View import android view ViewGroup import android os Build import android os CancellationSignal import android os ParcelFileDescriptor import android print PageRange import android print PrintAttributes import android print PrintDocumentAdapter import android content Context import android print PrintDocumentInfo import android print pdf PrintedPdfDocument import android graphics pdf PdfDocument import android graphics pdf PdfDocument PageInfo Override public void onWrite final PageRange pageRanges final ParcelFileDescriptor destination final CancellationSignal cancellationSignal final WriteResultCallback callback for int i 0 i totalpages i if pageInRange pageRanges i PageInfo newPage new PageInfo Builder pageWidth pageHeight i create PdfDocument Page page myPdfDocument startPage newPage if cancellationSignal isCanceled callback onWriteCancelled myPdfDocument close myPdfDocument null return drawPage page i myPdfDocument finishPage page try myPdfDocument writeTo new FileOutputStream destination getFileDescriptor catch IOException e callback onWriteFailed e toString return finally myPdfDocument close myPdfDocument null callback onWriteFinished pageRanges The onWrite method starts by looping through each of the pages in the document It is important to take into consideration however that the user may not have requested that all of the pages that make up the document be printed In actual fact the Printing framework user interface panel provides the option to specify that specific pages or ranges of pages be printed Figure 51 2 for example shows the print panel configured to print pages 1 4 pages 8 and 9 and pages 11 13 of a document Figure 51 2 eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters When writing the pages to the PDF document the onWrite method must take steps to ensure that only those pages specified by the user are printed To make this possible the Printing framework passes through as an argument an array of PageRange objects indicating the ranges of pages to be printed In the above onWrite implementation a method named pagesInRange is called for each page to verify

    Original URL path: http://www.techotopia.com/index.php/An_Android_Custom_Document_Printing_Tutorial (2016-02-13)
    Open archived version from archive

  • Handling Different Android Devices and Displays - Techotopia
    the only area of concern when adapting an application for different screen densities dimensions and aspect ratios Another area to pay attention to is that of images An image that appears correctly scaled on an large tablet screen for example might not appear correctly scaled on a smaller phone based device As with layouts however multiple sets of images can be bundled with the application each tailored for a specific display This can once again be achieved by referencing the smallest width value In this case drawable folders need to be created in the res directory For example res drawable The default image folder res drawable sw200dp res drawable sw600dp res drawable sw800dp eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Having created the folders simply place the display specific versions of the images into the corresponding folder using the same name for each of the images Alternatively the images may be categorized into broader display densities using the following directories based on the pixel density of the display res drawable ldpi Images for low density screens approx 120 dpi res drawable mdpi Images for medium density screens approx 160 dpi res drawable hdpi Images for high density screens approx 240 dpi res drawable xhdpi Images for extra high density screens approx 320 dpi res drawable tvdpi Images for displays between medium and high density approx 213 dpi res drawable nodpi Images that must not be scaled by the system Checking for Hardware Support By now it should be apparent that not all Android devices were created equal An application that makes use of specific hardware features such as a microphone or camera should include code to gracefully handle the absence of that hardware This typically involves performing a check to find out if the hardware feature is missing and subsequently reporting to the user that the corresponding application functionality will not be available The following method can be used to check for the presence of a microphone protected boolean hasMicrophone PackageManager pmanager this getPackageManager return pmanager hasSystemFeature PackageManager FEATURE MICROPHONE Similarly the following method is useful for checking for the presence of a front facing camera private boolean hasCamera if getPackageManager hasSystemFeature PackageManager FEATURE CAMERA FRONT return true else return false Providing Different Images User interface layouts are not the only area of concern when adapting an application for different screen densities dimensions and aspect ratios Another area to pay attention to is that of images An image that appears correctly scaled on an large tablet screen for example might not appear correctly scaled on a smaller phone based device As with layouts however multiple sets of images can be bundled with the application each tailored for a specific display This can once again be achieved by referencing the smallest width value In this case

    Original URL path: http://www.techotopia.com/index.php/Handling_Different_Android_Devices_and_Displays (2016-02-13)
    Open archived version from archive



  •