Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android Studio 4.1 Development Essentials – Java Edition

You're reading from  Android Studio 4.1 Development Essentials – Java Edition

Product type Book
Published in May 2021
Publisher Packt
ISBN-13 9781801815161
Pages 810 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (88) Chapters

1. Introduction 2. Setting up an Android Studio Development Environment 3. Creating an Example Android App in Android Studio 4. Creating an Android Virtual Device (AVD) in Android Studio 5. Using and Configuring the Android Studio AVD Emulator 6. A Tour of the Android Studio User Interface 7. Testing Android Studio Apps on a Physical Android Device 8. The Basics of the Android Studio Code Editor 9. An Overview of the Android Architecture 10. The Anatomy of an Android Application 11. An Overview of Android View Binding 12. Understanding Android Application and Activity Lifecycles 13. Handling Android Activity State Changes 14. Android Activity State Changes by Example 15. Saving and Restoring the State of an Android Activity 16. Understanding Android Views, View Groups and Layouts 17. A Guide to the Android Studio Layout Editor Tool 18. A Guide to the Android ConstraintLayout 19. A Guide to using ConstraintLayout in Android Studio 20. Working with ConstraintLayout Chains and Ratios in Android Studio 21. An Android Studio Layout Editor ConstraintLayout Tutorial 22. Manual XML Layout Design in Android Studio 23. Managing Constraints using Constraint Sets 24. An Android ConstraintSet Tutorial 25. A Guide to using Apply Changes in Android Studio 26. An Overview and Example of Android Event Handling 27. Android Touch and Multi-touch Event Handling 28. Detecting Common Gestures using the Android Gesture Detector Class 29. Implementing Custom Gesture and Pinch Recognition on Android 30. An Introduction to Android Fragments 31. Using Fragments in Android Studio - An Example 32. Modern Android App Architecture with Jetpack 33. An Android Jetpack ViewModel Tutorial 34. An Android Jetpack LiveData Tutorial 35. An Overview of Android Jetpack Data Binding 36. An Android Jetpack Data Binding Tutorial 37. An Android ViewModel Saved State Tutorial 38. Working with Android Lifecycle-Aware Components 39. An Android Jetpack Lifecycle Awareness Tutorial 40. An Overview of the Navigation Architecture Component 41. An Android Jetpack Navigation Component Tutorial 42. Creating and Managing Overflow Menus on Android 43. An Introduction to MotionLayout 44. An Android MotionLayout Editor Tutorial 45. A MotionLayout KeyCycle Tutorial 46. Working with the Floating Action Button and Snackbar 47. Creating a Tabbed Interface using the TabLayout Component 48. Working with the RecyclerView and CardView Widgets 49. An Android RecyclerView and CardView Tutorial 50. A Layout Editor Sample Data Tutorial 51. Working with the AppBar and Collapsing Toolbar Layouts 52. An Android Studio Master/Detail Flow Tutorial 53. An Overview of Android Intents 54. Android Explicit Intents – A Worked Example 55. Android Implicit Intents – A Worked Example 56. Android Broadcast Intents and Broadcast Receivers 57. A Basic Overview of Threads and AsyncTasks 58. An Overview of Android Started and Bound Services 59. Implementing an Android Started Service – A Worked Example 60. Android Local Bound Services – A Worked Example 61. Android Remote Bound Services – A Worked Example 62. An Android Notifications Tutorial 63. An Android Direct Reply Notification Tutorial 64. Foldable Devices and Multi-Window Support 65. An Overview of Android SQLite Databases 66. The Android Room Persistence Library 67. An Android TableLayout and TableRow Tutorial 68. An Android Room Database and Repository Tutorial 69. Accessing Cloud Storage using the Android Storage Access Framework 70. An Android Storage Access Framework Example 71. Video Playback on Android using the VideoView and MediaController Classes 72. Android Picture-in-Picture Mode 73. An Android Picture-in-Picture Tutorial 74. Making Runtime Permission Requests in Android 75. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 76. Working with the Google Maps Android API in Android Studio 77. Printing with the Android Printing Framework 78. An Android HTML and Web Content Printing Example 79. A Guide to Android Custom Document Printing 80. An Introduction to Android App Links 81. An Android Studio App Links Tutorial 82. A Guide to the Android Studio Profiler 83. An Android Biometric Authentication Tutorial 84. Creating, Testing and Uploading an Android App Bundle 85. An Overview of Android Dynamic Feature Modules 86. An Android Studio Dynamic Feature Tutorial 87. An Overview of Gradle in Android Studio Index

79. A Guide to Android Custom Document Printing

As we have seen in the preceding chapters, the Android Printing framework makes it relatively easy to build printing support into applications as long as the content is in the form of an image or HTML markup. More advanced printing requirements can be met by making use of the custom document printing feature of the Printing framework.

79.1 An Overview of Android Custom Document Printing

In simplistic terms, custom document printing uses canvases to represent the pages of the document to be printed. The application draws the content to be printed onto these canvases in the form of shapes, colors, text and images. In actual fact, the canvases are represented by instances of the Android Canvas class, thereby providing access to a rich selection of drawing options. Once all the pages have been drawn, the document is then printed.

While this sounds simple enough, there are actually a number of steps that need to be performed to make this happen, which can be summarized as follows:

Implement a custom print adapter sub-classed from the PrintDocumentAdapter class

Obtain a reference to the Print Manager Service

Create an instance of the PdfDocument class in which to store the document pages

