Android Wearable Programming Expand on your Android development capabilities by building applications for Android Wear 1st Edition Steven F. Daniel - Download the ebook now for instant access to all chapters
Android Wearable Programming Expand on your Android development capabilities by building applications for Android Wear 1st Edition Steven F. Daniel - Download the ebook now for instant access to all chapters
com
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookgate.com/product/wearable-android-android-wear-and-
google-fit-app-development-1st-edition-sanjay-m-mishra/
ebookgate.com
https://ebookgate.com/product/professional-android-programming-with-
mono-for-android-and-net-c-1st-edition-wallace-b-mcclure/
ebookgate.com
https://ebookgate.com/product/beginning-android-web-apps-development-
develop-for-android-using-html5-css3-and-javascript-1st-edition-jon-
westfall/
ebookgate.com
https://ebookgate.com/product/android-for-beginners-all-you-need-to-
get-started-with-your-android-device-fourth-revised-edition-white/
ebookgate.com
Android Application Development Programming with the
Google SDK 1st Edition Rick Rogers
https://ebookgate.com/product/android-application-development-
programming-with-the-google-sdk-1st-edition-rick-rogers/
ebookgate.com
https://ebookgate.com/product/programming-your-home-automate-with-
arduino-android-and-your-computer-1st-edition-mike-riley/
ebookgate.com
https://ebookgate.com/product/learn-java-for-android-development-2nd-
edition-jeff-friesen/
ebookgate.com
https://ebookgate.com/product/android-application-development-
cookbook-93-recipes-for-building-winning-apps-1st-edition-wei-meng-
lee/
ebookgate.com
https://ebookgate.com/product/android-high-performance-
programming-1st-edition-enrique-lopez-manas/
ebookgate.com
www.allitebooks.com
Android Wearable
Programming
Steven F. Daniel
BIRMINGHAM - MUMBAI
www.allitebooks.com
Android Wearable Programming
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
ISBN 978-1-78528-015-3
www.packtpub.com
www.allitebooks.com
Credits
Reviewers Proofreader
Marcus Gabilheri Safis Editing
Andreas Göransson
Dr. Jibo He Indexer
Tejal Soni
Qian He
Jason Salas
Graphics
Jason Monteiro
Commissioning Editor
Priya Singh
Production Coordinator
Aparna Bhagat
Acquisition Editor
Vivek Anantharaman
Cover Work
Aparna Bhagat
Content Development Editor
Amey Varangaonkar
Technical Editors
Utkarsha S. Kadam
Shiny Poojary
Copy Editor
Kausambhi Majumdar
www.allitebooks.com
About the Author
He was the cofounder and Chief Technology Officer (CTO) of SoftMpire Pty Ltd., a
company that focused primarily on developing business applications for the iOS and
Android platforms.
Steven is the author of various book titles, such as Xcode 4 iOS Development Beginner's
Guide, iOS 5 Essentials, iPad Enterprise Application Development Blueprints, and
Xcode 4 Cookbook, all by Packt Publishing. You can check out his blog at http://www.
geniesoftstudios.com/blog/ or follow him on Twitter at http://twitter.com/
GenieSoftStudio.
www.allitebooks.com
Acknowledgments
No book is the product of just the author — he just happens to be the one with his
name on the cover. A number of people contributed to the success of this book and
it would take more space than I have to thank each one individually.
I would personally like to thank two special people who have been an inspiration
and who have provided me with so much support during the writing of this book:
Vivek Anantharaman, my acquisition editor, who is the reason that this book
exists, for being a wonderful guide throughout this whole process, and Amey
Varangaonkar for his understanding and support, as well as his brilliant suggestive
approaches during the chapter rewrites. Thank you for everything, guys.
Lastly, to my reviewers: thank you so much for your valuable suggestions and
improvements, making this book what it is today. I am extremely grateful to each
and every one of you.
Also, thanks to the entire Packt Publishing team for working so diligently to help
bring out a high-quality product. Finally, a big thank you to the engineers at Google
for creating the Android platform and providing developers with the tools to create
fun and sophisticated applications.
Finally, I'd like to thank all of my friends for their support, understanding, and
encouragement during the writing process. It is a privilege to know each and
every one of you.
www.allitebooks.com
About the Reviewers
www.allitebooks.com
Dr. Jibo He is currently an assistant professor at Wichita State University. He
graduated from Peking University in 2007 and the University of Illinois in 2012
with a research specialty in engineering psychology. He won the Star of Tomorrow
Award from Microsoft and was voted the Most Valuable Graduate by the University
of Illinois. He directs the Human Automation Interaction Lab at Wichita State
University. His lab does research on user experience, mobile devices, driving safety,
aviation psychology, and human computer interaction. The goal of his research is
to understand the human cognitive processes and develop technologies to improve
performance, increase user experience, and mitigate human error. He has experience
in developing for Google Glass, Android, iPhone, and smartwatches.
He runs the R&D group for Guam's largest media company, where he also
co-anchors the nightly news.
www.allitebooks.com
www.PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.
com and as a print book customer, you are entitled to a discount on the eBook copy.
Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on Packt
books and eBooks.
TM
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
www.allitebooks.com
www.allitebooks.com
To my favorite uncle, Benjamin Jacob Daniel, for always making me smile and
inspiring me to work hard and achieve my dreams, I miss you a lot.
Chan Ban Guan, for the continued patience, encouragement, and support,
and most of all for believing in me during the writing of this book.
This book would not have been possible without everyone's love and understanding
and I would like to thank you all from the bottom of my heart.
Table of Contents
Preface v
Chapter 1: Understanding Android Wearables and Building
Your First Android Wear App 1
Introducing Android wearables 2
Understanding the Android Wear architecture 3
Setting up an Android development environment 6
Installing the Android Wear support library 7
Setting up and configuring the Android (AVD) Emulator 8
Building a simple Android wearable application 10
Creating the mobile activity component 12
Creating the Android Wear activity component 14
Summary 19
Chapter 2: Creating Notifications 21
Introducing Android notifications 22
Creating a basic notification for wearables 23
Specifying the form factors 24
Adding and customizing a blank activity 25
Adding dependencies to Gradle scripts 26
Creating a custom notification for wearables 33
Receiving voice input within a notification 39
Receiving multiple notifications through a process called
page stacking 43
Summary 49
Chapter 3: Creating, Debugging, and Packaging Wearable Apps 51
Creating an Android wearable watch face app 52
Presenting information inside the WatchFace class 55
Creating a custom watch face service class 60
[i]
Table of Contents
[ ii ]
Table of Contents
[ iii ]
Preface
Android Wear is becoming extremely popular, and offers a great opportunity for
developers to learn how to build applications for the Android Wear platform, which
is a special version of the core Android OS, and has been tailored for wearable
computing devices such as smartwatches. These wearable devices come with a brand
new user interface, which is the result of Google working with their customers to
understand how they use their phones today and how they can be more in touch
with their environment.
In this book, I have tried my best to keep the code simple and easy to understand
by providing a step-by-step approach, with lots of screenshots at each step to make
it easier to follow. You will soon be mastering the different aspects of Android
Wear programming, as well as the technology and skills needed to create your
own applications for the Android Wear platform.
[v]
Preface
Chapter 3, Creating, Debugging, and Packaging Wearable Apps, focuses on designing and
creating custom watch faces to present information within the Android wearable
watch area. You will learn how to effectively debug your app over Bluetooth, before
finally learning how to package your wearable app so that it can be used within the
handheld mobile device.
Chapter 4, Sending and Syncing Data, introduces you to the Data Layer API and
the Message API frameworks, so that you can synchronize image data from the
handheld device with the wearable, as well as use the Message API to communicate
between the handheld and the wearable to send and receive messages.
Chapter 5, Working with Google Glass, explores how to build effective user interfaces
for the Google Glass platform by creating user interfaces that display content that
responds to voice input commands, before finally learning how we can access the
Glass camera to take a snapshot and save the image to local storage.
Chapter 6, Designing and Customizing Interfaces for Android TV, provides you with the
background and understanding of how to effectively present your app within the
main user interface and how you can design your app by following the Android
TV UI Patterns to help users get the content they want quickly. Also, you will learn
how to create and use fragments that allow information to be presented within the
Android TV interface to represent your content.
[ vi ]
Preface
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text are shown as follows: "We can include other contexts through
the use of the include directive."
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:support-v4:20.0.+'
}
[ vii ]
www.allitebooks.com
Preface
New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "Next, click
on the Install packages button as shown in the preceding screenshot."
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or disliked. Reader feedback is important for us as it
helps us develop titles that you will really get the most out of.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things
to help you to get the most from your purchase.
[ viii ]
Preface
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our website or
added to any list of existing errata under the Errata section of that title.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.
We appreciate your help in protecting our authors and our ability to bring you
valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at
[email protected], and we will do our best to address the problem.
[ ix ]
Understanding Android
Wearables and Building Your
First Android Wear App
When Google announced Android Wear at their Google I/O conference back in
March 2014, developers were excited and started embracing this technology to
see what types of applications they could create to communicate between the
Android handheld device and Android wearable, while making our day-to-day
lives a lot easier.
This chapter provides you with a theoretical background of Android, and how to
develop applications for the Android Wear platform from Google. This platform
allows your Android wearable device to communicate with your phone wirelessly
over Bluetooth, and many manufactures like Samsung and LG have embraced this
technology and created wearable devices, such as the Samsung Gear Live and
the LG G Watch R smartwatches.
[1]
Understanding Android Wearables and Building Your First Android Wear App
In later chapters, we will be working with some of these APIs and seeing how we can
incorporate these in our applications to communicate between our Android phone
and Android Wear devices.
Android Wear provides consumers with a more personal interaction with their
devices. These tiny supercomputers can show you information and suggestions
when you need them. Given the wide variety of Android applications currently
on the market, you'll receive the latest posts and updates from your favorite social
apps and notifications from shopping apps.
Android wearables are great for fitness fanatics too. They allow you to better monitor
your health and fitness by showing your fitness summary in terms of real-time speed,
distance, and time information right on your wrist for your run, cycle, or walk.
Android Wear also lets you access and control other devices from your wrist by
simply saying OK Google to fire up a music playlist on your phone or cast your
favorite movie directly onto your TV. You can also receive instant messages
from your favorite social networking app, for example, Facebook. With Android
wearables, there's a lot of possibilities, and developers are jumping right in and
creating some stunning apps already.
[2]
Chapter 1
When a connection has been established between the Android device and the
wearable, over Google Play service, notification messages can be then exchanged
between the handheld device and the wearable to trigger appropriate actions on
each device.
The architecture of any typical wearable application has been set out by Google in
their design guideline documents that focus primarily on the new Material design
theme for Android 5.0 applications. This design document provides the developer
with a comprehensive framework to create visual, motion, and interaction design
across each of the various Android platforms and devices.
[3]
Understanding Android Wearables and Building Your First Android Wear App
Since Android Wear runs as a Bluetooth Low Energy (BLE) device, developers
need to ensure that they design their applications to run efficiently so that they don't
impact the device's battery. This is very important when designing the custom watch
faces or apps that use location service functionality.
The following image describes the architecture between the handheld device and the
wearable device. In the next section, we will take a look into some of the wearable
APIs that come as part of Google Play services, and explain their purpose when it
comes to communicating between the mobile device and the wearable:
.apk
wearable.apk
Awesome App
Play Store
Data API Play Services
Node API
Message API Intents somehow Outer World
wearable .apk
Once the connection is established, you can then start looking at sending and
synching data between the two devices. When a connection between two devices has
been established, each node can handle any given number of different functions. For
example, one node can handle the camera part on the mobile, while another node
could keep track of a user's GPS coordinates on the wearable device.
In the following list, we will explain each of the APIs, which are presented in the
preceding screenshot. In later chapters, we will be using these in more depth,
so at this stage, I will just be providing a brief introduction:
• Node API: The NodeApi class is responsible for keeping track of all
connected or disconnected nodes that have been established within the
wearable network by using the NodeListener interface method. When
a node establishes a connection between the handheld and the wearable,
MessageApi quietly begins to send a message from the wearable device to
the handheld device that it is paired with, which the user is signed in to with
their Google account. This sends a notification to the NodeListener method
that then begins to get information about each node.
[4]
Chapter 1
• Message API: The MessageApi class is responsible for sending across short
messages to each of the connected network nodes between the wearable
and the handheld device. Once a message has been received, a background
listener service on the receiving side (MessageListener) will be called so
that it can get the message.
• Data API: The DataApi class is responsible for synching data between the
connected Android wearable and the handheld device, and takes care of
providing the synching mechanism on both sides. In addition to synching
data, the big appeal of the data API is that when a user's connection gets
disconnected from the paired smartphone, the data will be automatically
transferred when the connection is restored, without the user needing to
worry about handling data issues. When the data API receives messages
from MessageApi, a background listening service on the receiving side
(addListener) will be called as part of the DataListener interface method.
Once the addListener method determines that a change has occurred, a call
is made to the onDataChanged method.
In the following chapters of this book, we will be taking a look at how to implement
some of these APIs to communicate between our Android device and our wearable
device, so stay tuned.
[5]
Understanding Android Wearables and Building Your First Android Wear App
Before you begin, and as a prerequisite to starting to work with Android Studio,
you will need to ensure that your system has the latest version of the Java Runtime
Environment (JRE) installed for the version of the operating system that you are using.
To determine if your system has the JRE or the Java Development Kit
(JDK) installed, open a new terminal window and issue the following
command from the command line:
java –version
Once you have determined if you have Java installed, you can proceed to download
Android Studio for your version of the operating system. The Android Studio
package can be downloaded from the Android developer tools web page at
http://developer.android.com/sdk/installing/studio.html.
Now that you have downloaded and installed Android Studio, you can begin
installing the Android 4.4W (API 20) for your system:
[6]
Chapter 1
You will notice that we have chosen to install the Android Wear system images for
both ARM and Intel. Intel delivers greater performance while running your app
using the Android Emulator, but you can select the appropriate one for your chipset.
If you decide to install both, the Android Studio IDE at design time will inform you
which one is supported.
In the next section, we will need to install the Android Wear support libraries for
our Android Wear application that will allow your Android wearable app to target
a specific version of the Android SDK APIs.
[7]
www.allitebooks.com
Understanding Android Wearables and Building Your First Android Wear App
The benefit of using the latest Android Wear support libraries is that it allows your
applications to take advantage of the new and improved features for devices that are
running Android 5.0 and above. However, while your app can still run on devices
running Android 1.6 and above, some features will not be available:
Scroll down to the Extras folder, and select the Android Support Library, as shown
in the preceding screenshot. Next, click on the Install packages button as shown in
the preceding screenshot.
If you are using Android Studio for your Android Wear development, this can
provide you with a much easier and more convenient way of adding the Android
Wear support library to your existing applications. Android Studio uses a module
model, where the mobile and wear modules are part of a single project.
[8]
Chapter 1
Open your Android Virtual Device (AVD) manager and create a new virtual device
for your Android Wear, as shown in the following screenshot:
Before we end this section, it is worth mentioning that while Android Emulator is the
most powerful and convenient tool that you will use throughout your development
of Android apps, it is important for developers to understand the types of limitations
it comes with, which are explained in the following points:
• The Android Emulator simulates real handheld device behavior, but not
specific hardware implementations
• Sensor information, such as satellite location, battery, and power settings,
as well as network connectivity, is all simulated using your computer
• Access to the camera hardware is not fully functional
• There is no ability to place or receive phone calls, or send SMS messages,
as these are all simulated
• There is no support for USB available
[9]
Understanding Android Wearables and Building Your First Android Wear App
As you can see, using the Android emulator is not recommended as a substitute for
testing your apps on a true handset or device. Now that we have set up all of the
preliminary configurations, we can start to build our Android Wear application.
1. Launch Android Studio, and then navigate to the File | New Project option.
2. Next, enter in HelloAndroidWear for the Application name field.
3. Then provide a name for the Company Domain field.
4. Next, choose Project location where you would like to save your
application code:
[ 10 ]
Chapter 1
5. Finally, click on the Next button to proceed to the next step. On the second
wizard screen, we need to specify the form factors using which our
application will run. On this screen, we choose the Minimum SDK versions
for phone and tablet, Android TV, and Android Wear.
6. Click the Phone and Tablet option and choose the API 19: Android 4.4
(KitKat) option for Minimum SDK. Choosing this option allows your
application to target more devices that are active on the Google Play Store,
with the added cost of having fewer features available for these devices.
7. Next, click on the Wear option and choose the API 20: Android 4.4
(KitKat Wear) option for Minimum SDK:
8. Next, click on the Next button to proceed to the next step in the wizard.
[ 11 ]
Understanding Android Wearables and Building Your First Android Wear App
In our next step, we will be taking a look at how to add a blank activity to our
application for its mobile section.
1. From the Add an activity to Mobile screen, choose the Blank Activity option
from the list of activities:
[ 12 ]
Chapter 1
2. Now, click on the Next button to proceed to the next step in the wizard.
In our next step, we need to set up and customize our Blank Activity
properties that can be used by our application. Here, we specify the name
of the activity, layouts, and title, as well as its menu resource name that it
will be using (if it contains a menu bar).
3. From the Customize the Activity screen, accept the default properties that
have been created for you by the wizard:
4. Click on the Next button to proceed to the next step in the wizard.
[ 13 ]
Understanding Android Wearables and Building Your First Android Wear App
1. From the Add an activity to Wear screen, choose the Blank Wear Activity
option:
2. Click on the Next button to proceed to the final step in the wizard.
In our final step, we need to customize our Blank Wear Activity properties
that can be used by our Android wearable. Here, we specify the name of the
activity as well as the layouts for the watch faces for round and rectangle.
[ 14 ]
Chapter 1
3. From the Customize the Activity screen, accept the default properties that
have been created for you by the wizard:
4. Next, click on the Finish button to proceed, and your Android wearable
project will be generated for you. After a few moments, the Android Studio
window will be displayed with your project loaded.
When you take a look at the project that the wizard created for you, the first thing
you will notice is that it contains two modules: mobile and wear. The mobile portion
of our project is the application that will run on a phone device that will be used to
communicate with our wearable device. The wear portion is the application that will
be installed on the Android wearable device.
[ 15 ]
Understanding Android Wearables and Building Your First Android Wear App
As you can see in the following screenshot, the default project structure that our
wizard created for us doesn't seem to do anything special—it simply contains the
skeleton structure of any Android wearable app. In our next step, we will look at
how we can write our own code for the Wear module of our application:
In our next step, we will begin modifying our MainActivity class file to display
our custom Android wearable welcome message to the user within the wearable
watch face :
[ 16 ]
Chapter 1
2. From the Project Navigator window, expand the Wear section, select,
and expand the java section.
3. Modify the following code in the MainActivity.java file of the project:
private TextView watchTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub theWatchView = (WatchViewStub)
theWatchView.setOnLayoutInflatedListener(new
WatchViewStub.OnLayoutInflatedListener() {
@Override
public void onLayoutInflated(WatchViewStub
theWatchView) {
watchTextView = (TextView)
theWatchView.findViewById(R.id.text);
watchTextView.setText("Android Wear Rocks!");
}
});
}
In the preceding code snippet, we start by creating a new activity, which is handled
by the onCreate method. This method is responsible for starting the activity when
the application is launched and the emulator sets up the content, prior to displaying
the watch layouts on the screen using the setContentView method.
[ 17 ]
www.allitebooks.com
Understanding Android Wearables and Building Your First Android Wear App
Now, we can finally compile, build, and run our application. Click on the green
button labeled B in the preceding screenshot or simply press
CMD + F9, and choose Android Virtual Device from the list of Android Emulators:
Once the emulator has launched and after a few moments, you should see your app
displayed, as shown in the preceding screenshot.
[ 18 ]
Chapter 1
Summary
In this chapter, we explored the features and key concepts of the Android Wear
platform; we discussed about the Android Wear architecture; and then we moved
on to look at how to configure our Android environment, setting up the Android
SDK and AVD, before finally taking a look at how to build our simple Android
wearable app.
In the next chapter, we will cover the features of Android notifications and explore
the different ways that we can send notifications between the handheld device and
the Android wearable to create basic and custom notifications. We will learn how
we can use the Android voice capabilities to allow the user to respond to notification
messages by using just their voice, and how we can use a method called page
stacking to receive multiple notifications.
[ 19 ]
Creating Notifications
This chapter provides you with a background of essential features of Android
notifications and how we can use these to send messages between a handheld device
and a wearable device.
We will be taking a look at how we can use different notification methods to develop
an application that shows how we can create basic and custom notifications. You will
also learn how you can incorporate and make use of Android's voice capabilities to
respond to notification messages that are contained within a notification.
At the end of the chapter, we will take a look at how we can use notification stacking
to display multiple notification messages within a notification.
[ 21 ]
Creating Notifications
Notifications in wear are the result of events that happen on the paired smartphone,
which are then mirrored on the wearable device, or contextual events like location-
aware events or time, and date-based reminders. Android notification messaging
works by communicating between the handheld device and wearable device over
Bluetooth. When the connection has been established, the Google Play Service
notification messages can be exchanged between the handheld device and the
wearable. An example of a notification message that has been sent from the Android
handheld device to the Android wearable can be seen in the following screenshot:
In the next sections, we will be taking a look at the different ways we can send
notifications and how we can respond to them.
[ 22 ]
Another Random Document on
Scribd Without Any Related Topics
fuggendo, quelli vincevano.» [308] E così i papi, per la loro smodata
ambizione, fecero sempre più peggiorare le cose d'Italia. Niccolò III
(1277-81) fu poi il primo che iniziò il nepotismo, e subito dopo i suoi
successori passarono anche in ciò ogni confine. «Laonde, come da
questi tempi indietro non s'è mai fatta menzione di nipoti o di parenti
di alcuno pontefice, così per l'avvenire ne fia piena l'istoria, tanto che
noi ci condurremo ai figliuoli, nè manca altro a tentare ai pontefici,
se non che, come eglino hanno disegnato insino ai tempi nostri di
lasciarli principi, così per l'avvenire pensino di lasciare loro il papato
ereditario.» [309] E procederono tanto oltre nella loro ambizione, che
Bonifazio VIII volse contro i Colonnesi, suoi nemici, le armi spirituali
insieme con le temporali. «Il che, sebbene offese alquanto loro,
offese assai più la Chiesa, perchè quelle armi, le quali per carità della
fede avevano virtuosamente adoperate, come si volsero per propria
ambizione ai Cristiani, cominciarono a non tagliare. E così il troppo
desiderio di sfogare il loro appetito, faceva che i pontefici a poco a
poco si disarmavano.» [310]
Gli altri avvenimenti politici, anche se di grandissima importanza,
come ad esempio i Vespri Siciliani, le discordie dei Guelfi e dei
Ghibellini, le vicende nel Napoletano, sono appena accennati, per
parlar sempre di quei fatti che in qualche modo potevano valere a
giustificare le simpatie o antipatie politiche dell'autore, a confermare
le sue teorie. Così sempre più chiaro apparisce, che egli non mirava
punto ad un ordinamento obbiettivo dei fatti, secondo il loro
intrinseco valore, nè quindi poteva riuscirvi. Il suo scopo, invece, è
costantemente quello di ritrovare nella storia la conferma del suo
concetto politico, il che non gli era difficile, avendolo da essa la
prima volta cavato, nè essendo egli molto scrupoloso nella esattezza
dei minuti particolari. Assai rapidamente parla ancora del viaggio
d'Arrigo VII in Italia, e delle molte conseguenze che ne derivarono; e
si ferma invece lungamente a descriverci le arti, le astuzie, le perfidie
con cui i Visconti, specialmente Matteo, s'impadronirono di Milano,
cacciandone i della Torre. E colorisce a suo modo questi fatti, nei
quali ritrova da capo le arti del Principe nuovo, argomento di cui,
direttamente o indirettamente, non si stanca mai di parlare. Più
innanzi, dopo aver narrato altri avvenimenti, il Machiavelli dà, non si
sa come nè perchè, un gran passo indietro, per raccontarci le origini
di Venezia. E poi da capo incontra un personaggio che lo induce a
fermarsi, e questi è il tribuno Cola di Rienzo, che se avesse finito
come aveva cominciato, sarebbe stato un altro degli uomini da lui
più ammirati. Ed infatti comincia subito a parlarne con entusiasmo,
per poi abbandonarlo con disprezzo, appena lo vede, senza ragione,
disertare la bene iniziata impresa di ricostituire la repubblica romana.
[311] Continua descrivendo i disordini d'Italia; lo scisma della Chiesa;
il trasferimento della sede in Avignone ed il suo ritorno a Roma; i
Concilî di Pisa e di Costanza; le ambiziose mire dei Visconti, massime
di Giovanni Galeazzo; le strane vicende di Giovanna II di Napoli; le
imprese militari dello Sforza, di Braccio di Montone e degli altri
condottieri italiani, i quali egli, fin da questo momento, ci dice che
furono la rovina della patria e delle sue armi.
E finalmente, dopo avere enumerato i principi e gli Stati, che nel
secolo XV tenevano divisa l'Italia, il Machiavelli conchiude: «Tutti
questi principali potentati erano di proprie armi disarmati. Il duca
Filippo, [312] stando rinchiuso per le camere, e non si lasciando
vedere, per i suoi commissarî le sue guerre governava. I Veneziani,
come e' si volsero alla terra, si trassero di dosso quelle armi, che in
mare gli avevano fatti gloriosi, e seguitando il costume degli altri
Italiani, sotto l'altrui governo amministravano gli eserciti loro. Il
Papa, per non gli star bene le armi in dosso, sendo religioso, e la
regina Giovanna di Napoli, per essere femmina, facevano per
necessità quello che gli altri, per mala elezione, fatto avevano. I
Fiorentini ancora alle medesime necessità ubbidivano, perchè,
avendo per le spesse divisioni spenta la nobiltà, e restando quella
repubblica nelle mani della mercanzia, seguitavano gli ordini e la
fortuna degli altri.» «Erano adunque le armi d'Italia divenute
mercenarie, in mano di condottieri che ne facevano mestiere, e che,
alleatisi per comune interesse, avevano ridotto la guerra a un'arte in
cui nessuno vinceva. Finalmente» «la ridussero in tanta viltà, che
ogni mediocre capitano, nel quale fosse alcuna ombra dell'antica
virtù rinata, gli avrebbe con ammirazione di tutta Italia, la quale, per
sua poca prudenza gli onorava, vituperati. Di questi adunque oziosi
principi e di queste vilissime armi sarà piena la mia istoria, alla quale
prima che io discenda, mi è necessario, secondo che nel principio
promisi, tornare a raccontare dell'origine di Firenze.» [313] E di qui
infatti comincia il secondo libro, che è veramente il primo della storia
fiorentina.
Riepilogando, adunque, l'Italia, invasa dai barbari, dei quali fu preda
per la decadenza dell'Impero, e per colpa di alcuni generali romani,
che, mossi da gelosie e da odî privati, li chiamarono, godette un
momento di pace e di felicità quando Teodorico, principe accorto,
seppe unirla, formandone uno Stato solo. Ma dopo la sua morte
riuscirono vani tutti gli sforzi fatti per mantenerla unita, e ciò
principalmente a cagione dei papi, i quali, per aumentare sempre più
il proprio potere, la vollero divisa, invitando sempre nuovi barbari e
nuovi stranieri, che in fatti vennero di continuo a lacerarla ed a
conculcarla. Vani del pari riuscirono gli sforzi dei Comuni a renderla
sicuramente libera, perchè nè essi nè altri seppero tenerla unita.
Tutti caddero finalmente in balìa degli eserciti mercenarî, che furono
l'ultima rovina d'Italia, la quale si trovò così esposta ai colpi di
chiunque volle assaltarla; e con la venuta di Carlo VIII ricominciò la
serie delle invasioni e delle calamità. Ecco quale è dunque il concetto
fondamentale del primo libro delle Storie. Da esso ne resulta
naturalmente un altro, che è veramente il pensiero dominante del
Machiavelli: unico rimedio a tanti mali che travagliarono l'Italia, era
la istituzione delle armi nazionali, comandate da un principe che
sapesse con esse difenderla, costituendo fortemente lo Stato,
emancipandolo dalla Chiesa e dall'aristocrazia feudale, assicurandone
con buone leggi la libertà per l'avvenire. Chi vorrà e saprà fare tutto
ciò, sarà veramente degno di salire in cielo, per sedere accanto agli
Dei.
Ed ora dobbiamo esaminare che cosa dice il Machiavelli della storia
interna di Firenze, nei tre libri che seguono.
Alcuni brani del libro I delle Storie del Machiavelli, messi a confronto
con altri delle Decadi di Flavio Biondo. [314]
Erano da Teodosio preposti alle Commiserat Theodosius in
tre parti dell'Imperio tre Imperio florens, tres potissimas
governatori, Ruffino alla Imperii partes tribus ducibus
orientale, alla occidentale gubernandas, Buffino
Stilicone, e Gildone orientalem, occidentalem
all'affricana; i quali tutti, dopo Stiliconi, et africanam Gildoni.
la morte del principe, Hic primus de morte
pensarono non di governarle, Imperatoris compertum
ma come principi possederle; habens, parvique faciens in
de' quali Gildone e Ruffino ne' puerorum manibus Imperii
primi loro principii furono vires, Africam sibi retinere
oppressi. Ma Stilicone, sapendo conatus est.... Eodem vero in
meglio celare l'animo suo, tempore Ruffinus Orienti
cercò d'acquistarsi fede coi praefectus, dum barbaris ad
nuovi imperatori, e dall'altra rebellionem concitatis,
parte turbare loro in modo lo Imperium sibi parare
Stato, che gli fosse più facile contenderet, Archadio curante,
dipoi l'occuparlo. E per fare loro interfectus est. Tertius ducum
nemici i Visigoti, gli consigliò Stillico, genere Vandalicus,
non dessero più loro la summam erat post Theodosii
consueta provvisione. Oltre a mortem apud novos principes
questo, non gli parendo che a gratiam consecutus.... Fuit vero
turbare l'Imperio questi nemici et ipse impiissimus, sed suam
bastassero, ordinò che i perfidiam maximis tegens
Burgundi, Franchi, Vandali ed simulationibus, nihil apertum
Alani, popoli medesimamente contra rempublicam est
settentrionali, e già mossi per molitus, quin potius affectatum
cercare nuove terre, assalissero Eucherio filio Imperium, non
le provincie romane. Privati prius invadere constituit, quam
adunque i Visigoti delle imperatores maximis
provvisioni loro, per essere calamitatibus involvisset.
meglio ordinati a vendicarsi Itaque primum omnium
della ingiuria, crearono Alarico immanes Svevorum,
loro re, ed assalito l'Imperio, Burgundionum, Alanorum et
dopo molti accidenti Vandalorum suorum gentes,
guastarono l'Italia, e presero e propriis excitas sedibus
saccheggiarono Roma concitavit ad romani Imperii
(Machiavelli, Istorie fiorentine, Galliarum provincias
Lib. I, p. 2-3). invadendas. Exinde Visigothos,
gentem ut noverat
ferocissimam, curavit stipendiis
privari ab imperatoribus....
cuius machinationis haec ratio
fuit, quod ipsos Visigothos,
rerum necessariarum indigentia
compulsos, optabat in Italiam
se conferre (Blondi,
Historiarum, ab Inclinatione
Romanorum libri XXXI, ed. cit.,
Dec. I, lib. I, pag. 7-8).
Nè fu l'isola di Brettagna, la Itaque romani cives, qui
quale oggi si chiama Britanniam frequentes diversis
Inghilterra, sicura da tanta respectibus inhabitabant, et ipsi
rovina, perchè temendo i simul Britanni, salutis
Brettoni di quei popoli che desperatione animos faciente,
avevano occupata la Francia, e arma ceperunt, et tunc quidem
non vedendo come l'imperatore Scotos Albienses, Pictosque, a
potesse difenderli, chiamarono quibus agitabantur, praelio
in loro aiuto gli Angli, popoli di superarunt, ac in ulteriorem
Germania. Presero gli Angli insulae partem recedere
sotto Votigerio loro re compulerunt. Sed paulo post,
l'impresa, e prima gli difesero, cum Britanni sese a Scotis
dipoi gli cacciarono dall'isola, e Pictisque diutius tueri
vi rimasero loro ad abitare, e diffiderent, Anglicos Saxones,
dal nome loro la chiamarono datis in stipendium pecuniis, ex
Anglia. Ma gli abitatori di proximis Germaniae littoribus
quella, sendo spogliati della conduxerunt praesidio
patria loro, diventarono per la affuturos. Qui quidem Saxones
necessità feroci, e pensarono, cognomine Anglici, duce
ancora che non avessero Vortigerio eorum rege, insulam
potuto difendere il paese loro, ingressi, Scotos atque Pictos
di poter occupare quello d'altri. represserunt praelio superatos.
Passarono pertanto colle Sed et ipsi postea mercenarii
famiglie loro il mare, ed Saxones, ambitione ducti,
occuparono quei luoghi che più magis Britonibus quam Picti et
propinqui alla marina Scoti hostes nocuerunt,
trovavano, e dal nome loro romanos enim cives et
chiamarono quel paese Britannorum primores, maiori
Brettagna (pag. 4-5). ex parte vario mortis genere
interfecerunt, ex eoque
tempore cooperunt Saxones
Anglici Britanniae dominari
(Dec. I, lib. II, pagine 20-21).
Campeggiando Attila re degli Et prima inter omnes mirabili
Unni Aquileia, gli abitatori di non magis modo quam loco
quella, poichè si furono difesi condi coepit veneta urbs, origo
molto tempo, disperati della cujus in hunc modum fuisse
salute loro, come meglio videtur. Athila Hunnorum rege
poterono, con le loro cose Aquileiam obsidente,
mobili sopra molti scogli, i quali Aquileienses, sicut ostendimus,
erano nella punta del mare Gradum Concordienses,
Adriatico disabitati, si Caprulas et Altinates Torcellum,
rifuggirono. I Padovani ancora, Maiorbum, Burianum,
veggendosi il fuoco propinquo, Amorianum, Costantianum et
e temendo che, vinta Aquileia, Aimanum populariter
Attila non venisse a trovarli, commigrarunt. Patavini autem,
tutte le loro cose mobili di più ea Aquileiae obsidione durante,
valore portarono dentro al sacra et supellectilem
medesimo mare, in un luogo preciosam cum imbelli
detto Rivo Alto, dove multitudine, in Rivumaltum
mandarono ancora le donne, i comportarunt, iuventute
fanciulli ed i vecchi loro, e la tutandis a potenti hoste
gioventù riserbarono in Padova, moenibus retenta.
per difenderla. Oltre a questi, Montesilicenses vero
quelli di Monselice con gli Adeustinique et Euganeorum
abitatori dei colli intorno, spinti collium incolae, Metamaucum
dal medesimo terrore, sopra gli et Albiolam, Pelestrinam
scogli del medesimo mare ne Clodiamque confugientes,
andarono. Ma presa Aquileia, Athilae terrorem declinavere....
ed avendo Attila guasta Patavini quidem plures
Padova, Monselice, Vicenza e potentioresque ditionis suae
Verona, quelli di Padova, ed i paludes, in quas sua miserant,
più potenti, si rimasero ad frequentavere, et aquis
abitare le paludi che erano elevatiora apud Rivumaltum
intorno a Rivo Alto; Dorsumque, cui duro a
medesimamente tutti i popoli soliditate fuit cognomen,
all'intorno di quella provincia, tenuere. Sic et caeteri Venetiae
che anticamente si chiamava provinciae populi, premente
Venezia, cacciati dai medesimi metu, ubicumque potuerunt
accidenti, in quelle paludi si eisdem in paludibus
ritrassero. Così, costretti da consederunt. Eam vero
necessità, lasciarono luoghi provinciam Abdua, Pado, lacu
amenissimi e fertili, ed in sterili, Benaco, Alpibus et Adriatico
deformi e privi di ogni comodità mari constat terminari. Per
abitarono. E per essere assai hunc modum populi
popoli in un tratto ridotti amoenissimis et uberrimis
insieme, in brevissimo tempo omnium Italiae soli in
furono quelli luoghi non solo regionibus nutriti, patriam
abitabili, ma dilettevoli, e avitosque lares commutavere,
costituite fra loro leggi ed informem in uliginem,
ordini, fra tante ruine d'Italia, stagnaque omni vel puri littoris
sicuri si godevano, ed in breve sterilitati, si libera sit per
tempo crebbero in riputazione securitatem electio,
e forze (p. 45-46). postponendam, ut nequaquam
dubitandum sit, illos Dei
munere coactos, cepisse loca
brevi futura optima, quae
tranquillis securisque rebus
nulla prudentia elegisset (Dec.
I, lib. III, p. 31).
Giustiniano morì, e rimase suo Coeperunt autem tunc urbs
successore Giustino suo Roma et Italia novam habere
figliuolo, il quale per il consiglio gubernationis, formam, ex qua
di Sofia sua moglie revocò dignitatem, gloriam et apud
Narsete d'Italia, e gli mandò orbem terrarum timorem magis
Longino suo successore. amiserunt quam omnibus, ex
Seguitò Longino l'ordine degli illis calamitatibus, quae eas
altri di abitare in Ravenna, ed centum et sexaginta annos
oltre a questo dette all'Italia attriverant, atque aliquando
nuova forma, perchè non Romam fecerant relinqui feris
costituì i governatori di et obscenis avibus habitandam.
provincie come avevano fatto i Longinus namque novum in
Goti, ma fece in tutte le città e Italiam adduxit magistratus
terre di qualche momento capi, nomen Exarchatus Italiae, qui
i quali chiamò duchi. Nè in tale interpetrabatur summus Italiae
distribuzione onorò più Roma magistratus. Et Ravennae se
che le altre terre, perchè tolto continens, nunquam ivit ad
via i consoli e il Senato, i quali urbem Romam vel qualis esset
nomi infino a quel tempo vi si inspiciendam. In
erano mantenuti, la ridusse administratione vero Italiae et
sotto un duca, il quale ciascun urbium, quae in Iustini
anno da Ravenna vi si imperatoris partibus cum Roma
mandava, e chiamavasi il et Ravenna duraverant, hunc
Ducato Romano, ed a quello primus servavit morem, ut non
che per l'Imperatore stava a provinciae aut regioni praeesset
Ravenna e governava tutta praeses sive quispiam
Italia, pose nome esarco. magistratus, sed singulae
Questa divisione fece più facile urbes, singula oppida a singulis
la rovina d'Italia, e con più custodirentur, regerenturque
celerità dette occasione ai magistratibus, quos appellavit
Longobardi di occuparla (p. duces. Parem itaque faciens
13). urbem Romam aliis Italiae vel
urbibus vel oppidis, hac una in
re illam honoravit, quod
impositum tunc magistratum
praesidem appellavit, sed qui
successerunt sunt appellati
duces, ut postea per multos
annos sic romanus appellaretur
Ducatus, sicut Narniensis
Spoletanusque est dictus.
Neque post Basilium, qui cum
Narsete consul fuit, vel
consules Roma habuit, vel
Senatum legitime coactum, sed
a duce graeculo homine, quem
exarchus ex Ravenna mittebat,
res romana per multa tempora
administrata est (Dec. I, lib.
VIII, p. 101-102).
Era Narsete sdegnato forte Nec satis fuit praestantissimum
contro l'Imperatore per essergli ducem, et optime de republica
stato tolto il governo di quella meritum privare, quod ille pro
provincia (l'Italia), che con la sua modestia videtur optasse,
sua virtù e con il suo sangue nisi et convicia procax
aveva acquistato, perchè a infaustaque romanis rebus
Sofia non bastò ingiuriarlo mulier addidisset: illi enim
rivocandolo, che ella vi comminata est futurum, ut
aggiunse ancora parole piene posthac non solum degeret
di vituperio, dicendo che lo privatus, sed quod eunuchum
voleva far tornare a filare con deceat dispartiendis inter
gli altri eunuchi; tantochè ancillas pensis a se deputetur.
Narsete ripieno di sdegno Qua indignitate non commoveri
persuase Alboino re dei non potuit vir ingentis spiritus
Longobardi, che allora regnava Narses, cui rerum a se
in Pannonia, di venire a gestarum magnitudinem et
occupare l'Italia (p. 13). pietatis integritatisque
conscientiam, cum tanta
ingratitudine atque nequitia,
mente et animo metienti ita
incensi sunt animi, ut continere
nequiverit quin adversus virum
et uxorem eo indignos imperio
suam ulcisceretur iniuriam.
Quamprimum itaque Longinum
in Italiam venturum intellexit,
secessit Neapolim, urbem
optime de se meritam. Ea in
urbe cum aliquot fuisset
menses, ad Alboinum regem
Longobardorum sibi
amicissimum misit, qui
suaderent, ut Pannoniam, quod
usu antea compertum erat,
semper novis barbarorum
incursibus expositam, linquens,
gentem longobardam
traduceret in Italiam, terram
omnium orbis terrarum
primariam, et cuius possessio
illos, etiam nolentes, ab orbis
imperium sublimaret (Dec. I,
lib. VII, p. 98-99).
Erano stati i Longobardi 232 Quantum vero attinet ad
anni in Italia, e di già non Longobardos, ea gens, ducentis
ritenevano di forestieri altro iam triginta et pene duobos
che il nome (p. 20). annis maiori Italiae portione
potita, nihil iam externi praeter
nomen retinebat (Dec. II, lib. I,
p. 163, che per errore è nella
stampa 167).
E così veniva l'Italia in questi Ut confidenter affirmemus sex
tempi ad essere sive imperatores sive reges
maravigliosamente afflitta, Italia oriundos, tres scilicet
sendo combattuta di verso le Berengarios, Guidonem,
Alpi dagli Unni, di verso Napoli Lotharium et Albertum, inter
da Saracini. Stette l'Italia in quos Rodulphus Burgundus et
questi travagli molti anni, e Ugo Arelatensis regnarunt, per
sotto tre Berengari che eos quinquagintaquinque annos
successero l'uno all'altro (p. Italiam motibus agitasse. Sed
22). ad rem. Dum Sararceni quos
Ioannes decimus pontifex et
Albericus marchio
superaverant, ex Gargano
monte unam, et Hungari aliam
Italiae partem saepe infestant,
etc. (Dec. II, lib. II, p. 180).
CAPITOLO XIII.
ebookgate.com