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".
  • Video Recording and Image Capture using Camera Intents - An Android Studio Example - Techotopia
    ACTION IMAGE CAPTURE private static 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 Android Studio 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 may then be modified to play back the recorded video Create a new project in Android Studio entering CameraApp into the Application name field and ebookfrenzy com as the Company Domain setting before clicking on the Next button On the form factors screen enable the Phone and Tablet option and set the minimum SDK setting to API 8 Android 2 2 Froyo Continue to proceed through the screens requesting the creation of a blank activity named CameraAppActivity with corresponding layout and menu resource files named activity camera app and menu camera app Designing the User Interface Layout google ADSDAQBOX FLOW google Navigate to app res layout and double click on the activity camera app xml layout file to load it into the Designer tool With the Designer tool in Design mode delete the default Hello world text view 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 Figure 48 2 Finally double click on the button and change the ID to recordButton The corresponding XML in the activity 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 paddingLeft dimen activity horizontal margin android paddingRight dimen activity horizontal margin android paddingTop dimen activity vertical margin android paddingBottom dimen activity vertical margin tools context CameraAppActivity Button android layout width wrap content android layout height wrap content android text string record string android id id recordButton android layout centerVertical true android layout centerHorizontal true android onClick startRecording RelativeLayout 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 Checking for the Camera Before attempting to launch the video capture intent the application first needs to verify that the

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


  • An Android Studio Recording and Playback Example using MediaPlayer and MediaRecorder - Techotopia
    and ebookfrenzy com as the Company Domain setting before clicking on the Next button On the form factors screen enable the Phone and Tablet option and set the minimum SDK setting to API 8 Android 2 2 Froyo Continue to proceed through the screens requesting the creation of a blank activity named AudioAppActivity with corresponding layout and menu resource files named activity audio app and menu audio app respectively Designing the User Interface Once the new project has been created select the activity audio app xml file from the Project tool window and with the Designer tool in Design mode 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 49 1 shows a suggested layout Configure the buttons to display string resources that read Play Record and Stop and give them view IDs of recordButton playButton and stopButton respectively Figure 49 1 Select the Play button and within the Properties panel configure the OnClick property 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 stopAudio respectively 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 Project tool window locate and double click on the AudioAppActivity java file and modify it to add this method package com ebookfrenzy audioapp import android support v7 app ActionBarActivity import android os Bundle import android view Menu import android view MenuItem import android content pm PackageManager public class AudioAppActivity extends ActionBarActivity Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity audio app protected boolean hasMicrophone PackageManager pmanager this getPackageManager return pmanager hasSystemFeature PackageManager FEATURE MICROPHONE Performing the Activity Initialization The next step is to modify the onCreate method of the activity to perform a number of initialization tasks Remaining within the AudioAppActivity java file modify the method as follows package com ebookfrenzy audioapp import java io IOException import android support v7 app ActionBarActivity import android os Bundle import android view Menu import android view MenuItem import android

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

  • Working with the Google Maps Android API in Android Studio - Techotopia
    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 import java io IOException import java util List import android location Address import android location Geocoder 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 import java io IOException import java util List import android location Address import android location Geocoder 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 the SupportMapFragment instance added to the activity map demo xml file created by Android Studio fragment 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 id id map tools context MapDemoActivity android name com google android gms maps SupportMapFragment 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 Edit the onCreate method in the MapDemoActivty java file to enable display of the user s current location package com ebookfrenzy mapdemo import android support v4 app FragmentActivity import android os Bundle import com google android gms maps GoogleMap import com google android gms maps SupportMapFragment import com google android gms maps model LatLng import com google android gms maps model MarkerOptions public class MapDemoActivity extends FragmentActivity private GoogleMap mMap Might be null if Google Play services APK is not available Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity map demo setUpMapIfNeeded if mMap null mMap setMyLocationEnabled true 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 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 change to the onCreate method for example switches a map to Terrain mode Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity map demo setUpMapIfNeeded if mMap null mMap setMyLocationEnabled true mMap 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 SupportMapFragment 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

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

  • Printing with the Android Printing Framework in Android Studio - Techotopia
    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 class has been extended in Android 4 4 to include support for printing with minimal coding requirements When dynamically creating HTML content as opposed to loading and printing an existing web page the process involves the creation of a WebView object and associating with it a WebViewClient instance The web view client is then configured to start a print job when the HTML has finished being loaded into the WebView With the web view client configured the HTML is then loaded into the

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

  • An Android Studio HTML and Web Content Printing Example - Techotopia
    be viewed by selecting the Downloads icon located amongst the other app icons on the device Figure 59 2 for example shows the PDF output generated by the Save to PDF option viewed on an Android device Figure 59 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 Create a new project in Android Studio entering WebPrint into the Application name field and ebookfrenzy com as the Company Domain setting before clicking on the Next button On the form factors screen enable the Phone and Tablet option and set the minimum SDK setting to API 21 Android 5 0 Lollipop Continue to proceed through the screens requesting the creation of a blank activity since we will be making use of the context menu provided by the blank activity template named WebPrintActivity with the remaining properties set to the default values Removing the Floating Action Button Selecting the Blank Activity template provided a context menu and a floating action button Since the floating action button is not required by the app it can be removed before proceeding Load the activity web print xml layout file into the Designer select the floating action button and tap the keyboard Delete key to remove the object from the layout Edit the WebPrintActivity java file and remove the floating action button code from the onCreate method as follows Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity web print Toolbar toolbar Toolbar findViewById R id toolbar setSupportActionBar toolbar FloatingActionButton fab FloatingActionButton findViewById R id fab fab setOnClickListener new View OnClickListener Override public void onClick View view Snackbar make view Replace with your own action Snackbar LENGTH LONG setAction Action null show Designing the User Interface Layout Load the content web print xml layout resource file into the Designer tool if it has not already been loaded and in Design mode select and delete the Hello World TextView object Switch to the XML view by clicking on the Text tab located along the lower edge of the Designer 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 android paddingLeft dimen activity horizontal margin android paddingRight dimen activity horizontal margin android paddingTop dimen activity vertical margin android paddingBottom dimen activity vertical margin tools context WebPrintActivity RelativeLayout Switch back to Design mode and from the Widgets section of the palette drag and drop a WebView object onto the center of the device screen layout Using either the Properties panel or the Designer toolbar buttons change the layout width and layout height properties of the WebView to match parent so that it fills

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

  • An Android Studio Custom Document Printing Example - Techotopia
    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 ebookfrenzy customprint import java io FileOutputStream import java io IOException import android app Activity import android os Bundle import android view Menu import android view MenuItem 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 53 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 53 2 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 that the page is within the specified ranges The code for the pagesInRange method will be implemented later in this chapter for int i 0 i totalpages i if pageInRange pageRanges i For each page that is within any specified ranges a new PdfDocument Page object is created When creating a new page the height and width values previously stored by the onLayout method are passed through as arguments so that the page size matches

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

  • Generating a Signed Release APK File in Android Studio - Techotopia
    which will be used to sign the application package Within the Key section of the New Key Store dialog enter the following details An alias by which the key will be referenced This can be any sequence of characters though only the first 8 are used by the system A suitably strong password to protect the key The number of years for which the key is to be valid Google recommends a duration in excess of 27 years In addition information must be provided for at least one of the remaining fields for example your first and last name or organization name Figure 54 5 Once the information has been entered click on the Next button to proceed with the package creation Creating the Application APK File The next task to be performed is to instruct Android Studio to build the application APK package file in release mode and then sign it with the newly created private key At this point the Generate Signed APK Wizard dialog should still be displayed with the keystore path passwords and key alias fields populated with information Figure 54 6 Assuming that the settings are correct click on the Next button to proceed to the APK generation screen Figure 54 7 Within this screen review the Destination APK path setting to verify that the location into which the APK file will be generated is acceptable In the event that another location is preferred click on the button to the right of the text field and navigate to the desired file system location Figure 54 7 Enable the Run ProGuard checkbox ProGuard performs a series of optimization and verification tasks that result in smaller and more efficient byte code before clicking on the Finish button At this point the Gradle system will compile the application in release mode Once the build is complete a dialog will appear providing the option to open the folder containing the APK file in an explorer window Figure 54 8 At this point the application is ready to be submitted to the Google Play store The private key generated as part of this process should be used when signing and releasing future applications and as such should be kept in a safe place and securely backed up The final step in the process of bringing an Android application to market involves submitting it to the Google Play Developer Console Once submitted the application will be available for download from the Google Play App 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 Register for a Google Play Developer Console Account The first step in the application submission process is to create a Google Play Developer Console account To do so navigate to https play google com apps publish signup and follow the instructions to complete the

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

  • An Android Studio Google Play In-app Billing Tutorial - Techotopia
    string click string android id id clickButton android layout above id buyButton android layout centerHorizontal true android layout marginBottom 83dp android onClick buttonClicked RelativeLayout With the user interface design complete it is time to start writing some Java code to handle the purchasing and consumption of clicks Implementing the Click Me Button When the application is initially launched the Click Me button will be disabled To make sure that this happens load the InAppBillingActivity java file into the editor and modify the onCreate method to obtain a reference to both buttons and then disable the clickButton package com ebookfrenzy inappbilling import android app Activity import android os Bundle import android view Menu import android view MenuItem import android widget Button public class InAppBillingActivity extends Activity private Button clickButton private Button buyButton Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity in app billing buyButton Button findViewById R id buyButton clickButton Button findViewById R id clickButton clickButton setEnabled false The buttonClicked method that will be called when the button is clicked by the user now also needs to be implemented All this method needs to do is to disable the button once again so that the button cannot be clicked until another purchase is made and to enable the buy button so that another click can be purchased Remaining within the InAppBillingActivity java file implement this method as follows package com ebookfrenzy inappbilling import android app Activity import android os Bundle import android view Menu import android view MenuItem import android widget Button import android view View public class InAppBillingActivity extends Activity public void buttonClicked View view clickButton setEnabled false buyButton setEnabled true Work on the functionality of the first button is now complete The next steps are to begin implementing the in app billing functionality Google Play Developer Console and Google Wallet Accounts Application developers making use of Google Play billing must be identified by a unique public license key The only way to obtain a public license key is to register an application within the Google Play Developer Console If you do not already have a Google Play Developer Console account go to http play google com apps publish and follow the steps to register as outlined in the chapter entitled Generating a Signed Release APK File in Android Studio Once you are logged in click on the Settings option represented by the cog icon on the left hand edge of the web page and on the Account details page scroll down to the Merchant Account section In order to use in app billing your Google Play Developer Console account must have a Google Wallet Merchant account associated with it If a Google Wallet merchant account is not set up create a merchant account and register it with your Google Developer Console account before proceeding Obtaining the Public License Key for the Application From the home page of the Google Play Developer Console click on the Add new application button specifying the default language and a title of InAppBilling Once this information has been entered click on the Upload APK button Figure 55 6 It is not necessary to upload the APK file at this point so once the application has been registered click on the Services APIs option to display the Base64 encoded RSA public key for the application as shown in Figure 55 7 Figure 55 7 Keep this Browser window open for now as this key will need to be included in the application code in the next step of this tutorial Setting Up Google Play Billing in the Application With the public key generated it is now time to use that key to initialize billing within the application code For the InAppBilling example project this will be performed in the onCreate method of the InAppBillingActivity java file and will make use of the IabHelper class from the utilities classes previously added to the project as follows Note that your license key here should be replaced by your own license key generated in the previous section package com ebookfrenzy inappbilling import your domain inappbilling util IabHelper import your domain inappbilling inappbilling util IabResult import your domain inappbilling inappbilling util Inventory import your domain inappbilling inappbilling util Purchase import android app Activity import android os Bundle import android view Menu import android view MenuItem import android widget Button import android view View import android content Intent import android util Log public class InAppBillingActivity extends Activity private static final String TAG com ebookfrenzy inappbilling IabHelper mHelper private Button clickButton private Button buyButton Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity in app billing buyButton Button findViewById R id buyButton clickButton Button findViewById R id clickButton clickButton setEnabled false String base64EncodedPublicKey your license key here mHelper new IabHelper this base64EncodedPublicKey mHelper startSetup new IabHelper OnIabSetupFinishedListener public void onIabSetupFinished IabResult result if result isSuccess Log d TAG In app Billing setup failed result else Log d TAG In app Billing is set up OK After implementing the above changes compile and run the application on a physical Android device Google Play Billing cannot be tested within an emulator session and make sure that the In app Billing is set up OK message appears in the LogCat output panel Initiating a Google Play In app Billing Purchase With access to the billing system initialized we can now turn our attention to initiating a purchase when the user touches the Buy Click button in the user interface This was previously configured to trigger a call to a method named buyClick which now needs to be implemented in the InAppBillingActivity java file In addition to initiating the purchase process in this method it will be necessary to implement an onActivityResult method and also a listener method to be called when the purchase has completed Begin by editing the InAppBillingActivity java file and adding the code for the buyClick method so that it reads as follows public class InAppBillingActivity extends Activity private static final String TAG com example inappbilling IabHelper mHelper static final String ITEM SKU android test purchased public void buyClick View view mHelper launchPurchaseFlow this ITEM SKU 10001 mPurchaseFinishedListener mypurchasetoken Clearly all this method needs to do is make a call to the launchPurchaseFlow method of our mHelper instance The arguments passed through to the method are as follows A reference to the enclosing Activity instance from which the method is being called The SKU that identifies the product that is being purchased In this instance we are going to use a standard SKU provided by Google for testing purposes This SKU referred to as a static response SKU will always result in a successful purchase Other testing SKUs available for use when testing purchasing functionality without making real purchases are android test cancelled android test refunded and android test item unavailable The request code which can be any positive integer value When the purchase has completed the onActivityResult method will be called and passed this integer along with the purchase response This allows the method to identify which purchase process is returning and can be useful when the method needs to be able to handle purchasing for different items The listener method to be called when the purchase is complete The developer payload token string This can be any string value and is used to identify the purchase For the purposes of this example this is set to mypurchasetoken Implementing the onActivityResult Method When the purchasing process returns it will call a method on the calling activity named onActivityResult passing through as arguments the request code passed through to the launchPurchaseFlow method a result code and intent data containing the purchase response This method needs to identify if it was called as a result of an in app purchase request or some request unrelated to in app billing It does this by calling the handleActivityResult method of the mHelper instance and passing through the incoming arguments If this is a purchase request the mHelper will handle it and return a true value If this is not the result of a purchase then the method needs to pass it up to the superclass to be handled Bringing this together results in the following code Override protected void onActivityResult int requestCode int resultCode Intent data if mHelper handleActivityResult requestCode resultCode data super onActivityResult requestCode resultCode data In the event that the onActivityResult method was called in response to an in app billing purchase a call will then be made to the listener method referenced in the call to the launchPurchaseFlow method in this case a method named mPurchaseFinishedListener The next task therefore is to implement this method 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 Implementing the Purchase Finished Listener The purchase finished listener must perform a number of different tasks In the first instance it must check to ensure that the purchase was successful It then needs to check the SKU of the purchased item to make sure it matches the one specified in the purchase request In the event of a successful purchase the method will need to consume the purchase so that the user can purchase it again when another one is needed If the purchase is not consumed future attempts to purchase the item will fail stating that the item has already been purchased Whilst this would be desired behavior if the user only needed to purchase the item once clearly this is not the behavior required for consumable purchases Finally the method needs to enable the Click Me button so that the user can perform the button click that was purchased Within the InAppBillingActivity java file implement this method as follows IabHelper OnIabPurchaseFinishedListener mPurchaseFinishedListener new IabHelper OnIabPurchaseFinishedListener public void onIabPurchaseFinished IabResult result Purchase purchase if result isFailure Handle error return else if purchase getSku equals ITEM SKU consumeItem buyButton setEnabled false As can be seen from the above code fragment in the event that the purchase was successful a method named consumeItem will be called Clearly the next step is to implement this method Consuming the Purchased Item In the documentation for Google Play In app Billing Google recommends that consumable items be consumed before providing the user with access to the purchased item So far in this tutorial we have performed the purchase of the item but not yet consumed it In the event of a successful purchase the mPurchaseFinishedListener implementation has been configured to call a method named consumeItem It will be the responsibility of this method to query the billing system to make sure that the purchase has been made This involves making a call to the queryInventoryAsync method of the mHelper object This task is performed asynchronously from the application s main thread and a listener method called when the task is complete If the item has been purchased the listener will consume the item via a call to the consumeAsync method of the mHelper object Bringing these requirements together results in the following additions to the InAppBillingActivity java file public void consumeItem mHelper queryInventoryAsync mReceivedInventoryListener IabHelper QueryInventoryFinishedListener mReceivedInventoryListener new IabHelper QueryInventoryFinishedListener public void onQueryInventoryFinished IabResult result Inventory inventory if result isFailure Handle failure else mHelper consumeAsync inventory getPurchase ITEM SKU mConsumeFinishedListener As with the query the consumption task is also performed asynchronously and in this case is configured to call a listener named mConsumeFinishedListener when completed This listener now needs to be implemented such that it enables the Click Me button after the item has been consumed in the billing system IabHelper OnConsumeFinishedListener mConsumeFinishedListener new IabHelper OnConsumeFinishedListener public void onConsumeFinished Purchase purchase IabResult result if result isSuccess clickButton setEnabled true else handle error Releasing the IabHelper Instance Throughout this tutorial much of the work has been performed by calling methods on an instance of the IabHelper utility class named mHelper Now that the code to handle purchasing and subsequent consumption of a virtual item is complete the last task is to make sure this object is released when the activity is destroyed Remaining in the InAppBillingActivity java override the onDestroy activity lifecycle method as follows Override public void onDestroy super onDestroy if mHelper null mHelper dispose mHelper null Modifying the Security java File When an application is compiled and installed on a device from within Android Studio it is built and executed in debug mode When the application is complete it is then built in release mode and uploaded to the Google Play App Store as described in the chapter entitled Generating a Signed Release APK File in Android Studio As the InAppBilling application is currently configured purchases are being made using the android test purchased static response SKU code It is important to be aware that static response SKUs can only be used when running an application in debug mode As will be outlined later new in app products must be created within the Google Play Developer Console before full testing can be performed in release mode The current version of the utility classes provided with the TrivialDrive example application include an added level of security that prevents purchases from being made without a valid signature key being returned from the Google Play billing server A side effect of this change is that it prevents the code from functioning when using the static response SKU values Before testing the application in debug mode therefore a few extra lines of code need to be added to the verifyPurchase method in the Security java file Within the Android Studio Project tool window select the Security java file located in the app java package name util folder of the project to load it into the editor Once loaded locate and modify the verifyPurchase method so that it reads as follows package com ebookfrenzy inappbilling util import android text TextUtils import android util Log import org json JSONException import org json JSONObject import com ebookfrenzy inappbilling BuildConfig import java security InvalidKeyException import java security KeyFactory import java security NoSuchAlgorithmException import java security PublicKey import java security Signature import java security SignatureException import java security spec InvalidKeySpecException import java security spec X509EncodedKeySpec public static boolean verifyPurchase String base64PublicKey String signedData String signature if TextUtils isEmpty signedData TextUtils isEmpty base64PublicKey TextUtils isEmpty signature Log e TAG Purchase verification failed missing data if BuildConfig DEBUG return true return false PublicKey key Security generatePublicKey base64PublicKey return Security verify key signedData signature This will ensure that when the application is running in debug mode the method does not report an error if the signature is missing when a static response SKU purchase is verified By checking for debug mode in this code we ensure that this security check will function as intended when the application is built in release mode Testing the In app Billing Application Compile and run the application on a physical Android device with Google Play support and click on the Buy a Click button This should cause the Google Play purchase dialog to appear listing the test item as illustrated in Figure 55 8 Figure 55 8 Click on the Buy button to simulate a purchase at which point a Payment Successful message Figure 55 9 should appear after which it should be possible to click on the Click Me button once Figure 55 9 Having consumed the click it will be necessary to purchase another click in order to once again enable the button Building a Release APK Up until this point the example application created in this chapter has used a static response testing SKU provided by Google for early stage testing of in app billing The next step is to create a real in app billing product SKU code for a virtual item and use this when testing the application Before creating an in app billing product however the application code needs to be changed slightly so that it uses a real SKU instead of the static response SKU The product SKU that will be used in the remainder of this chapter will be named com example buttonclick so edit the InAppBillingActivity java file and modify the SKU reference accordingly public class InAppBillingActivity extends Activity private static final String TAG com ebookfrenzy inappbilling IabHelper mHelper static final String ITEM SKU com example buttonclick private Button clickButton private Button buyButton Before any products can be created a release APK file for the application must first be uploaded to the developer console In order to prepare this release APK file for the InAppBilling application follow the steps outlined in the chapter entitled Generating a Signed Release APK File in Android Studio Once the APK file has been created select the previously registered application from the list of applications in the Google Play Developer Console and from the resulting screen click on the APK link in the left hand panel When prompted upload the release APK file to the console Creating a New In app Product Once the APK file has been uploaded select the In app Products menu item from the left hand panel of the developer console to display the screen shown in Figure 55 10 Figure 55 10 To add a new product click on the Add new product button and in the resulting panel set the product type to Managed product and enter a Product ID in this case com example buttonclick Click on Continue and in the second screen enter a title description and price for the item Change the menu at the top of the page to Activate On returning to the In app Products home screen the new product should now be listed Figure 55 11 Publishing the Application to the Alpha Distribution Channel The application APK file is currently stored within the Google Play Developer Console in Draft mode Before it can be used for further testing using real in app products the application must be

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



  •