Add pages to the PdfDocument in the form of PdfDocument.Page instances

Obtain...

79.2 Preparing the Custom Document Printing Project

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Empty Activity template before clicking on the Next button.

Enter CustomPrint into the Name field and specify com.ebookfrenzy.customprint as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Java.

Load the activity_main.xml layout file into the Layout Editor tool and, in Design mode, select and delete the “Hello World!” TextView object. Drag and drop a Button view from the Form Widgets section of the palette and position it in the center of the layout view. With the Button view selected, change the text property to “Print Document” and extract the string to a new resource. On completion, the user interface layout should match that shown in Figure 79-1:

Figure 79-1

...

79.3 Creating the Custom Print Adapter

Most of the work involved in printing a custom document from within an Android application involves the implementation of the custom print adapter. This example will require a print adapter with the onLayout() and onWrite() callback methods implemented. Within the MainActivity.java file, add the template for this new class so that it reads as follows:

package com.ebookfrenzy.customprint;

.

.

import android.os.CancellationSignal;

import android.os.ParcelFileDescriptor;

import android.print.PageRange;

import android.print.PrintAttributes;

import android.print.PrintDocumentAdapter;

import android.content.Context;

 

public class MainActivity extends AppCompatActivity {

 

    public static class MyPrintDocumentAdapter extends PrintDocumentAdapter

    {

        Context context;

 

    &...

79.4 Implementing the onLayout() Callback Method

Remaining within the MainActivity.java file, begin by adding some import directives that will be required by the code in the onLayout() method:

package com.ebookfrenzy.customprint;

.

.

import android.print.PrintDocumentInfo;

import android.print.pdf.PrintedPdfDocument;

import android.graphics.pdf.PdfDocument;

 

public class MainActivity extends AppCompatActivity {

.

.

}

Next, modify the MyPrintDocumentAdapter class to declare variables to be used within the onLayout() method:

public static class MyPrintDocumentAdapter extends PrintDocumentAdapter

{

       Context context;

       int pageHeight;

       int pageWidth;

       PdfDocument myPdfDocument;

       int totalpages = 4;

.

.

}

Note that...

79.5 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.graphics.pdf.PdfDocument.PageInfo;

.

.

@Override

public void onWrite(final PageRange[] pageRanges,

                   final ParcelFileDescriptor destination,

                   final CancellationSignal cancellationSignal,

                   final WriteResultCallback callback...

79.6 Checking a Page is in Range

As previously outlined, when the onWrite() method is called it is passed an array of PageRange objects indicating the ranges of pages within the document that are to be printed. The PageRange class is designed to store the start and end pages of a page range which, in turn, may be accessed via the getStart() and getEnd() methods of the class.

When the onWrite() method was implemented in the previous section, a call was made to a method named pageInRange(), which takes as arguments an array of PageRange objects and a page number. The role of the pageInRange() method is to identify whether the specified page number is within the ranges specified and may be implemented within the MyPrintDocumentAdapter class in the MainActivity.java class as follows:

public class MyPrintDocumentAdapter extends PrintDocumentAdapter {

.

.

       private boolean pageInRange(PageRange[] pageRanges, int page)

  ...

79.7 Drawing the Content on the Page Canvas

We have now reached the point where some code needs to be written to draw the content on the pages so that they are ready for printing. The content that gets drawn is completely application specific and limited only by what can be achieved using the Android Canvas class. For the purposes of this example, however, some simple text and graphics will be drawn on the canvas.

The onWrite() method has been designed to call a method named drawPage() which takes as arguments the PdfDocument.Page object representing the current page and an integer representing the page number. Within the MainActivity.java file this method should now be implemented as follows:

package com.ebookfrenzy.customprint;

.

.

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

 

public class MainActivity extends AppCompatActivity {

.

.

       public static class...

79.8 Starting the Print Job

When the “Print Document” button is touched by the user, the printDocument() onClick event handler method will be called. All that now remains before testing can commence, therefore, is to add this method to the MainActivity.java file, taking particular care to ensure that it is placed outside of the MyPrintDocumentAdapter class:

package com.ebookfrenzy.customprint;

.

.

import android.print.PrintManager;

import android.view.View;

 

public class MainActivity extends AppCompatActivity {

 

       public void printDocument(View view)

       {

           PrintManager printManager = (PrintManager) this

                   .getSystemService(Context.PRINT_SERVICE);

 

  ...

79.9 Testing the Application

Compile and run the application on an Android device or emulator that is running Android 4.4 or later. When the application has loaded, touch the “Print Document” button to initiate the print job and select a suitable target for the output (the Save to PDF option is a useful option for avoiding wasting paper and printer ink).

Check the printed output which should consist of 4 pages including text and graphics. Figure 79-3, for example, shows the four pages of the document viewed as a PDF file ready to be saved on the device.

Experiment with other print configuration options such as changing the paper size, orientation and pages settings within the print panel. Each setting change should be reflected in the printed output, indicating that the custom print document adapter is functioning correctly.

Figure 79-3

79.10 Summary

Although more complex to implement than the Android Printing framework HTML and image printing options, custom document printing provides considerable flexibility in terms of printing complex content from within an Android application. The majority of the work involved in implementing custom document printing involves the creation of a custom Print Adapter class such that it not only draws the content on the document pages, but also responds correctly as changes are made by the user to print settings such as the page size and range of pages to be printed.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021 Publisher: Packt ISBN-13: 9781801815161
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}