Palm OS ® Programming Bible will show you how to create applications for Palm’s popular line of handheld organizers, as well as third-party devices that also run thePalm OS.. You will al
Trang 1Palm OS®
Programming Bible
Trang 3Palm OS ®
Programming Bible
Lonnon R Foster
IDG Books Worldwide, Inc
An International Data Group CompanyFoster City, CA ✦ Chicago, IL ✦ Indianapolis, IN ✦ New York, NY
Trang 4Foster City, CA 94404
www.idgbooks.com (IDG Books Worldwide Web site) Copyright © 2000 IDG Books Worldwide, Inc All rights reserved No part of this book, including interior design, cover design, and icons, may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without the prior written permission of the publisher.
ISBN: 0-7645-4676-7 Printed in the United States of America
10 9 8 7 6 5 4 3 2 1 1B/QW/RR/QQ/FC Distributed in the United States by IDG Books Worldwide, Inc.
Distributed by CDG Books Canada Inc for Canada;
by Transworld Publishers Limited in the United Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for Sweden; by IDG Books Australia Publishing Corporation Pty Ltd for Australia and New Zealand; by TransQuest Publishers Pte Ltd for Singapore, Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc for Taiwan; by ICG Muse, Inc for Japan; by Intersoft for South Africa;
by Eyrolles for France; by International Thomson Publishing for Germany, Austria, and Switzerland;
by Distribuidora Cuspide for Argentina; by LR International for Brazil; by Galileo Libros for Chile;
by Ediciones ZETA S.C.R Ltda for Peru; by WS Computer Publishing Corporation, Inc., for the Philippines; by Contemporanea de Ediciones for Venezuela; by Express Computer Distributors for the Caribbean and West Indies; by Micronesia Media Distributor, Inc for Micronesia; by Chips Computadoras S.A de C.V for Mexico; by Editorial Norma de Panama S.A for Panama; by American Bookshops for Finland.
department at 800-434-3422.
For information on where to purchase IDG Books Worldwide’s books outside the U.S., please contact our International Sales department at 317-596-5530
or fax 317-572-4002.
For consumer information on foreign language translations, please contact our Customer Service department at 800-434-3422, fax 317-572-4002, or e-mail rights@idgbooks.com.
For information on licensing foreign or domestic rights, please phone +1-650-653-7098.
For sales inquiries and special prices for bulk quantities, please contact our Order Services department at 800-434-3422 or write to the address above.
For information on using IDG Books Worldwide’s books in the classroom or for ordering examination copies, please contact our Educational Sales department at 800-434-2086 or fax 317-572-4005 For press review copies, author interviews, or other publicity information, please contact our Public Relations department at 650-653-7000 or fax 650-653-7500.
For authorization to photocopy items for corporate, personal, or educational use, please contact Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, or fax 978-750-4470.
Library of Congress Cataloging-in-Publication Data
Foster, Lonnon R., Palm OS programming Bible / Lonnon R Foster.
1972-p cm.
ISBN 0-7645-4676-7 (alk paper)
1 Palm OS 2 PalmPilot (Computer) Programming.
I Title.
QA76.76.O63 F685 2000 005.26'8- -dc21 00-044954
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK THE PUBLISHER AND AUTHOR MAKE NO REPRESENTATIONS
OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS PARAGRAPH NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES
Trademarks: All brand names and product names used in this book are trade names, service marks,
trademarks, or registered trademarks of their respective owners IDG Books Worldwide is not associated with any product or vendor mentioned in this book.
is a registered trademark or trademark under exclusive license
to IDG Books Worldwide, Inc from International Data Group, Inc
in the United States and/or other countries.
Trang 5Eleventh Annual Computer Press Awards 1995 Tenth Annual
Computer Press Awards 1994
Eighth Annual Computer Press Awards 1992 Ninth Annual
Computer Press Awards 1993
IDG is the world’s leading IT media, research and exposition company Founded in 1964, IDG had 1997 revenues of $2.05 billion and has more than 9,000 employees worldwide IDG offers the widest range of media options that reach IT buyers
in 75 countries representing 95% of worldwide IT spending IDG’s diverse product and services portfolio spans six key areas including print publishing, online publishing, expositions and conferences, market research, education and training, and global marketing services More than 90 million people read one or more of IDG’s 290 magazines and newspapers, including IDG’s leading global brands — Computerworld, PC World, Network World, Macworld and the Channel World family of publications IDG Books Worldwide is one of the fastest-growing computer book publishers in the world, with more than
700 titles in 36 languages The “ For Dummies ® ” series alone has more than 50 million copies in print IDG offers online users the largest network of technology-specific Web sites around the world through IDG.net (http://www.idg.net), which comprises more than 225 targeted Web sites in 55 countries worldwide International Data Corporation (IDC) is the world’s largest provider of information technology data, analysis and consulting, with research centers in over 41 countries and more than 400 research analysts worldwide IDG World Expo is a leading producer of more than 168 globally branded conferences and expositions in 35 countries including E3 (Electronic Entertainment Expo), Macworld Expo, ComNet, Windows World Expo, ICE (Internet Commerce Expo), Agenda, DEMO, and Spotlight IDG’s training subsidiary, ExecuTrain, is the world’s largest computer training company, with more than 230 locations worldwide and 785 training courses IDG Marketing Services helps industry-leading IT companies build international brand recognition by developing global integrated marketing programs via IDG’s print, online and exposition products worldwide Further information about the company can be found
Welcome to the world of IDG Books Worldwide.
IDG Books Worldwide, Inc., is a subsidiary of International Data Group, the world’s largest publisher of computer-related information and the leading global provider of information services on information technology IDG was founded more than 30 years ago by Patrick J McGovern and now employs more than 9,000 people worldwide IDG publishes more than 290 computer publications in over 75 countries More than 90 million people read one or more IDG publications each month.
Launched in 1990, IDG Books Worldwide is today the #1 publisher of best-selling computer books in the United States We are proud to have received eight awards from the Computer Press Association in recognition
of editorial excellence and three from Computer Currents’ First Annual Readers’ Choice Awards Our
best-selling For Dummies ® series has more than 50 million copies in print with translations in 31 languages IDG Books Worldwide, through a joint venture with IDG’s Hi-Tech Beijing, became the first U.S publisher to publish a computer book in the People’s Republic of China In record time, IDG Books Worldwide has become the first choice for millions of readers around the world who want to learn how to better manage their businesses.
Our mission is simple: Every one of our books is designed to bring extra value and skill-building instructions
to the reader Our books are written by experts who understand and care about our readers The knowledge base of our editorial staff comes from years of experience in publishing, education, and journalism — experience we use to produce books to carry us into the new millennium In short, we care about books, so
we attract the best people We devote special attention to details such as audience, interior design, use of icons, and illustrations And because we use an efficient process of authoring, editing, and desktop publishing our books electronically, we can spend more time ensuring superior content and less time on the technicalities
of making books.
You can count on our commitment to deliver high-quality books at competitive prices on topics you want
to read about At IDG Books Worldwide, we continue in the IDG tradition of delivering quality for more than
30 years You’ll find no better book on a subject than one from IDG Books Worldwide.
John Kilcullen Chairman and CEO IDG Books Worldwide, Inc.
Trang 6Acquisitions Editors
John OsbornGreg Croy
Project Coordinators
Joe ShinesDanette Nurse
Graphics and Production Specialists
Robert BihlmayerJude LevinsonMichael LewisVictor Pérez-VarelaRamses Ramirez
Quality Control Technician
Dina F Quan
Illustrators
Rashell SmithKarl BrandtGabriele McCann
Proofreading and Indexing
York Production Services
Cover Image
Evan Deerfield
About the Author
Lonnon R Foster is a freelance programmer who has spent the past seven years
cre-ating desktop applications, database front ends, Web sites, communications software,technical documentation, and handheld applications He has been developing Palm
OS applications almost as long as the platform has existed, starting with his first Pilot
5000 Lonnon fills his sparse free time with tactical tabletop gaming, recreational Perlcoding, and reading everything he can get his hands on
Trang 7For Elisabeth, who believed from the very start that I could do it
Trang 9In 1992, Palm Computing (now Palm, Inc.) was founded The rest is history Of
course, there’s a lot more to it Many good decisions were made, and many baddesigns were thrown out Palm started as a software company intending to influenceexisting handheld manufacturers with its easy-to-use software and synchronizationtechnologies The company soon realized two things The first was that the hard-ware manufacturers didn’t seem to believe in Palm’s philosophy The second wasthat it was difficult to make a viable business just writing software for this small market Palm realized that its first take at this company was not the right one anddecided to become the master of its destiny The name was Pilot Palm changed thefocus of its business virtually overnight This is a lot like in development, where youfind that the first take is rarely the best one I have often gone back through my codeand discovered some wacky designs Only then do I discover the best architecturaldesign, giving me fewer bugs and the best feature set In Palm, this is known as thesweet spot and it is a zone that few developers enter and fewer leave successfully.However, Palm not only entered this zone, it now owns it This accounts for most
of Palm’s success There are more powerful devices out there (PocketPC), and thereare more connected ones (Cybiko) Yet all of those devices combined still do not add up to the amount of devices that Palm has shipped Why? Because Palm hasfound the sweet spot, the spot where functionality and ease of use conflict, and difficult decisions are made to remove functionality (something that even Microsofthasn’t realized) Other companies have discovered this zone and understand what
is necessary in the handheld market That’s the reason why these very wise nies have licensed the Palm OS Companies like Sony, Handspring, and Symbol haveall realized the importance of Palm’s philosophy, where ease of use and power arenot necessarily mutually exclusive, and where the end-user experience is always top notch
compa-At this writing, there are more than 100,000 Palm OS developers This developmentcommunity is as diverse as the world of computing: from high school kids writing
in Basic to skilled university researchers writing in C, from enterprise developerswriting in Java to commercial developers writing in C++ From Iceland to Argentina,these developers have realized not only that Palm is the best-selling handheld inthe world but also that the Palm OS is an open operating system, intuitive to pro-gram and very clearly documented I don’t expect to see developers evangelize
the virtues of Palm OS ® Programming Bible, but they should Lonnon Foster has
proven that he understands not only the fundamentals of Palm OS programming
Trang 10but the sweet spot of writing as well This book covers everything from buildingforms and menus to programming sounds and color The examples are completeyet amazingly simple Not only will you learn to program the Palm OS, you willunderstand the philosophy that has made Palm successful, and in doing so, I hope that you will be successful too.
Phillip B ShoemakerDirector, Development ToolsPalm, Inc
Trang 11The convenience, power, and ease of use of Palm OS handheld devices make
them attractive to a wide variety of users Handheld devices running the Palm
OS have found their way into the shirt pockets of doctors, lawyers, sales personnel,business professionals, and other segments of society not normally given to usingsmall electronic gadgetry With more than 100,000 registered developers, the Palm
OS has also proven to be popular with software authors, which is where this bookcomes in
Palm OS ® Programming Bible will show you how to create applications for Palm’s
popular line of handheld organizers, as well as third-party devices that also run thePalm OS In addition, this book covers creation of Web clipping applications for thePalm VII/VIIx (and other wireless-equipped Palm OS handhelds) to allow wirelessconnection to the Internet You will also find material on writing conduit programs
to synchronize data between a Palm OS handheld and a desktop computer
Whether you are a developer for a large organization that is integrating Palm OShandhelds into its sales force or a hobbyist who wants to get the most from yourorganizer, you will find this book to be a useful guide to creating software for thePalm OS platform
The primary focus of this book is Palm OS development in the C language, usingCodeWarrior for Palm Computing Platform or the GNU PRC-Tools as a developmentenvironment Other tools exist for developing Palm OS applications (and an overview
of other such tools is available in the appendixes), but these two environments arepopular with the largest developer audience, and they offer the most completeaccess to the many features of the Palm OS and the handhelds that run it
Who Should Read This Book
This book was written with the experienced C programmer in mind If you knownothing at all about Palm OS programming, this book will get you started with thefundamentals, teaching you how the Palm OS works, showing you the tools avail-able for Palm OS development, and providing you with tips to make your own applications work seamlessly within Palm’s programming guidelines
Even if you already have delved into the world of creating Palm OS applications,you will find this book a useful resource, because it covers almost every aspect ofPalm OS development in depth The Palm OS is very large, and this book can serve
as a guide to exploring those parts of the operating system that you have not yetdealt with
Trang 12If you wish to create Web clipping applications for the Palm VII/VIIx, you will need to know the basics of HTML and Web page creation to make the Palm QueryApplications (PQAs) that reside on the handheld and provide a client-side connec-tion to the Internet To create the server side of a Web clipping application, you will need to be familiar with some sort of system for creating dynamic Web content, such as Perl CGI or Active Server Pages.
Conduit programming requires knowledge of C++, as well as a working knowledge
of how to create desktop applications for either Windows or the Mac OS
How This Book Is Organized
This book is organized into seven parts, plus four appendixes
Part I: Getting Started
This first part of the book discusses the philosophy behind the Palm OS and duces fundamental concepts behind the inner workings of the operating system
intro-Part II: Creating Palm OS Applications
The chapters in Part II cover the mechanics of making a Palm OS application Thissection begins with a tour of the tools for Palm OS programming, then gets you off the ground with a simple “Hello, world” application and finally presents toolsand techniques for every programmer’s favorite part of writing an application:debugging
Part III: Programming the Palm OS
The third part of this book focuses on actually writing the code to make a Palm OSapplication work Starting with chapters on creating the resources that form thestructure of an application, this part continues by showing how to actually makethe program do something, from interacting with the user to manipulating text
Part IV: Storing Information on the Handheld
Part IV shows how to store and retrieve application data It starts with the big picture, showing how to interact with databases, then moves in for a closer look
at the records that make up a database
Trang 13Part V: Communicating Outside the Handheld
The chapters in Part V cover the myriad methods a Palm OS handheld can use tocommunicate with the outside world, including infrared beaming, serial communi-cation, and wireless Web clipping
Part VI: Synchronizing Data with the Desktop
Part VI introduces the concepts behind the HotSync Manager, which allows a Palm
OS handheld to synchronize its applications with desktop data sources The sectioncontinues by showing how to write a conduit to customize the interaction between
a Palm OS database and desktop applications
Part VII: Advanced Programming Topics
In Part VII you will find various topics that do not come up as often as do the others
in Palm OS programming, including managing color, creating large applications, andcreating user interface elements dynamically while an application is running
Appendixes
The final section of the book is devoted to four appendixes:
✦ Appendix A, “Palm OS API Quick Reference,” is a quick guide to the most
common functions, data structures, and constants used in the Palm OS,including prototypes for Palm OS functions
✦ Appendix B, “Finding Resources for Palm OS Development,” is a list of
helpful resources for Palm OS developers
✦ Appendix C, “Developing in Other Environments,” is a survey of alternative
tools for Palm OS development
✦ Appendix D, “What’s on the CD-ROM?” describes the contents of the
CD-ROM that accompanies this book, which features sample code and applications from the book, as well as all the tools a developer needs to get started with Palm OS development
In addition, I’ve included a glossary at the end of the book
Trang 14How to Approach This Book
Readers who are completely new to Palm OS development will get the most benefitfrom this book by reading Parts I and II first to get a good handle on how the Palm
OS works and how to use CodeWarrior or the PRC-Tools Then look at Part III tolearn what to do with those tools to make an actual application, and follow up withPart IV to learn how to save and retrieve an application’s data The other parts ofthe book may be read in any order; pick a topic of interest, and start reading.For readers who have already done some Palm OS development, Part I probably will
be material you already know Part II can be useful if you use either CodeWarrior orthe PRC-Tools, and you want to see how the other set of tools works in comparisonwith what you are using, and in particular, Chapter 5, “Debugging Your Program,”contains useful tips for any Palm OS developer Parts III and IV will serve as usefulreferences to parts of the operating system that you may or may not already befamiliar with, and later chapters introduce other parts of the Palm OS that are not strictly required by most applications
Developers interested in creating Web clipping applications can go straight toChapter 16, “Creating Web Clipping Applications.” Most Web clipping developmentrequires only a working knowledge of HTML, and if you run across any Palm OS–specific concepts you are not familiar with, a quick look through Part I should serve to resolve any confusion
Anyone interested in creating conduits should first be familiar with the conceptualinformation in Part I After you understand the concepts behind the Palm OS, turn
to Part VI to learn how to hook the Palm OS up to a desktop computer
Conventions Used in This Book
Each chapter in this book begins with a heads-up of the topics covered in the chapter and ends with a summary of what you should have learned by reading the chapter
Throughout this book, you will find icons in the margins that highlight special orimportant information Keep an eye out for the following icons:
A Caution icon indicates a procedure that could potentially cause difficulty or evendata loss; pay careful attention to Caution icons to avoid common and not-so-common programming pitfalls
Cross-Reference icons point to additional information about a topic, which you canfind in other sections of the book
Cross-Reference
Caution
Trang 15A Note icon highlights interesting or supplementary information and often containsextra bits of technical information about a subject.
The On the CD-ROM icon is a pointer to information, tools, or programs available
on the CD-ROM that accompanies this book
Tip icons draw attention to handy suggestions, helpful hints, and useful pieces ofadvice
In addition to the icons listed previously, the following typographical conventionsare used throughout the book:
✦ Code examples appear in a fixed width font
✦ Other code elements, such as data structures and variable names, appear
in fixed width
✦ File names and World Wide Web addresses (URLs) also appear in fixed width
✦ Function and macro names are in bold.
✦ The first occurrence of an important term in a chapter is highlighted with
italic text Italic is also used for placeholders — for example, ICON <icon
file name>, where <icon file name>represents the name of a bitmap file
✦ A menu command is indicated in hierarchical order, with each menu mand separated by an arrow For example, File ➪ Open means to click the File command on the menu bar, and then select Open
com-✦ Keyboard shortcuts are indicated with the following syntax: Ctrl+C
Tip
On the CD-ROM Note
What Is a Sidebar?
Topics in sidebars provide additional information Sidebar text contains discussion that isrelated to the main text of a chapter, but not vital to understanding the main text
Trang 17Few books of this size and scope are ever the work of a single individual, and
this one is no exception I owe a debt of gratitude to many people for their help and encouragement in writing this book
First and foremost, thanks to my acquisitions editors, John Osborn and Greg Croy,
as well as my agent, Neil Salkind, for giving me the opportunity to write this book.Thanks also go to Erica Sadun, who had the whole idea in the first place
I want to extend special thanks to Eric Newman, whose hard work as developmenteditor was an incalculable asset in creating this book Not only did he help wrestlethe text of the book into a more focused and organized whole, he kept up the faitheven in the face of slipping deadlines and the author’s trip to England in the middle
of the writing A Palm enthusiast himself, Eric also kept me abreast of happenings
in the Palm OS world that I would otherwise have missed during the busiestmonths of writing
In addition, my thanks go out to the book’s technical reviewer, JB Parrett, whoseexpertise and passion for good user interface improved the quality of the bookimmeasurably I would also like to thank Mildred Sanchez and S B Kleinman fortheir copyediting as well as apologize for any gross abuses of the English languagethey were forced to endure
A big thank you to the production team at IDG Books, including Gabriele McCann,Linda Marousek, Danette Nurse, Ronald Terry, and Mary Jo Weis, whose effortsbehind the scenes made it possible for a random assortment of Word documentsand bitmap images to transform magically into the printed copy you now hold.More thanks go to Jessica Montgomery, Lenora Chin Sell, and Carmen Krikorian, the media production folks who secured legal permissions for third-party CD-ROMcontent, and a very special thank you to Joe Kiempisty for his able assistance andpatience in getting my own source code onto the CD
I owe a lot to Lisa Rathjens and Ryan Robertson of Palm Lisa’s loan of time and ware helped produce much better CodeWarrior support in this book, and Ryan’sexplanation of how tables work and answers to random technical questions ensuredthat some of the more confusing aspects of the Palm OS were made much clearer.Thanks also go to Christine Ackerman and Neil Shepherd of Oracle, Ivan Phillips ofPendragon Software, Ray Combs of PUMATECH, Dan Simon of Qualcomm, and ChrisCiervo of Symbol
Trang 18soft-Special thanks go to Ken Martin, Gene Thompson, and Steve Feldon, whose mentary as “beta testers” was very useful in making sure that I have not ignoredfirst-time Palm OS programmers in this volume Steve also deserves my gratitudefor introducing me to handheld computing, first with his old Newton (which hewouldn’t let me touch for fear of messing up the handwriting recognition), thenagain with his Pilot 5000 (which he did let me touch, and convinced me that I really needed to get one of my own).
com-An especially warm thank you goes out to the free software community, both forproducing the free Palm OS development tools that allowed me to get into Palmdevelopment in the first place and for providing source code of working Palm OSprograms, which allowed me to learn the ropes of the Palm OS In particular, I thank Mitch Blevins, author of DiddleBug and other fine free software, for fabuloussource code to work from and general camaraderie between developers, and John Marshall, maintainer of the PRC-Tools, for his able assistance in getting the PRC-Tools up and running under GNU/Linux
I also thank Garbage, Goodness, Guano Apes, and other bands whose names do notbegin with “G” (like Jethro Tull, Depeche Mode, and They Might Be Giants), for theirinspiring tunes, which were of great help during those really long chapters In addi-tion, my thanks go out to Nullsoft, makers of the Winamp MP3 player, whose fineprogram allowed me to queue up hundreds of songs by the aforementioned bandsand blast them at obnoxious volumes
Finally, I would like to offer my eternal thanks to Elisabeth (my wife), ConstanceMaytum, John Hedtke, Alan Zander, both of my cats, and all my friends who put
up with alternating blank stares and manic technical babbling from me over thecourse of this massive project
Trang 20Contents at a Glance
Foreword ix
Preface xi
Acknowledgments xviii
Part I: Getting Started 1
Chapter 1: Understanding the Palm Computing Platform 3
Chapter 2: Understanding the Palm OS 15
Part: II: Creating Palm OS Applications 41
Chapter 3: Introducing the Development Environments 43
Chapter 4: Writing Your First Palm OS Application 67
Chapter 5: Debugging Your Program 97
Part III: Programming the Palm OS 131
Chapter 6: Creating and Understanding Resources 133
Chapter 7: Building Forms 165
Chapter 8: Building Menus 193
Chapter 9: Programming User Interface Elements 213
Chapter 10: Programming System Elements 265
Chapter 11: Programming Tables 309
Part IV: Storing Information on the Handheld 371
Chapter 12: Storing and Retrieving Data 373
Chapter 13: Manipulating Records 403
Part V: Communicating Outside the Handheld 469
Chapter 14: Beaming Data by Infrared 471
Chapter 15: Using the Serial Port 507
Chapter 16: Creating Web Clipping Applications 535
Trang 21Part VI: Synchronizing Data with the Desktop 571
Chapter 17: Introducing Conduit Mechanics 573
Chapter 18: Building Conduits 593
Part VII: Advanced Programming Topics 657
Chapter 19: Programming in Color 659
Chapter 20: Odds and Ends 673
Appendix A: Palm OS API Quick Reference 707
Appendix B: Finding Resources for Palm OS Development 813
Appendix C: Developing in Other Environments 821
Appendix D: What’s on the CD-ROM? 829
Glossary 837
Index 861
End-User License Agreement 894
GNU General Public License 897
CD-ROM Installation Instructions 904
Trang 23Foreword ix Preface xi Acknowledgments xviii
Part I: Getting Started 1
Chapter 1: Understanding the Palm Computing Platform 3
The Palm OS Philosophy 3Comparing Desktop and Handheld Application Design 4Expectation of Performance 5Limited Input Methods 5Small Screen Size 6Battery and Processor Power 6Limited Memory 7RAM as Permanent Storage 7Connecting to the Desktop 8Comparing Hardware Versions 9Looking to the Future 13
Chapter 2: Understanding the Palm OS 15
Understanding a Palm OS Handheld’s Power Usage 15Running a Palm OS Application 16Responding to Launch Codes 17Handling Events 17Managing Memory 18Dynamic RAM 19Storage RAM 21Using Resources 23Designing the User Interface 24Forms 25Alerts 26Menus 27Tables 27Lists 28Pop-up Triggers 28Buttons 29
Trang 24Repeating Buttons 29Selector Triggers 30Push Buttons 30Check Boxes 31Labels 31Form Bitmaps 31Fields 32Graffiti Shift Indicator 32Scroll Bars 33Gadgets 34Communicating with Other Devices 35Serial 35TCP/IP 35Wireless 36IrDA 36Beaming 36Comparing Palm OS Versions 37Changes in Version 2.0 37Changes in Version 3.0 38Changes in Version 3.1 38Changes in Version 3.2 38Changes in Version 3.3 39Changes in Version 3.5 39
Part II: Creating Palm OS Applications 41
Chapter 3: Introducing the Development Environments 43
Using CodeWarrior for Palm OS 43Familiarizing Yourself with the IDE 45Changing Target Settings 52Compiling and Linking in CodeWarrior 56Using the GNU PRC-Tools 57Compiling and Linking with the PRC-Tools 59Automating Builds with Make 61
Chapter 4: Writing Your First Palm OS Application 67
Looking at the Hello World User Interface 67Walking Through the Hello World Code 68Including Header Files 69Entering the Application 71Starting the Application 73Closing the Application 73Handling Events 73Setting Up Forms 76Responding to Form Events 77
Trang 25Handling Menu Events 81Displaying Alerts and Using the Text Field 83Using Memory in the Palm OS 85Putting It All Together 90
Chapter 5: Debugging Your Program 97
Using the Palm OS Emulator 97Controlling POSE 100Running POSE for the First Time 102Installing a ROM Image 103Installing Applications 106Saving and Restoring Configurations 106Adjusting POSE Settings 107Handling Gremlins 112Emulating a HotSync Operation 115Taking Screen Shots 117Handling Errors in POSE 118Debugging at the Source Level 118Debugging with CodeWarrior 119Debugging with GDB 122Resetting a Palm OS Handheld 125Using Developer Graffiti Shortcuts 125Using the Palm OS Error Manager 127
Part III: Programming the Palm OS 131
Chapter 6: Creating and Understanding Resources 133
Following Palm OS User Interface Guidelines 133Making Fast Applications 134Highlighting Frequently Used Functions 135Designing for Ease of Use 136Maintaining Palm OS Style 137Creating Resources with Constructor 142Exploring the Project Window 143Creating Catalog Resources 156Creating Resources with PilRC 157Creating Application Resources 158Previewing the Interface in PilrcUI 163Assigning Constants to Resources 163
Chapter 7: Building Forms 165
Building Forms with Constructor 165Setting Common Object Properties 167Setting Individual Object Properties 169
Trang 26Building Forms with PilRC 180Creating a Form Resource 181Adding Objects to a Form 182
Chapter 8: Building Menus 193
Building Menus with Constructor 193Sharing Menus between Menu Bars 196Building Menus with Rez 197Integrating Rez Menus with Your Project 200Building Menus with PilRC 202Introducing Librarian, a Sample Application 204Displaying Multiple Records in List View 204Displaying an Individual Book in Record View 205Editing a Record in Edit View 206Examining Librarian’s Menus 208
Chapter 9: Programming User Interface Elements 213
Programming Alerts 213Programming Forms 216Switching to a New Form 216Displaying a Complex Modal Dialog Box 217Displaying a Simple Modal Dialog Box 218Programming Objects on Forms 221Handling Form Object Events 222Retrieving an Object Pointer 225Hiding and Showing Form Objects 226Programming Check Boxes and Push Buttons 227Handling Control Groups 228Programming Selector Triggers 229Programming Fields 233Setting a Handle for a Text Field 233Modifying a Text Field 234Retrieving Text from a Field 236UInt16 length = FldGetTextLength(field); Setting Field Focus 236Setting Field Attributes 237Programming Gadgets 238Programming Lists and Pop-up Lists 243Retrieving List Data 243Manipulating Lists 244Programming Dynamic Lists 245Handling Pop-up Lists 248Programming Menus 249Using MenuEraseStatus 250Removing Menu Items 250Drawing Graphics and Text 252Understanding Windows 252
Trang 27Drawing Lines 256Drawing Rectangles 256Drawing Text 260Drawing Bitmaps 261
Chapter 10: Programming System Elements 265
Checking for Supported Features 265Determining Operating System Version 266Checking Individual Features 268Manipulating Text 270Using Font Functions 270Using String Functions 274Using Character Macros 276Handling Pen Events 279Handling Key Events 281Setting Alarms 284Setting an Alarm 285Responding to Alarms 286Responding to Other Launch Codes 289Playing Sounds 290Looking Up Phone Numbers 292Launching Applications 293Calling the System Application Launcher 294Launching Applications Directly 294Sending Launch Codes Globally 297Creating Your Own Launch Codes 297Generating Random Numbers 298Managing Power 299Reacting to Low Battery Conditions 300Identifying the Device 301Manipulating Time Values 302Retrieving and Setting Time Values 303Converting Time Values 303Altering Time Values 305Using the Clipboard 305
Chapter 11: Programming Tables 309
Creating a Simple Table 310Understanding How Tables Work 311Initializing a Table 314Handling Table Events 328Hiding Rows and Columns 328Creating More Complex Tables 331Connecting a Table to Data 332Scrolling Tables 350Handling Table Text Fields 365
Trang 28Part IV: Storing Information on the Handheld 371
Chapter 12: Storing and Retrieving Data 373
Understanding the Data Manager 373Resource Databases 378Working with Databases 379Creating Databases 379Opening Databases 381Closing Databases 382Finding Databases 383Deleting Databases 385Retrieving and Modifying Database Information 386Creating an Application Info Block 391Storing Application Preferences 394Reading and Setting System Preferences 397Using Feature Memory 399
Chapter 13: Manipulating Records 403
Working with Records 403Looking at Records in the Librarian Sample Application 404Comparing Records 409Finding Records 416Creating Records 418Deleting Records 422Reading Records 424Modifying Records 424Sorting Records 435Retrieving and Modifying Record Information 436Categorizing Records 438Implementing Private Records 448Resizing Records 449Working with Resources 450Finding Resources 452Creating Resources 453Deleting Resources 454Reading Resources 455Retrieving and Modifying Resource Information 457Resizing Resources 458Implementing the Global Find Facility 458Handling sysAppLaunchCmdSaveData 459Handling sysAppLaunchCmdFind 460Handling sysAppLaunchCmdGoto 464
Trang 29Part V: Communicating Outside the Handheld 469
Chapter 14: Beaming Data by Infrared 471
Using the Exchange Manager 471Registering a Data Type 475Sending Data 477Customizing the Beam Acceptance Dialog Box 488Receiving Data 492Displaying Beamed Records 499Debugging Beaming 499Beaming Applications and Databases 500Understanding the IR Library 503
Chapter 15: Using the Serial Port 507
Understanding Palm OS Serial Communications 507Using the Serial Manager 510Using the New Serial Manager 511Using the Old Serial Manager 529
Chapter 16: Creating Web Clipping Applications 535
Understanding Web Clipping 535Understanding Web Clipping Security 537Designing PQAs and Web Clippings 537Building Palm Query Applications 539Organizing HTML Files 540Defining Header Tags 541Formatting Text 542Linking to Other Pages and Applications 544Constructing Query Forms 549Adding Images 554Using the Query Application Builder 556Looking at a Sample PQA 558Building Web Clippings 561Defining Header Tags 562Creating Clipping Pages for Desktop Browsers 562Linking Outside the Web Clipping 563Adding Images 563Looking at a Sample Web Clipping 563Testing Web Clipping Applications 567
Trang 30Part VI: Synchronizing Data with the Desktop 571
Chapter 17: Introducing Conduit Mechanics 573
Understanding Conduits 574Stepping Through the HotSync Process 576Designing Conduits 578Choosing a Development Path 579Installing Conduits 580Installing Conduits Manually 581Creating Automatic Conduit Installations 585Logging Actions in the HotSync Log 588
Chapter 18: Building Conduits 593
Using the Conduit Wizard 593Selecting a Conduit Type 595Choosing a Handheld Application 595Selecting a Data Transfer Type 597Selecting Conduit Features 598Confirming Class and File Names 599Implementing Conduit Entry Points 601Implementing GetConduitInfo 602Implementing GetConduitName 605Implementing GetConduitVersion 606Implementing OpenConduit 606Implementing Configuration Entry Points 610Using the Palm MFC Base Classes 619Following MFC Conduit Flow of Control 621Implementing a Monitor Class 622Implementing a Table Class 623Implementing a Schema Class 626Implementing a Record Class 627Implementing a Link Converter Class 631Using the Generic Conduit Base Classes 635Following Generic Conduit Flow of Control 636Describing the Desktop Record Format 637Implementing Storage and Retrieval 639Converting Data to and from CPalmRecord 643Syncing the Application Info Block 645Using the Sync Manager API 646Registering and Unregistering a Conduit 646Opening and Closing Handheld Databases 646Iterating Over Database Records 650Reading and Writing Records 653Deleting Records 654Maintaining a Connection 655
Trang 31Part VII: Advanced Programming Topics 657
Chapter 19: Programming in Color 659
Determining and Setting Color Depth 660Retrieving Color Depth 662Setting Color Depth 663Using Color Tables 664Translating RGB to Index Values 667Using Color Bitmaps 667Coloring the User Interface 669
Chapter 20: Odds and Ends 673
Creating Large Applications 673Breaking the 32KB Barrier 674Segmenting Applications 676Adding Custom Fonts to Applications 684Creating a Custom Font 685Creating User Interface Dynamically 688Localizing Applications 692Using the Text and International Managers 692Using the File Streaming API 699Opening File Streams 700Closing File Streams 702Retrieving File Stream Errors 703Deleting File Streams 703Setting Position in a File Stream 704Reading and Writing File Stream Data 704
Appendix A: Palm OS API Quick Reference 707 Appendix B: Finding Resources for Palm OS Development 813 Appendix C: Developing in Other Environments 821 Appendix D: What’s on the CD-ROM? 829
Trang 32Glossary 837 Index 861 End-User License Agreement 894 GNU General Public License 897 CD-ROM Installation Instructions 904
Trang 33Understanding the Palm
Computing Platform
Since the release of the Pilot 1000 in 1996, devices
run-ning Palm OS have dominated the handheld computingmarket Right from the start, Palm Computing was able tocombine just the right mix of features to make a PersonalDigital Assistant (PDA) that is easy to integrate into almostany user’s lifestyle Programming an application that takesadvantage of the strengths of the Palm Computing platformrequires an understanding of not only how the platformworks, but also why it was designed the way it was
This chapter explains some of the thinking that has made thePalm Computing platform so successful It also provides anoverview of the different versions of Palm OS available andthe hardware platforms on which they run
The Palm OS Philosophy
Devices running the Palm OS are not intended to be portableversions of desktop computers Instead, the handheld is asatellite device, designed as an extension to a desktop system
The handheld provides a window to desktop data, allowingthat data to be viewed anywhere Though it is indeed possible
to perform many complex tasks with Palm OS handhelds,their form and function are optimized for viewing data andentering small amounts of data
Connecting to the desktopComparing hardwareversions
The future of Palm OS
Trang 34In order to meet the goal of conveniently presenting a user’s data while away fromthe desktop, the handheld device must adhere to certain criteria:
✦ Small size It needs to be small enough to be carried anywhere Most of the
devices currently available for the Palm Computing platform easily fit in a shirtpocket The Palm V, smallest member of the Palm family, measures 4.5×3.1×0.4inches, weighing a measly 4 ounces Even the largest, Qualcomm’s pdQ, mea-sures only 1.4×6.2×2.6 inches, with a weight of 8.2 ounces, and it includes afully functional cell phone in that small package
✦ Ergonomic interface Using the device must be simple and quick enough to
not interrupt whatever the user is currently doing Handheld users need tocomfortably and rapidly operate the device during meetings, in airports, atbusiness lunches, and in other situations where there is no convenient place
to set the device down Useful information should be available instantly andwith a minimum of user interaction The four main applications that ship withPalm OS handhelds (Date Book, Address Book, To Do List, and Memo Pad) candisplay useful information without any stylus input from the user; the usercan scroll through the applications’ data by using the hardware buttons
✦ Desktop integration The handheld must synchronize easily and reliably with
the desktop computer Synchronizing with the desktop not only backs upimportant data, but it also allows the user to input large amounts of data on
a desktop machine with a mouse and keyboard, which is much better suited
to mass data entry than the limited interface of the handheld Palm OS helds include a cradle to sync the handheld to the desktop with a single but-ton press, and Palm Computing’s HotSync technology quickly transfers databetween the handheld and desktop
hand-Palm Computing hit upon a perfect combination of these factors with its firstdevice, and it has resisted the temptation to cram marginally useful features intonew Palm devices Although they have fewer features than many other handhelds,such as Windows CE and the older Newton devices, Palm OS handhelds are morefocused on providing features that will be genuinely useful Intelligent selection offeatures has made these devices into handy tools instead of merely expensive toys
Comparing Desktop and Handheld Application Design
There are significant differences between a desktop computer and a handhelddevice — enough differences that designing a handheld application must beapproached differently from designing a desktop application Several elementsmust be kept in mind when designing a Palm OS application:
✦ Expectation of performance
✦ Limited input methods
Trang 35✦ Small screen size
✦ Battery and processor power
✦ Limited memory
✦ RAM as permanent data storage
Expectation of Performance
Desktop application users usually won’t mind waiting a few seconds for a program
to load because they plan to be using the application for an extended period oftime A user seated at a desk probably isn’t going anywhere anytime soon
Compare this with a handheld user on the go A person using a Palm OS handheldwill need to look up a piece of data (such as a phone number) quickly, or spend afew seconds jotting down a note, while in the middle of performing some other task
Someone who is talking to clients on the phone or trying to catch a bus doesn’thave the time to watch a spinning wait cursor while an application loads
Speed and efficiency are key to a successful Palm OS application Writing fast code
is only a small part of the equation; the user interface must be simple and quick touse The application should allow for rapid navigation, selection, and execution ofcommands Functions that the user will use most often should require less interac-tion than those that will be used infrequently
Limited Input Methods
A desktop system is ideal for entering large quantities of data A keyboard and afast processor allow desktop users to easily input lots of text into the computer
in a short period of time
A Palm OS handheld does not have a keyboard Though third-party add-on boards exist, such as the Newton, GoType!, and Palm Portable keyboards, mostusers of a standard Palm OS handheld must enter text with a stylus and eitherGraffiti or an on-screen keyboard Graffiti, a software system that converts a specialtype of shorthand into text, is faster and more accurate than previous attempts athandwriting recognition, notably those used by the Apple Newton Instead of usingthe limited processor power and memory available on a handheld device to makesense of your own handwriting, Graffiti relies on a much more powerful system
key-to perform its magic: the human brain It is much simpler for a person key-to learn key-towrite Graffiti’s simple set of glyphs than it is for a piece of software to interpret the idiosyncrasies of most people’s handwriting (A friend of mine used to own aNewton, and after spending months tuning it to recognize his writing, he wouldn’tlet anyone else near the device for fear that they would “untrain” the recognitionsoftware.) Although Graffiti is faster than many forms of handwriting recognition,
at a top speed of around thirty words per minute, it is still too slow for enteringanything longer than a short note
Trang 36HotSync technology provides an easy way to get large amounts of data from thedesktop system to the handheld The Palm Computing platform is designed aroundthe idea that users will perform mass data entry on the desktop machine, which isoptimized for that kind of work, and then “sync” that data to the handheld Thiskind of symbiosis between desktop computer and handheld plays to the strengths
of both devices
However, don’t let this discourage you from writing applications that use a Palm OShandheld as a data collection tool With intelligent interface design, you can per-form data entry quickly and efficiently on such a device
For more details about designing efficient data entry, see Chapter 2, “Understandingthe Palm OS.”
Small Screen Size
Current desktop machines have large monitors, generally running at a minimumresolution of 640×480 pixels With this kind of screen real estate to play with, dis-playing large amounts of information and a complex user interface in the samespace is easy
By contrast, Palm OS handhelds have a screen 6 centimeters on a side, with a lution of 160×160 pixels This screen size is necessary to keep the device within theshirt-pocket size range that has contributed to the popularity of such devices.Designing applications to use such a small screen is a challenge Displaying theright information is more important than fitting as much information on the screen
reso-as possible You must strike a balance between showing enough information andkeeping the interface uncluttered and simple to use
Requiring users to scroll through many screens of data to find the information theywant will make your application frustrating to use Find logical groupings of dataand offer the user a way to filter different views of that data The To Do List applica-tion is a good example of data filtering; its preferences allow the user to quicklychoose what subset of the list should be displayed Implementing the standardPalm OS user-defined categories can also help users zero in on exactly the datathey want to view
Battery and Processor Power
Unlike desktop machines, which are plugged into wall outlets and sport powerful,fast processors, Palm OS handhelds must rely on batteries for power, which limitsthem to slower processors The small processor on such a device is not well suited
Trang 37relegating processor-intensive tasks to the desktop machine is Doc, the de factostandard for large text documents on the Palm OS Several converter applicationsexist for the desktop machine, which perform the computationally expensive con-version and compression of a large text document to Doc format The newly format-ted document can then be transferred to the handheld during the next HotSyncsession All the Doc viewer application on the handheld need concern itself with isdisplaying the document; all the hard stuff has been handled by the faster desktopcomputer.
Limited Memory
As memory prices continue to drop, desktop applications can afford to be lesschoosy about how they deal with memory When your application has 64MB ormore to play with, it can load huge data structures into RAM and leave them therethe entire time the program is running
Palm OS handhelds have very limited memory space for running applications OnPalm OS 3 and later, there is less than 36KB of memory available for dynamic alloca-tion, application global variables, and static variables Earlier versions of Palm OShave considerably less room, so writing applications that are compatible with olderPalm OS handhelds can be somewhat challenging Keep this in mind when writingyour application; things like deeply recursive routines, large numbers of global vari-ables, and huge dynamically allocated data structures are not Palm OS–friendly
RAM as Permanent Storage
Hard drives provide desktop computers with abundant permanent storage for vastamounts of data Palm OS handhelds are considerably more limited in storagespace because they must store applications and data in RAM
Available memory on a Palm OS handheld ranges between 128KB on the Pilot 1000and 8MB on the Palm IIIxe or Visor Deluxe This kind of limited storage dictates thathandheld applications must be as small as possible Avoid adding features to yourapplication that will be used infrequently; if a feature will be used by fewer than
20 percent of the users, leave it out
For example, features that globally modify an application’s data, but will see onlyinfrequent use, are prime candidates for inclusion in a companion program on thedesktop A command that removes duplicate entries in a database would be perfectfor the desktop; it’s not likely to be used very often on the handheld, and removing
it from the handheld application makes the program smaller
Your application should also pack its data tightly before writing it to memory Notonly will this reduce the amount of RAM required to store your application’s data,but it will also decrease the amount of time taken by HotSync when synchronizingthat data with the desktop computer
Trang 38Connecting to the Desktop
Sharing data with the desktop is a key ingredient in the popularity of Palm OS helds The connection between desktop and handheld allows each device to borrowthe strengths of the other A desktop computer is great for large-scale data entry andcrunching numbers, but you can’t carry one in your pocket when visiting clients
hand-A handheld device is perfect for taking quick notes and reminding you of ments, but it’s terrible for analyzing financial reports or writing a book Together, the devices become greater than the sum of their parts
appoint-The software component that forms the vital link between the Palm OS device and
the desktop computer is called a conduit HotSync calls code in a conduit, which
resides on the desktop computer, during synchronization with your handheld cation, and this code controls exactly what data HotSync transfers between the twodevices There are several different scenarios in which a conduit plays a vital role;here are just a few examples:
appli-✦ Two applications, one on the handheld and one on the desktop, use the duit to keep records in their databases in sync with each other This is howthe conduit for the Date Book and the three other main Palm OS applicationsworks In this scenario, the conduit is responsible for looking at the records
con-in both databases and determcon-incon-ing what records are different between them,
as well as which direction those data must be transferred
✦ The conduit keeps data in a handheld application synchronized with data
in a centralized corporate database, either stored on the machine runningHotSync, or another machine on a corporate network In this case, the con-duit might also sift the data and transfer only a customized subset to thehandheld based on user preferences Customization like this keeps the size
of the data manageable and reduces the time required for HotSync to run
✦ When syncing, the conduit compares content on the handheld with the tents of a Web page or Usenet newsgroup If the information on the Web ornewsgroup is newer than what the handheld application has stored, the con-duit downloads the new data, processes it into a form the handheld applica-tion can read, and transfers it to the handheld The conduit may also instructthe handheld application to cull out-of-date pages or articles Since Internetconnections are prone to delays, this sort of conduit should probably onlylook at information previously cached by a desktop application A HotSyncoperation should be as short as possible because having the serial port open drains a Palm OS handheld’s batteries rapidly
con-If your application does not require the level of detailed synchronization logic that a
conduit can provide, you may be able to use the default backup conduit Instead of
comparing the handheld application’s database record by record with data on the
Trang 39desktop, the backup conduit simply makes a copy of the entire database and fers it to the desktop computer This works perfectly well for small application data-bases but can slow down the HotSync process if your application stores a lot of data.
trans-Chapter 17, “Introducing Conduit Mechanics,” provides an introduction to oping Palm OS conduits Further details on writing conduits follow in Chapter 18,
devel-“Building Conduits.”
Comparing Hardware Versions
Palm OS handhelds have evolved slowly, adding just a few new features at a time
This incremental change is a boon to application developers, because it means that new versions of hardware and operating system software require only smallchanges, if any, to existing applications instead of requiring that they be rewrittenfrom the ground up
Even though Palm Computing has wisely refrained from making wild, earth-shatteringchanges to the platform, there are some significant differences between versions ofthe hardware that you should take into account when designing your application
Table 1-1 highlights the features of different Palm OS devices
Trang 40Palm III family
Feature Palm III Palm IIIe Palm IIIx Palm IIIxe Palm IIIc
version Processor Motorola Motorola Motorola Motorola Motorola
MC68328 MC68EZ328 MC68EZ328 MC68EZ328 MC68EZ328
“DragonBall” “DragonBall “DragonBall “DragonBall “DragonBall
Matrix TFT LCD screen