Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (2 votes)
24 views

Instant Access to Android Software Internals Quick Reference: A Field Manual and Security Reference Guide to Java-based Android Components 1st Edition James Stevenson ebook Full Chapters

Reference

Uploaded by

khaetiwodny
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
24 views

Instant Access to Android Software Internals Quick Reference: A Field Manual and Security Reference Guide to Java-based Android Components 1st Edition James Stevenson ebook Full Chapters

Reference

Uploaded by

khaetiwodny
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

Android Software Internals Quick Reference: A


Field Manual and Security Reference Guide to Java-
based Android Components 1st Edition James
Stevenson
https://textbookfull.com/product/android-software-internals-
quick-reference-a-field-manual-and-security-reference-guide-
to-java-based-android-components-1st-edition-james-
stevenson/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Java quick syntax reference Second Edition Olsson

https://textbookfull.com/product/java-quick-syntax-reference-second-
edition-olsson/

textboxfull.com

Java EE 6 Pocket Guide A Quick Reference for Simplified


Enterprise Java Development 1st Edition Gupta Arun

https://textbookfull.com/product/java-ee-6-pocket-guide-a-quick-
reference-for-simplified-enterprise-java-development-1st-edition-
gupta-arun/
textboxfull.com

Learn Android Studio 4 - Efficient Java-Based Android Apps


Development 2nd Edition Ted Hagos

https://textbookfull.com/product/learn-android-studio-4-efficient-
java-based-android-apps-development-2nd-edition-ted-hagos/

textboxfull.com

Android Studio 3 3 Development Essentials Android 9


Edition Developing Android 9 Apps Using Android Studio 3 3
Java and Android Jetpack Neil Smyth
https://textbookfull.com/product/android-studio-3-3-development-
essentials-android-9-edition-developing-android-9-apps-using-android-
studio-3-3-java-and-android-jetpack-neil-smyth/
textboxfull.com
Java in a Nutshell A Desktop Quick Reference 7th Edition
Benjamin J. Evans

https://textbookfull.com/product/java-in-a-nutshell-a-desktop-quick-
reference-7th-edition-benjamin-j-evans/

textboxfull.com

Quick Reference Guide to Pediatric Care 2nd Edition Deepak


M. Kamat

https://textbookfull.com/product/quick-reference-guide-to-pediatric-
care-2nd-edition-deepak-m-kamat/

textboxfull.com

Learn Java for Android Development Friesen Jeff

https://textbookfull.com/product/learn-java-for-android-development-
friesen-jeff/

textboxfull.com

Oracle IaaS: Quick Reference Guide to Cloud Solutions 1st


Edition Okcan Yasin Saygili (Auth.)

https://textbookfull.com/product/oracle-iaas-quick-reference-guide-to-
cloud-solutions-1st-edition-okcan-yasin-saygili-auth/

textboxfull.com

Managing infectious diseases in child care and schools a


quick reference guide Aronson

https://textbookfull.com/product/managing-infectious-diseases-in-
child-care-and-schools-a-quick-reference-guide-aronson/

textboxfull.com
James Stevenson

Android Software Internals Quick


Reference
A Field Manual and Security Reference Guide to
Java-based Android Components
1st ed.
James Stevenson
London, UK

Any source code or other supplementary material referenced by the


author in this book is available to readers on GitHub via the book’s
product page, located at www.​apress.​com/​9781484269138. For more
detailed information, please visit http://​www.​apress.​com/​source-code.

ISBN 978-1-4842-6913-8 e-ISBN 978-1-4842-6914-5


https://doi.org/10.1007/978-1-4842-6914-5

© James Stevenson 2021

This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.

The use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

The publisher, the authors and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

Distributed to the book trade worldwide by Apress Media, LLC, 1 New


York Plaza, New York, NY 10004, U.S.A. Phone 1-800-SPRINGER, fax
(201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit
www.springeronline.com. Apress Media, LLC is a California LLC and the
sole member (owner) is Springer Science + Business Media Finance Inc
(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
Table of Contents
Chapter 1:​Introduction
What Is This Book
What This Book Is Not
Chapter 2:​Android Versions
Chapter 3:​Fundamentals
Android Sandbox
Application Components
Activities
Broadcast Receivers
Content Providers
Manifest
Permissions
Context
Application Context
Activity Context
The Activity Life Cycle
onCreate()
onStart()
onResume()
onPause()
onStop()
onRestart()
Android Users
Linux Users
Android Users
Chapter 4:​Intents
Starting Components
Intent Attributes
Core Attributes
Additional Attributes
Actions
Categories
Extras
Flags
Task Stack
Intent Filters
Chapter 5:​Application Names, Android Package Name, and ID
Java Package Name
Package ID
Retrieving Package ID
Application ID
Suffix and Flavor
Application Name
Retrieving Application Name
Chapter 6:​Storage
Partitions
External and Internal Storage
Text Files
Databases
Shared Preferences
File Providers
Assets Folder
Resources
Chapter 7:​Android Unique Identifiers
Google Play Advertising ID
Android ID (Secure Settings Android ID – SSAID)
SIM Serial Number
Phone Number
IMEI and MEID
Chapter 8:​Obfuscation and Encryption
Logging
Standard Logging
Final Constant Variables
Using .​isLoggable
Dynamically Checking If Debuggable
ProGuard
Enabling ProGuard
The ProGuard Mapping File
The ProGuard Allow-List
The Different Types of Keep
Entry Points
Example Rules
Public Key/​Certificate Pinning
AES Encryption
Chapter 9:​Services, Launchers, and Components
Long-Running Services
Triggers
Services
IntentService, AlarmManager, and BootComplete
Foreground Services
JobScheduler
Work Managers
Threading
AsyncTasks
Modifying a Component’s State
Statically Modifying Component State
Dynamically Modifying Components
Creating an Android Launcher
Creating a Launcher Application
Additional Functionality
Chapter 10:​Reflection and Class Loading
Reflection
Making an Instance of a Class
.​getDeclaredMetho​d Compared With .​getMethod
Static Methods
Private Constructors
Initialized Classes as Fields of Other Classes
Class Loading
Chapter 11:​The Android Shell
Running Commands Programmatically​
Chapter 12:​Decompiling and Disassembling Android Applications
Decompiled Java
Disassembled Dalvik Bytecode (Smali)
Extracting APKs from Running Devices
Chapter 13:​Closing Thoughts
Index
About the Author
James Stevenson
has been working in the programming
and computer security industry for over
4 years, and for most of that has been
working as an Android software
engineer. Prior to this, James graduated
with a BSc in computer security in 2017.
James has featured articles on both
personal websites and industry
platforms such as Infosecurity Magazine -
covering topics from security principles
to android programming and security to
cyber terrorism.
At the time of writing, James is a full-
time security researcher, part-time PhD student, and occasional
conference speaker. Outside of Android internals, James’ research has
also focused on offender profiling and cybercrime detection
capabilities. For more information and contact details, visit
https://JamesStevenson.me .
About the Technical Reviewer
Peter Späth
Graduated in 2002 as a physicist and soon afterward became an IT
consultant, mainly for Java-related projects. In 2016 he decided to
concentrate on writing books on various subjects, with a primary focus
on software development. With a wealth of experience in Java-related
languages, the release of Kotlin for building Android apps made him
enthusiastic about writing books for Kotlin development in the Android
environment.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer
Nature 2021
J. Stevenson, Android Software Internals Quick Reference
https://doi.org/10.1007/978-1-4842-6914-5_1

1. Introduction
James Stevenson1
(1) London, UK

In 2016 there were more than five million Android developers


worldwide. Three years later, in 2019, there were 2.5 billion Android
devices in circulation across the world. There is no doubt that Android
is a massively adopted operating system, and not going anywhere
anytime soon.
This book has been designed for Android software engineers new
and old, with a focus away from typical UI design. This book instead
focuses on the parts of Java and the Android system that typically go
forgotten when learning to build applications. This book will serve as a
reference guide for techniques from device and user unique identifiers
to ProGuard obfuscation to long-running services - in turn digging into
some of the principles not intrinsically obvious from the get-go.
As the name may suggest, this book won’t be covering Android UI
development, nor will it be covering low-level C, or Kernel techniques.
Instead, this book will be focusing on easily digestible, useful, and
interesting techniques in Java and the Android system.

What Is This Book


An Android Java programming reference guide for non-UI elements.
This book covers the Android operating system from Android 4.4 to
11.0.
What This Book Is Not
This book doesn’t include an introduction tutorial for Java; if you’re
looking for this, there are many other great resources out there.
This book doesn’t cover any low-level C programming, Kernel
interaction, or vulnerability research.
While one or two aspects of the Android UI may be covered in this
book, it will not be a key focus.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer
Nature 2021
J. Stevenson, Android Software Internals Quick Reference
https://doi.org/10.1007/978-1-4842-6914-5_2

2. Android Versions
James Stevenson1
(1) London, UK

Android 1.0 was released on September 23, 2008; since then the
operating system has gone through countless changes. Table 2-1
denotes the different versions of Android (starting from version 1.5
Cupcake).
The API level in Android defines the supported API functionality on
that device. If using a device’s shell prompt (e.g., via the command adb
shell, which is available as part of the Android platform tools), you
can return the system property that relates to the current API level by
running getprop | grep sdk. This can also be done via adb
(Android Debug Bridge) from a connected machine.
The following shows an example output of this command as run on a
Google Pixel 4a running Android 11:

[ro.build.version.min_supported_target_sdk]: [23]
[ro.build.version.preview_sdk]: [0]
[ro.build.version.preview_sdk_fingerprint]: [REL]
[ro.build.version.sdk]: [30]
[ro.product.build.version.sdk]: [30]
[ro.qti.sdk.sensors.gestures]: [false]
[ro.system.build.version.sdk]: [30]
[ro.system_ext.build.version.sdk]: [30]
[ro.vendor.build.version.sdk]: [30]

Table 2-1 Android Release Versions


Version Codename API Release Date Linux Kernel Version
Level
1.5 Cupcake 3 April 2009 2.6.27
1.6 Donut 4 September 2.6.29
2009
2.0 Eclair 5 October 2.6.29
2009
2.0.1 Eclair 6
2.1 Eclair 7
2.2.x Froyo 8 May 2010 2.6.32
2.3 -> Gingerbread 9 December 2.6.35
2.3.2 2010
2.3.3 -> Gingerbread 10
2.3.7
3.0 Honeycomb 11 February 2.6.36
2011
3.1 Honeycomb 12
3.2.x Honeycomb 13
4.0.1 -> Ice Cream 14 October 3.0.1
4.0.2 Sandwich 2011
4.0.3 -> Ice Cream 15 .. ..
4.0.4 Sandwich
4.1.x Jelly Bean 16 July 2012 3.0.31
4.2.x Jelly Bean 17 3.4.0
4.3.x Jelly Bean 18 3.4.39
4.4 -> KitKat 19 October 3.10
4.4.4 2013
5.0 Lollipop 21 June 2014 3.16.1
5.1 Lollipop 22
6.0 Marshmallow 23 October 3.18.10
2015
7.0 Nougat 24 August 2016 3.18.48/4.4.0
Version Codename API Release Date Linux Kernel Version
Level
7.1 Nougat 25
8.0.0 Oreo 26 August 2017 3.18.72/4.4.83/4.9.44
8.1.0 Oreo 27 3.18.70/4.4.88/4.9.56
9 Pie 28 August 2018 4.4.146/4.9.118/4.14.61
10 Android 10 (Q) 29 September 4.9.191/4.14.142/4.19.71
2019
11 Android 11 (R) 30 September 4.14.y/4.19.y/5.4.y
2020
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
J. Stevenson, Android Software Internals Quick Reference
https://doi.org/10.1007/978-1-4842-6914-5_3

3. Fundamentals
James Stevenson1
(1) London, UK

Android Sandbox
Android runs under a multiuser Linux system which means that each application, and its
storage, runs under a separate user. This means that under normal circumstances, applications
cannot read another application’s data or internal storage. Each process uses its own virtual
machine (VM) which segregates applications. Prior to API level 21 (Android 5), this would have
been a Dalvik Virtual Machine, and in later versions will instead use the Android Runtime
(ART). Both operate in similar fashions, where they simulate a device’s CPUs, registers, and
other features while running an application’s compiled Dalvik bytecode. ART, however, is
considered to have many performance improvements.
In these VMs applications only have access to the components that they require to run (a
policy of least privilege). These individual process VMs are created by Zygote1 (zai·gowt).
Zygote is launched by the Android runtime at startup, with root permissions, with the first
virtual machine and all shared Java classes and resources. When a new application wants to
launch, a new Zygote process is forked and the application is bound to the thread of the new
process, and its code is run inside of it, nonrequired and nonrequested permissions are
dropped by Zygote so that the application only possesses the necessary permissions.

Application Components
Activities
Activities are the main entry points for Android applications. Akin to a single web page, an
activity is a single screen which in general will only remain running while in the foreground.
While not all activities have to be visible, most standard application activities will be. An activity
can be programmatically implemented by extending the Activity class .

Services
In general terms services are a utility in Android for providing functionality in the background
while an application is not currently running in the foreground, for example, a music player, an
email client polling for emails, or a maps application. The preferred technology used for tasking
services has changed in Android over the years from using Services to using
JobSchedulers. These will be discussed more in Chapter 10.

Broadcast Receivers
Another entry point to the application is where the system, other applications, and the
application itself can “broadcast” events that the application then receives. Broadcast receivers
have restricted functionality (where, as a general rule, they can only run for 10 seconds before
being considered as unresponsive2) and, because of this, will normally start another form of
long-running service such as a foreground Activity or a JobScheduler. A broadcast
receiver is implemented by extending the BroadcastReceiver class. These will be discussed
more in Chapter 4.

Content Providers
Content providers are used to manage sets of application data so that they are sharable with
other applications on a device. Using a URI other applications can query or modify the data
even if the application the URI belongs to is not currently running. Examples include images,
text files, SQLite databases, etc.

Manifest
An application’s manifest file 3 is created precompilation and cannot be edited during runtime.
These xml-like files, called AndroidManifest.xml, detail all of the components in a single
application (activities, broadcast receivers, services, etc.). The manifest file also details
permissions that the application requires, the minimum API level, as well as hardware and
software features used by the application (such as a camera). While an application will only
have one manifest file, imported libraries may have their own. Due to this, during the build,
Gradle will merge all of these individual manifest files; the result is called a merged manifest.4
This is evident when reversing an Android application (APK file), as (if using libraries) the
reversed manifest will be significantly larger and have additional elements than the original
premerged manifest .
An example of a simple AndroidManifest.xml file can be seen here. In this example the
package is called simple_app, it uses the FINGERPRINT permission (as described below), and
its main entry point is an activity called MainActivity which has two intent filters:

<?xml version="1.0" encoding="utf-8"?>


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.simple_app">

<uses-permission
android:name="android.permission.USE_FINGERPRINT" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"
/>

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Permissions
Permissions in Android follow the least privilege model where specific types of functionality
are only given to applications that specifically request for them. There are two main types of
permission: manifest permissions and runtime permissions (of which commonly fall into the
“dangerous” permissions category). Both runtime and manifest permissions must be declared
in the Android manifest; however, in addition, runtime permissions must be requested at
runtime prompting the user with a dialogue (as seen in Figure 3-1) on if they are happy for the
application to use the stated functionality. Runtime permissions were implemented in API level
23; however, previous to this a user will be shown all runtime permissions prior to install
instead.

Figure 3-1 Example of a runtime permission as seen by the user

As previously stated permissions are given a permission type based on the risk they pose to
users, the Android system, or other applications on a device. A summary of all permission types
can be seen in Table 3-1.5

Table 3-1 Permission Types

Permission Risk Description


Type
Normal Low The default permission type. Providing the application with isolated application-level
features such as BLUETOOTH, NFC, and INTERNET.
Dangerous High Providing the application with access to private data or an aspect of device control such
as WRITE_EXTERNAL_STORAGE, ACCESS_FINE_LOCATION, and CAMERA.
Unlike the normal permission type, a runtime permission request has to be accepted by
the user (at runtime via a button click) before permissions are granted by the system (or
at install time on devices prior to API level 23).
Signature Critical This permission is only granted if the application requesting the permission is signed by
the same certificate as the application that declared the permission.
This is commonly used to restrict a permission type to system/preinstalled
applications. These permissions normally grant either mass access to the control of the
Permission Risk Description
Type
system and other applications or circumvent Android security mechanisms. This
includes MANAGE_EXTERNAL_STORAGE, READ_LOGS, and CAPTURE_AUDIO_OUTPUT.
In addition to these types, additional flags can be applied to permissions including
privileged and development which refer to the rights given to system and development
applications, respectively.6
Finally there are two additional permission types that need to be considered in identifying
what applications can perform what actions:
Hard-restricted permission - Where a permission cannot be held by any application on
the device unless the permission has been allow-listed by the installer application
Soft-restricted permission - Where a permission cannot be help by any application on
the device, in its full form, unless the permission has been allow-listed by the installer
application
When debugging a device, permissions that would normally not be available for a standard
application (such as a permission with the Signature permission type) can be granted using
adb. As an example for the READ_LOGS permission the following command can be used to
grant the permission adb shell pm grant <Package ID>
android.permission.READ_LOGS. To retrieve an application’s Package ID, see Chapter 5
or Chapter 12.
An example of a manifest permission:

<uses-permission android:name="android.permission.
WRITE_EXTERNAL_STORAGE "/>

An example of a runtime permission request:

if (Build.VERSION.SDK_INT >= 23) {


// Notification will not be shown unless the correct manifest
permission is set
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1234);
}

At the time of writing the Android specifications,7 list 166 different manifest permissions.
Table 3-2 shows a subset of the most common of these permissions as well as their API and
permission levels.
Table 3-2 Android Permissions

Name Permission API Description


Level
ACCESS_COARSE_LOCATION Dangerous 29+ Access to approximate location,
via non-GPS providers (such as
network provider).
ACCESS_FINE_LOCATION Dangerous 1+ Access to a specific location, via
GPS and network provider.
ACCESS_NETWORK_STATE Normal 1+ Access to ConnectivityManager
responsible for, among other
Name Permission API Description
Level
things, monitoring network
connection (Wi-Fi-GPRS, UMTS,
etc.).
ACCESS_WIFI_STATE Normal 1+ Access to WifiManager
responsible for viewing a list of
configured networks, the current
active network, and results of
access point scans.
ANSWER_PHONE_CALLS Dangerous 26+ Allows the application to answer
an incoming call.
BATTERY_STATS Signature|privileged|development 1+ Allows for the aggregation of
battery information and statistics.
BLUETOOTH Normal 1+ Allows for the pairing and
connection with Bluetooth
devices.
CALL_PHONE Dangerous 1+ Allows the application to call
without sending an intent to the
dialer application (in turn not
needing to notify the user via the
UI).
CALL_PRIVILEGED Not for use by third-party 1+ A less restricted version of the
applications CALL_PHONE permission allowing
the application to call any phone
number including emergency
numbers.
CAMERA Dangerous 1+ Provides access to the device’s
cameras.
CAPTURE_AUDIO_OUTPUT Prohibited to third-party 19+ Allows for nonrestricted access to
applications record audio from the device’s
microphone.
CHANGE_WIFI_STATE Normal 1+ Allows for the application to
modify the device’s network
configuration and to connect to
and disconnect from Wi-Fi access
points.
DELETE_PACKAGES Prohibited to third-party 1+ Allows for the removal of an
applications application. As of Android 7 user,
confirmation is required if the
application requesting the removal
is not the same as the application
that installed it.
INSTALL_PACKAGES Prohibited to third-party 1+ Allows an application to install
applications another.
INTERNET Normal 1+ Allows an application to open
network sockets.
MANAGE_EXTERNAL_STORAGE Signature|appop|preinstalled 30+ Due to the implementation of
scoped storage in Android 10
(applications having a sandboxed
Name Permission API Description
Level
external storage), this permission
allows for the broad managing of
the external storage space.
NFC Normal 9+ Allows for I/O operations over
NFC (near-field communication).
PROCESS_OUTGOING_CALLS Dangerous and hard restricted 1–29 Allows an application to see and
redirect all outgoing calls.
READ_CONTACTS Dangerous 1+ Allows for the reading of the user’s
contact information.
READ_EXTERNAL_STORAGE Dangerous, soft restricted 16+ Allows for an application to read
from external storage.
After API 19 this permission is not
required to read the application’s
scoped storage. As of the forced
implementation of scoped storage
in API level 29, this only provides
read only acceess.
READ_LOGS Prohibited to third-party 1+ Allows for reading system log
applications information, such as those created
by DropBoxManager.
READ_PHONE_NUMBERS Dangerous 26+ Allows for the application to read
all of the device’s phone numbers.
By default this permission is
exposed to instant applications.
READ_PHONE_STATE Dangerous 1+ Includes the
READ_PHONE_NUMBERS permission.
Allows for access to device/phone
information such as the current
cellular network.
READ_SMS Dangerous and hard restricted 1+ Allows for the reading of SMS
messages already received by the
device.
REBOOT Prohibited to third-party 1+ Allows for the rebooting of the
applications device.
RECEIVE_BOOT_COMPLETED Normal 1+ Allows an application to receive
the
Intent.ACTION_BOOT_COMPLETED
intent. This intent is broadcast
after the system has finished
booting.
RECEIVE_MMS Dangerous and hard restricted 1+ Allows for an application to
monitor incoming MMS messages.
RECEIVE_SMS Dangerous and hard restricted 1+ Allows for an application to
monitor incoming SMS messages.
RECORD_AUDIO Dangerous 1+ Allows for an application to record
audio.
Name Permission API Description
Level
REQUEST_DELETE_PACKAGES Normal 26+ Allows for an application to
request for either itself or another
application to be deleted. This will
require user interaction.
REQUEST_INSTALL_PACKAGES Signature 23+ Allows for an application to
request for the installing of an
application. This will require user
interaction.
SEND_SMS Dangerous and hard-restricted 1+ Allows for the sending of SMS
permission messages.
SET_PREFERRED_APPLICATIONS Normal 1–15 Allows the application to modify
the user’s preferred (default)
applications – including web
browser and installer.
SET_TIME Prohibited to third-party 8+ Allows for the setting of the
applications system time.
USE_BIOMETRIC Normal 28+ Allows for the use of device-
supported hardware.
USE_FINGERPRINT Normal 23– Allows for the use of device
28 fingerprint hardware. Replaced by
the USE_BIOMETRIC permission in
Android API level 28.
WAKE_LOCK Normal 1+ Allows the application to
initiate PowerManager Wake
Locks which can prohibit the
device from sleeping or from the
screen dimming.
WRITE_EXTERNAL_STORAGE Dangerous 4+ Allows for the writing to the
device external storage. Also
grants the
READ_EXTERNAL_STORAGE
permission.
After API 19 this permission is not
required to read/write in the
application’s scoped storage. As of
the forced implementation of
scoped storage in API level 29, this
only allows for an application to
read their own storage data.

Context
Another core component in Android is Context. Colloquially referred to as the “god” class,
Context8 in Android is an interface for retrieving global information about an application’s
environment. It allows for accessing application-specific resources as well as application-level
operations such as broadcasting, receiving intents, and launching activities. Some use cases
include
Accessing the location of the application’s internal storage
Sending a Toast or Notification dialogue
Setting an ImageView in an activity
Retrieving the system package manager
There are two main types of Context: an application context and an activity context. Both of
these types of Context are bound to the life cycle of their respective area - where an application
context is tied to the life cycle of the application and the activity context is bound to the life
cycle of its activity. This means that if either is destroyed, then their respective context is
garbage collected.
In addition to these two subclasses of Context, there is also ContextWrapper which can
be used with the Context method getBaseContext(). Context Wrapper allows for a proxy
Context to be used, where it is then possible to modify the behavior of the object without
changing the original Context.

Application Context
The following returns the application context. When the application is destroyed, it will be
garbage collected.
Retrieve application context:

getApplicationContext()

Activity Context
When in an Activity or subclass of Activity, use this to return the activity context. When
the activity is destroyed, then the activity context is garbage collected.
Retrieve activity context from inside activity:

this

The Activity Life Cycle


As part of using a device, the individual activities of an application can enter many different
states. The activity class provides useful callbacks that are triggered when these states are
entered so that an application can respond appropriately. The full activity life cycle can be seen
in Figure 3-2.
Figure 3-2 Android application activity life cycle

onCreate()
This callback is called when the activity is first created. This method takes a parameter of
savedInstanceState which is a bundle containing the activity’s previously saved state or
null if it hasn’t existed previously.

onStart()
This callback prepares the activity to enter the foreground and makes it visible to the user. This
callback is always called each time the activity starts, unless resuming.

onResume()
When entering this state, the activity is ready to be interacted with by the user and enters the
foreground. Interrupt events may occur such as a phone call or the user moving to another
activity - if this occurs the activity moves to the onPause() callback.

onPause()
This callback indicates that the activity is no longer in the foreground; however, it does not
necessarily mean that it is about to be destroyed.

onStop()
This callback is called before the activity is destroyed when the activity is no longer visible to
the user. This is where applications should release resources. The onStop() callback is the
last callback an activity will receive.

onRestart()
This activity is called after the onStop() callback when the activity is being redisplayed to the
user. This is followed by onStart() and onResume().
Android Users
In Android there are two distinct concepts that could both be identified as “users”.

Linux Users
Android is a multiuser Linux system where each application is sandboxed, meaning that each
application is represented by a different user. The Android system assigns each unique
application certificate (the certificate that the apk file is signed with) a unique Linux user ID, in
turn also setting the permission of all of the application’s files so that only the specified Linux
user ID can access them.9 This means that if two applications are signed by the same certificate,
then they are placed in the same sandbox. This is also required when it comes to the
Signature permission type (discussed earlier) where if a permission has this type, then it can
only be used by applications with the same certificate as the application that created the
permission (commonly seen to prohibit nonsystem applications from accessing system
permissions).
To view an application’s Linux user ID, you can use adb as root to traverse to the file system
of the application (e.g., /data/data/com.android.chrome) and use the ls -la
command as can be seen in Figure 3-3.

Figure 3-3 Example of Linux user ID seen in the adb shell

To view the application process ID programmatically:

Log.v("Application Process ID",


String.valueOf(android.os.Process.myUid()));

The shell command id -u can also be used via adb or via the runtime environment, as
follows:

id -u

Android Users
The second concept of users in Android is designed for multiple end users10 of a device,
designed to allow for multiple users who use the same Android device. This is achieved by
having distinct application data and some unique settings per account. In turn this supports for
multiple users to run in the background while another user is active.
The users currently active on a device can be found under the /data/user directory (as
seen in Figure 3-4) or via the UI User screen (as seen in Figure 3-5). As different users will have
their own internal and scoped storage, it is important to use the corresponding method calls
(e.g., using the Context method getFilesDir()) to retrieve the correct file paths as these
may change over time. A user cannot access the internal storage of another user even if it is for
the same application.
Figure 3-4 Example of Android user IDs, as seen in adb shell

Figure 3-5 End user’s view of different users on a device

Footnotes
1 “The Zygote Process - Masters on Mobile - Medium.” https://medium.com/masters-on-mobile/the-
zygote-process-a5d4fc3503db. Accessed 11 May. 2020.

2 “BroadcastReceiver | Android Developers.” 30 Sept. 2020,


https://developer.android.com/reference/android/content/BroadcastReceiver. Accessed
6 Dec. 2020.
3 “Application Fundamentals | Android ....” 3 Jun. 2019,
https://developer.android.com/guide/components/fundamentals. Accessed 11 May. 2020.

4 “Merge multiple manifest files | Android Developers.” 3 Jun. 2016,


https://developer.android.com/studio/build/manifest-merge. Accessed 11 May. 2020.

5 “<permission> | Android Developers.” 27 Dec. 2019,


https://developer.android.com/guide/topics/manifest/permission-element. Accessed 8
Dec. 2020.

6 “R.attr | Android Developers.” https://developer.android.com/reference/android/R.attr.


Accessed 8 Dec. 2020.

7 “Manifest.permission | Android Developers.” 30 Sept. 2020,


https://developer.android.com/reference/android/Manifest.permission. Accessed 6 Dec.
2020.

8 “Context | Android Developers.”


https://developer.android.com/reference/android/content/Context. Accessed 11 May. 2020.

9 “Application Signing | Android Open Source Project” 28 Oct. 2020,


https://source.android.com/devices/tech/admin/multi-user. Accessed 26 Dec. 2020.

10 “Supporting Multiple Users | Android Open Source Project.” 18 Feb. 2020,


https://source.android.com/devices/tech/admin/multi-user. Accessed 11 May. 2020.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
J. Stevenson, Android Software Internals Quick Reference
https://doi.org/10.1007/978-1-4842-6914-5_4

4. Intents
James Stevenson1
(1) London, UK

Intents are one of the core inter-process communication (IPC) mechanisms in Android,
allowing for applications to communicate (e.g., send data or initiate an action) with other
Android components (including applications) even if the recipient is not currently running.
There are two main categories of intent in Android, these being:
Explicit - Explicit intents are intents that specify the application or both the application and
component that will action the request.
Implicit - Implicit intents are more vague and specify a type of action that is desired (e.g.,
opening a camera or location application).
In addition to these two main categories of intents, where the message is directly sent to a
specific application or service, broadcast intents can also be sent. These broadcast messages,
which can be sent by the Android system or applications, are simultaneously received by all
applications on the device that have previously registered for the specific broadcast action
type. In some cases special permissions may be required to register for specific broadcasts
(e.g., in the case of the BOOT_COMPLETE permission which allows for the receiving of an
ACTION_BOOT_COMPLETED intent when the Android system finishes loading after startup).

Starting Components
Outside of the two categories of intent, there are three main methods for sending intents:
Starting an activity - An instance of an activity can be started by passing an initialized
Intent object to either the startActivity() or startActivityForResult() context
methods.
Starting a background service - Prior to Android 5.0 (API level 21), a background
Service can be started by passing an initialized Intent object to the startService()
context method. Post API level 21, this can be used to start JobScheduler components
instead.
Sending a broadcast - While the system sends many broadcasts at a regular frequency, such
as TIME_TICK and BOOT_COMPLETE, it is also possible for an ordinary application to send
its own broadcasts. In general, broadcasts are a type of intent that can be received by
multiple applications simultaneously. Such a broadcast can be sent with the
sendBroadcast() or sendOrderedBroadcast() context methods.

Intent Attributes
Another Random Scribd Document
with Unrelated Content
Though Sir John had severed his official connection with
Morocco, he retained his villa at Ravensrock. Thither, after an
interval, he returned to spend the winters. During the first year of
absence after his retirement, on learning of the serious illness of the
companion of so many of his sporting days, Hadj Hamed, the chief of
the boar-hunters, he writes to his daughter, enclosing a letter to be
delivered by his little grandson to the dying man:—

Wiesbaden, March 31, 1887.


Your letter of the 23rd has just reached A. I cannot tell you how grieved I feel
from the account you give of dear old Hadj Hamed, and I fear much I may never
see his kind face again. As I thought it would please and cheer him if I wrote a few
lines to him as an old friend, I have written in my bad Arabic the enclosed note,
which dear Jock will perhaps deliver in person to him. It is merely to say I am so
sorry to hear from you he is ill, that I pray God he will keep his health, and that we
shall meet in October next and hunt together, and that I look upon him as a brother
and a dear friend.

In 1887 he returned to winter at Tangier, and though a


septuagenarian, was as keen a sportsman as ever. Writing in
October he says:—

I have already bought a nag for myself, and, like myself, short and dumpy, but
with legs that will not fail or stumble with twelve stone seven on his back, for if I fall
I do not stot up as of old, but make a hole in the ground and stick there.

The winter of that year found him riding hard after pig on his little
cob, and untiring in pursuit of game. He writes to his son-in-law an
account of one of these hunts in which he had a narrow escape from
injury:—

The hunt has been a successful one, and barring three wounded horses, one
dog killed, a couple of spills, and ——— rather shaken, all’s well. Six or seven
lances smashed—not by me, except one dumpy lance, of which anon.
A. went off early on Monday the 12th to put the camp in order. I followed her
with mother. We lunched in the Ghaba Sebaita. At 3 p.m. I left her, so as to be
early in camp to see that all was right. On reaching the head of the lake, I met a
hunter who told me he had seen a very large boar come out of the cork-wood and
lie down on the border of the lake. I sent a messenger for the hunters, who were
returning, and awaited them on my ‘kida,’ sine lance. When they arrived they also
were lanceless; but the Sheríf having come up with his lance, and Mahmud with
him with another, I induced the Sheríf to make Mahmud dismount and give his
lance to J. G. I took from a beater a short lance (five feet), and thus armed we
entered the lake. W., with a lance, was seen in the distance and beckoned for;
Colonel C., with his party, also arrived armed with a lance. J. G. started the boar,
and away we went in six inches of water. As soon as J. G. approached, the boar
turned and charged, smashing his lance. Spying his horse coming up in the
distance, as it was being led to the camp, he galloped off and got the fresh horse
and his own lance.
Colonel C. followed the boar with me, and as soon as he neared the beast, it
turned and charged; but received a severe wound, the lance remaining in the boar.
Then, as no sound lance remained, I presented myself. No sooner did the boar
hear me in his wake than round he came, at a hundred miles an hour, upon my
short lance, the point of which, being badly tempered and very blunt, bent to an
angle of ninety degrees. My gallant little horse leapt over the pig, as he passed
under his barrel. Up came J. G. with his fresh lance and gave it hard, but still the
boar went on, in deeper and deeper water, making for Arára[67]. Some greyhounds
of the Sheríf’s were slipped, and the gallant boar fought them all. The hunters
came up, and the boar still moved towards Arára. I asked a Moor with a hatchet to
knock the brave beast on the head, but he declined the task; and, as there was no
second lance, the boar moved on towards Arára very slowly, fighting the dogs.
Finding that neither prayers nor abuse were attended to by the hunters, I jumped
off my nag into the water, knee deep, and taking the hatchet advanced on the pig.
He charged when I got within five yards of him, and I broke the hatchet on his skull
and retreated; the greyhounds laid hold behind, and the brave beast was done for.
I got rated by J. G., who saw it, and by A. afterwards; but mother is to be kept in
the dark about this ‘tomfoolery,’ as A. says. The fact is, there was no danger, for
the greyhounds came to the rescue when the boar charged.

On another occasion, after a successful day’s pigsticking thirteen


miles from Tangier, he and his younger daughter, riding home in the
evening, saw two Bonelli eagles and six great bustards. The latter
allowed them to approach within forty yards. ‘This,’ he writes, ‘was
too much for my old sporting blood, so I invited J. G. to join me, and
next day we went out to the site and viewed three ‘hobar’ (great
bustards), and were after them twice, but could not get near for a
shot. I shot a Bonelli eagle from my pony, who, even after a thirty
miles’ ride yesterday, was very larky, but stood fire like an old war-
horse.’
Not only did Sir John retain to the end of his life all his love of
sport, but, like most sportsmen, he dwelt with pleasure on his
recollections of past encounters. Many of his reminiscences he put
together, now that he was comparatively an idle man, in the form of
articles which were printed in Murray’s Magazine for 1887, under the
title of ‘Scraps from my Note-Book.’ Some of these, supplemented
with additions subsequently made by himself or with details since
gathered from his letters, are reproduced here, though they for the
most part belong to a much earlier date. Thus, on the subject of
boar-hunting, he wrote:—

The Moorish hunters are generally small farmers or peasants from


the villages around Tangier, who join the hunt solely from love of
sport. Some of them act as beaters, wearing leathern aprons and
greaves—such as the ancient Greek peasantry wore—to protect
their legs. Of these, some carry bill-hooks to cut their way through
the thicket, others long guns. They are accompanied by native dogs
(suggestive of a cross between a collie and a jackal), with noses that
can wind a boar from afar, and do good service.
As the thickets where the animals lie are for the most part
bordered by the sea on one side, and by lake or plain on the other,
the boar, when driven, generally make straight for the guns; and we
were wont to have capital sport, shooting on an average about
fifteen boar in two days’ hunting. There are also jackals and
porcupine; and, during a beat near Brij, a panther once took me by
surprise, jumping across the path where I was posted before I could
fire. This animal was shot afterwards on a neighbouring hill.
On one occasion on the promontory of Brij, which is surrounded
by the sea and the river ‘Taherdats’ except for a narrow slip of sand
on the northern side, sometimes flooded at high tides, we found
thirty-six boar in one beat, and killed fourteen. It was an exciting
sight to see the boar breaking from the bush across the neck of sand
about 150 yards broad. The herd did not break together, but came
separately and continuously. A large tusker who led the van was
wounded as he sallied from the bush pursued by dogs, and forthwith
charged the man who had fired; and then beaters, who ran up to the
rescue, were followed again by other boar, who, wounded in their
turn, pursued the beaters that were hurrying after the first boar; then
came dogs, pigs, beaters, more dogs and pigs. Volleys were fired,
up, down, and across the line, regardless of the rules of the hunt.
Great was the excitement; several beaters were knocked down by
the boar, but no one was ripped, though dogs and boar lay wounded
on the sands all around. I shot five boar: one great tusker, being
wounded, sat on his haunches in the defiant posture of the
Florentine boar, so I ran up, assassin-like, from behind and plunged
my knife into his heart.
In one of the beats, a hunter named ‘Shebá,’ a veteran past
seventy, had just shot a boar, when the dogs came in full cry after
another, and he had only time to pour in the powder carried loose in
his leathern pouch, and to put the long iron ramrod down the barrel,
when another tusker came to the front. Shebá fired and sent the
ramrod like a skewer through the body of the boar, who charged and
knocked him over. Shebá fell flat on his face, neither moving arm nor
leg, whilst the boar stood over him, cutting into ribbons his hooded
woollen ‘jelab.’ He shouted for help, exclaiming ‘Fire! fire!’ I ran up
within a few feet. ‘I fear to hit you,’ I said. ‘Fire!’ he cried; ‘I would
rather be shot than be killed by a “halluf” (pig).’
From a Photograph by Baron Whetnall.

The last Hunt in 1886; Sir John on “E’dhem.”


Walker & Boutall Ph. Sc.

I stooped low, and raising the muzzle of my gun, shot the boar
through the heart. The huge carcass fell upon Shebá, who, when
released from the weight, got up and shook me by the hand heartily,
saying, ‘Praise be to God the Merciful! Thanks to you I have escaped
death.’ I withdrew the ramrod, which had passed right through the
body of the animal.
I had not at that time introduced the lance or spear, but when a
boar happened to take to the open I had frequently pursued on
horseback and killed with an ancient rapier I possessed.
Mounted on a little Barb, about fourteen hands three, I once
pursued, gun in hand, a large sow across the plain of Awára. We
came suddenly on a ditch formed by an estuary from the sea, about
sixteen feet broad. No bank was visible until I saw the boar suddenly
disappear, and before I could pull up, my nag tried to clear the ditch,
but failed, as the ground was soft on the brink, so in we plumped
headlong into thick mud and water, gun and all; but a pistol, loose in
my holster, by good fortune was cast high and dry on the opposite
bank.
The horse, sow, and I wallowed for some seconds in the mud
together, each of us scrambling out about the same moment, for I
had chosen an easier ascent of the bank to clamber up than the sow
had done. I left my gun swamped in the mud, and, seizing hold of the
pistol, remounted. Away we went again. It was about a quarter of a
mile to the bush, where the sow would be safe. I came up alongside
and fired, but only wounded her; she turned and made a jump to
seize hold of my leg, but missed, passing her fore leg up to the joint
in my right stirrup, and there her leg and my foot were jammed. The
hind legs of the sow just touched the ground. She tried to bite my
knee; I struggled to release my foot and the sow her leg. I had no
other weapon than the exploded pistol, and my fear was that the
stirrup-leather would give way, and then, if I fell, the sow would have
it all her own way. The pain from my jammed instep was intense, but
after a few seconds the sow freed her leg and then turned on my
horse, who cleverly leapt aside as she charged.
The sow then entered the thicket, badly wounded, and when the
dogs came up we found and killed her. The hunters, who had viewed
the chase from the side of the hill, and had been hallooing joyously
on witnessing the pig, horse, and me tumble into the ditch, were
greatly amused in aiding me to remove the thick coating of grey mud
which shrouded my person, my gun, and the body of my horse.
On another occasion, when a very large boar, slightly wounded,
was making up the side of a rocky hill, bare of bush, a strange Moor,
with a long gun, who had joined the hunt, ran along the open to a
narrow path where the boar would have to pass, and squatted down
to pot him. I was about forty yards off, and shouted as the boar made
towards him, ‘Look out! Stand aside of the path!’—but the stranger
remained steady, fired, and then jumped up and ran.
The infuriated beast pursued and knocked him headlong over,
ripping his legs and body as he struggled to get up. I ran up with
another hunter, but boar and man were so mixed up I could not fire.
The boar, burying its snout under the man’s clothes, ripped his body
severely, then seizing his woollen dress in its mouth like a bull-dog,
knelt on his prostrate body. I dared not fire; so laying hold of the hilt
of a sword my companion carried, and finding the point too blunt to
pierce the ironclad hide, I told the owner to take hold of the point,
and putting the blade under the boar’s throat, we sawed away until
the beast fell dead, still holding the man’s dress in his jaws. The
wounded Moor, who was built like a Samson, fainted away from loss
of blood. We stanched his wounds, making a tourniquet with
handkerchief and stick, laid him on the pad of a mule, and sent him
into town to a room in my stable, where he was attended to by a
surgeon for three weeks and recovered. On taking leave of me, he
observed it was his first and would be his last boar-hunt. This man,
as I learnt afterwards, was a famous cattle-lifter. He told the hunters,
that out of gratitude for my care of him, he would never rob my cows
or the cattle of my friends.
We were wont to hunt for a couple of days every fortnight at Sharf
el Akab and Awára, but finding that the mountaineers from the hills
of Beni M’Suar and Jebel Habíb, who dwell about twelve miles from
this hunting-ground, had been in the habit of coming down in large
parties once a week to hunt and were destroying the game, we
determined, from a spirit of rivalry, to hunt more frequently.
There had been conflicts between my hunters and the
mountaineers, and during a beat for boar, when a number of these
wild fellows had joined our hunt, I heard bullets whizzing and cutting
the branches near to where I stood. One of these mountaineers was
caught by my party, and a vigorous bastinado was inflicted on the
culprit, who had been seen to take a deliberate shot at me.
In less than six months the boar at Sharf el Akab and Awára were
destroyed, except a huge ‘solitaire,’ who had made his lair on the
rocky hill of Bu Amar, then overgrown with impenetrable bush. He
was a very wary animal, who refused to bolt when bayed at by dogs,
frequently killing or wounding those that ventured to approach his
lair.
At that time a Spaniard had brought, much to the annoyance of
the peasants, a herd of tame pigs to feed in the cork-wood, for, as
the peasants reported, the ‘accursed animals’ not only fed on acorns
and white truffles, which abound there, but ravaged also their grain
crops, whither the Spaniard had been seen to drive the herd at night
to feed.
Complaints were made by the farmers to the Moorish authorities
regarding the havoc committed by the pigs, and I backed their
petition to the Basha. So the herdsman was ordered by the Spanish
Legation to remove the herd, which was accordingly done; but two of
the Spaniard’s sows were missing, and he offered a handsome
reward to any Moor who would bring them, dead or alive, declaring
that they had been led astray by a large wild boar, who had been
seen by him to come boldly amongst the herd some weeks before,
had attacked and ripped severely a tame boar, paying no attention to
the herdsman’s shouting, and had led off, as he declared, ‘Dos
cerdas muy hermosas’ (two very beautiful sows), not unwilling, as he
insinuated, to accompany their captor.
The Spaniard declared he had occasionally seen at dusk his two
sows with the boar, feeding in the plains; but as soon as the latter
winded man, he made off at a gallop with his captives.
A hunter reported this to me, mentioning that he had been offered
five dollars for each sow, dead or alive, and that he believed both
sows had large litters of wee striped pigs, evidently the progeny of
their captor.
I communicated with the Spaniard, and these two sows and their
litters were sold to me for about £6. I made known to the Basha of
Tangier how the sport at Sharf el Akab had been spoilt by the too
frequent hunting, both of my party and of the mountaineers; and
related how I had purchased the Spaniard’s two sows and their
litters. I requested that orders should be sent to the mountaineers
who were under the Basha’s jurisdiction to keep to their own hunting-
grounds, and not hunt at Sharf el Akab; and that the peasantry also
of the villages round Tangier should be warned not to shoot boar in
that district unless they joined our hunt, which had always been open
to sportsmen, ‘Moslem or Nazarene,’ of low or high degree.
To all this the Basha agreed, whilst I offered to give compensation
to farmers whose crops might be injured by the ravages of my
porcine acquisition. I also made known to the Foreign
Representatives the steps I had taken, and requested them to give
directions to the subjects of their respective Governments not to
shoot or hunt the hybrids or any other boar in that district, as it was
my intention not to shoot boar in the preserved district, but to hunt
with the spear, after a couple of years, when I expected not only the
hybrids would have increased in numbers, but that they would be
joined by wild boar from the neighbouring hills.
My wishes were granted, and a document was signed to that
effect by the Basha and Foreign Representatives, and in 1868 I
introduced hunting on horseback with the lance—known in India as
pigsticking.
The hybrids at first were not disposed to break from covert and
give a fair gallop in the open; but when the two ‘hermosas cerdas’
were slain, their progeny behaved better, and now give capital runs
across country, and are more disposed to charge than the
thoroughbred boar.
The mode of hunting with the lance is to drive a thicket where pig
are reported to lie, with beaters, dogs, and stoppers, towards the
marsh, plain, or cork-wood, where the pig knows that he can make
for covert in an opposite thicket. The chief beater sounds a horn
when a boar is on foot, firing gun or pistol should he come to bay.
The horsemen are placed down-wind, concealed as much as
possible, with directions to keep silent, and not to start until the boar
is well away in the open, so as to ride in the rear and check his
turning back to the thicket. It is a difficult task to prevent those who
are novices or not sportsmen at heart from breaking through these
rules, especially ardent youths who may view the boar break, and
hope to take the lead by an early start.
The boar, when aware that he is pursued, puts on pace. It
requires a fast horse to come up for the first quarter of a mile; but
when hard pressed, the boar gets blown, shortens stride, and begins
to dodge amongst the low bush.
One of the best gallops I ever had was in pursuit of a huge boar,
who took across the lake from a thicket of Arára. My son, a first-rate
rider, was with me; we did not carry spears, but had revolvers. After
a hard gallop we came up with the boar a few yards before entering
the cork-wood. We fired several shots, but the animal sped on at
racing pace, charging us alternately. The wounds which the boar
received (for blood poured down his flank) were not of a character to
stop his career, so away we dashed through the wood, dodging the
cork-trees, firing occasionally a shot, until the boar ringed back to the
thick jungle of Arára from which he had been driven, and there it was
out of the question to follow on horseback. Disheartened and greatly
disappointed, for the boar was one of the largest we had seen for
many years, we joined the hunters, and dismounted to give our nags
a rest, whilst our party lunched.
We had halted for an hour, and were again preparing to mount,
when a shepherd, all tattered and torn, ran up to me breathless,
saying a ‘halluf,’ black as a ‘Jin’ and as big as a bull, had passed
through the flock of sheep he was tending, knocking several over;
had charged his dog, and made for the sea, where, he said, after
rolling several times, the boar stood erect amidst the waves,
throwing water over his body. ‘This lad is a “kedab” (a liar),’
exclaimed one of the hunters. ‘Who ever heard of a boar bathing in
the sea at midday?’
‘Make haste,’ exclaimed the lad; ‘it is about half an hour’s walk,
and if the boar is not still there, the tracks on the shore will show
whether I lie or not.’
So off the hunters started, guided by the shepherd. As we topped
the sand-hills which line the coast, a black form, such as the
shepherd had described, big as a bull, was viewed amongst the
waves. My son and I recognised the enormous beast that had given
us the gallop, who had evidently taken to the sea to cool his wounds.
As our party approached in line, to check any attempt of the boar to
take back to Arára, he came out of the breakers with bristles up, and
‘Volta feroce al inimico!’ (a word of command formerly used in the
Portuguese army), prepared to receive us.
Some of the hunters were about to fire, which I prevented, saying
I would approach on horseback, as we might have the chance of
another gallop. When I got within twenty yards, the beast charged. I
fired my revolver, missed, gave spurs to my nag, and was pursued
by the boar until the dogs, which had been held back, were let loose;
he then took out to sea, breasting the rollers gallantly, making due
West for the first port in the United States, with the hounds in his
wake.
When the intention of the pig to emigrate became evident and he
was already some hundred yards out to sea, I cried ‘Fire!’ as his
black form topped a wave. Volley after volley followed, and the huge
carcass was washed back on shore. The boar was a hybrid,
perfectly black, with good tusks, and measuring about six feet two
from snout to root of tail, and three feet two from shoulder to hoof. I
have preserved the hide.
The largest boar I have ever seen measured six feet four from
snout to tail, three feet four at the shoulder, and weighed twenty
stone—clean. An old beater of eighty, whose dog had been wounded
to the death, when he came up to the monster lying lifeless, got upon
the body, took off from his shaven pate the red gun-cover which he
used as a turban, and throwing it on the ground, cried out, ‘Now I
can die in peace. The death of this “haisha,” (whale), who has
baulked us for years, is what I have longed for. At last! It was written
he should die before me,’ and the veteran performed a wild wriggling
dance on the carcass of the animal.
This old hunter, named Ben Isa, was still alive, aged a hundred,
when I left Tangier in July, 1886.
During one of our beats, a large boar was started from the low
bush near the beach below Awára, and two mounted Moors joined
me in pursuit. The country was open, and the ground good for
galloping. The pig went away at racing pace, bounding like a deer
over the low bushes. On getting near, I was astonished to see his
ears were cropped like those of a terrier. After a gallop of a mile we
speared him. Hadj Abdallah, who was one of my companions,
exclaimed, ‘Do you remember four years ago two “berakkel”
(squeakers) being caught by the dogs, and you and I carried them in
our arms and let them go near a thicket, where they would be safe;
but the little fellow you carried turned on you, when freed, and tried
to bite your legs, and you bid me catch him and turn him loose again
in the thicket? This I did, but he had shown such pluck I thought I
would mark him, so I cropped his ears and then let him go, saying
“We may meet again.” And here he is, and has given us proof this
day that he was as gallant a boar as he was a squeaker.’
Some years ago we had a good day, killing nine boar.
The camp was pitched at Awára, near the farm huts of the chief
hunter Hadj Hamed. A large party, both of English and foreigners,
went out to join in the sport. On the first two days several boar were
killed, though my favourite horse, ‘Snabi,’ was badly wounded. I
chased a tusker which took right across the burnt wood towards
Awínats and broke into the open on the side of the hill. There I
overtook the beast and transfixed him. He charged before I could
extract the lance, carrying it under my horse, and inflicted a deep
gash between the off fore-leg and chest. I had to dismount and send
the poor suffering beast into town. He was very lame for a
twelvemonth. I had thought of shooting ‘Snabi,’ but he was such a
favourite with my family, that a reprieve was granted. He was the
best nag for pigsticking I ever rode. He was not fast, but thoroughly
understood the sport, and would take his rider, without guiding,
alongside of the pig at the right moment for attack. He never
swerved from a boar; no huntsman knew better where the pig would
be likely to break, as soon as the shouts of the beaters and the horn
were heard, and ‘Snabi’ would be sure to view the animal before his
rider, whenever it broke covert.
When desirous of showing sport to any friend who had never seen
pigsticking I mounted him on ‘Snabi,’ and my advice was to let the
horse take his own direction after the pig, and have his own way
when closing with the enemy. If his rider fell, or a hole brought
‘Snabi’ on his head, the nag would get up and stand by, putting his
head down, and looking with anxious eyes, as if to say, ‘Get up
quickly, the pig is making off.’—‘Snabi’ had belonged to Kaid Meno,
the Colonel of the Berber regiment of Askar, and had often been in
action when his master was sent by the Sultan in command of a
detachment to ‘eat up’ some rebellious tribe. There were several
scars on ‘Snabi’s’ dun coat—which, in the sun, shone like gold. One
ball could be distinctly felt in his neck.
On the evening of the second day we hunted the Haffa, a wood
on the south side of the camp. The lances were placed along the
side of the Awínats woods, and numbers of boar were found. But,
pig-headed, they refused to cross the plain, and took away out of
sight over the rough and open slope of the hill leading towards the
sea; had we foreseen which, we should have had long and hard
runs.
One enormous fellow, the monster of the forest—described by
Hadj Hamed as being as big as my grey horse!—of a glistening grey
colour, and with tusks sticking out, as he said, like the horns of a
young bull, carried away in pursuit beaters and dogs towards the
lake. From the moment this beast was found, he charged dog or
man that he happened to sight. He took his time, leisurely moving off
at a slow trot, followed at a respectful distance by the beaters, still
charging any one who ventured to approach him. A messenger was
dispatched for us by Hadj Hamed and we started off in pursuit, but
arrived too late, the monster had entered the thicket.
Hadj Alarbi, the head beater, told me that he did not sleep a wink
that night from disappointment that the monster boar had escaped;
but he added, ‘I never should have allowed you to pursue the giant,
for he would have knocked over both horse and rider from sheer
weight when he charged. I should have asked some of those
“Nazarenes” (indicating the foreigners) to go to the front.’
On the third day it was decided to give a rest to dogs and horses.
Many of the party, therefore, went out snipe-shooting; but about 2
p.m., a boar having been viewed by the Italian Minister near the
camp, Hadj Hamed proposed that we should have a beat of the
Haffa wood. I had hardly placed the lances along the rough hill-side
between the camp and the sea-shore, when a large boar was viewed
making towards the Shebenía. Away we rattled. C. W. led on his fast
horse, and, riding pluckily, got both first spear and a second spear on
a charge. J. M. got third, and the boar then took to a thick clump of
juniper. We left him there and returned to our posts in time to chase
and kill another boar.
Having selected half a dozen beaters with their dogs, we returned
to the clump of juniper and myrtle where the wounded boar had
retreated. This thicket, standing not far from the sea-shore, covered
a space of about two hundred yards square, with open ground on
every side. The dogs bayed at the boar, and the riders stood around
the thicket down-wind—awaiting his exit, in the hope that, when
rested, he would move; but three-quarters of an hour, big with
expectation, passed, and though the boar frequently charged the
dogs to the brink of the thicket, and occasional howls told us that
mischief was done, he never broke, but after each charge went back
to the densest part of the copse. I directed the beaters to halloo with
all their might and sound the horn, but in vain.
As it was getting late I dismounted, and spear in hand went into
the bush; but finding that with ten feet of bamboo in my hand I
should be at the mercy of the boar if he charged, I retreated.
In the open towards the sea I found two Moors, with guns, who
had come up from camp, standing near a boar-path in the hope of
getting a shot; for when a wounded boar takes to covert where
horses cannot penetrate, the regulation against using fire-arms is in
abeyance.
Sunset was drawing nigh, and, fearing that the wounded animal
might die in the thicket before next day, I told the hunters to creep in
and shoot the boar. The Moor who had a long native gun declined,
saying he could not venture; for, if the boar charged in the bush,
through which he would have to creep on hands and knees, the
animal would probably be on him before he could fire. But he
volunteered to crawl along the top of the bushes, if stiff enough to
support him (he was a little wiry fellow), and thus perhaps he might
get a shot. The other young Moor had a smart-looking double-
barrelled gun, a muzzle-loader, so I challenged him to enter. He
replied he was not going to risk his life with such a savage brute still
strong in limb. ‘Hark!’ he cried, as a rush, followed by a piteous howl
from a hound, was heard. ‘You are a coward,’ I retorted angrily, ‘to
remain passive whilst our dogs are being killed.’ ‘You say that I am a
coward,’ he replied, handing me the gun; ‘then show that you are
not!’
I hesitated, for though I had shot many wounded boar at bay or on
the charge, it had always been with my own trusty gun; but feeling I
had wronged the Moor by taunting him with cowardice, and that he
would have the best of it if I did not take up the glove, I inquired how
his gun was loaded. He replied, ‘with ball.’ The copper caps looked
bright and appeared to have been lately put on, so, kneeling down
and keeping the gun before me at full-cock, I crawled in. The bush
was too thick to stand up, for if I had squeezed myself into an upright
position, my legs would have been at the mercy of the pig if he
charged, which I knew the beast would, if he got a whiff of me or
viewed my legs. Moreover I could not have lowered my gun
suddenly in the thick bush to take aim.
On I crawled for about twenty-five yards, peering anxiously
through the bush. A dog which had been charged came close, and
saluted me with his tail and a whimper of satisfaction; then went
back to his companions, and no doubt informed them, in dog
language, that a man had come to the rescue, for they set up
forthwith a chorus of tongue, which again induced the boar to move
and engrossed his attention; so, crawling on, I got within ten yards
and viewed him, ‘cassant les noisettes,’ as French sportsmen say.
Blood streamed down his side and his bristles stood on an end.
I squatted, took deliberate aim behind the right shoulder and
pulled the trigger, expecting to see the beast roll over; but a fizz, a
faint report, and the sound of a bullet falling amongst the bushes,
sounded like my death-knell; for I knew that the boar would in a few
seconds be on me. With faint hope, however, that the second barrel
would not also contain a damp charge, I held my gun firm. On came
the huge beast, and when within three yards with his head towards
me, I aimed at his left shoulder; the explosion was faint, but the
beast dropped on his head, then rose, charging on to the muzzle of
my gun, which I continued to hold steadily in front, sent it flying over
my head, whilst I toppled backwards, and with the force of the blow
my legs were thrown straight up into the air, and in that position I had
sufficient presence of mind to remain, and could see through my legs
the grim monster’s head and tusks.
That moment appeared a lifetime, a thousand thoughts of past life
flashed through my brain, but the chief one was—My epitaph—‘A
fool killed by a pig.’ My last shot had broken his leg at the shoulder,
so that the movements of the boar were less active; but on he came,
whilst I kept my legs aloft. It is better, I thought, to have my nether
limbs ripped than more vital regions. So when his grizzly snout was
on me, I brought down with force my right leg, armed with a heavy
shooting boot, like a Nasmyth hammer on his skull, which sent the
boar, who had only one sound fore-leg, on his knees; this was
followed up by the left leg, and I pummelled his head alternately with
each foot as the boar tried to get in at me. The right leg I managed to
raise rapidly, so that it was not cut; but with the left I was less
successful, and it was ripped in three places, as I found afterwards,
for at the time I felt no pain. ‘If no one comes to the rescue,’ I cried
out, ‘I shall be killed by the “halluf.”’ I had hardly spoken, when
suddenly there appeared standing on my left the brave beater,
Ahmed Ben Ali, with his hatchet raised in the air about to strike the
boar, saying, ‘La bas,’ equivalent to ‘all right.’
The boar left me and went at him; the lithe fellow struck the beast
with his hatchet whilst he jumped aside. A shot within a few yards
followed. It was from the hunter who had kept his promise, having
crawled in a wonderful manner along the tops of the bushes close to
where we were, and putting his long gun down on the beast, killed it.
I lay prostrate, my legs and breast bespattered with blood from
the boar’s wounds and my own. Ahmed suddenly laid hold of me
and began to take off my nether garments. Angered at what
appeared to me an inexplicable liberty, I used some strong
expressions, not the blessings he deserved for saving my life. Upon
which Ahmed said, ‘No time is to be lost: you have blood in front of
your clothes, and if the bowels are injured, the wound must be sewn
up before the air penetrates. I have needle and silk ready’ (carried by
hunters to sew the wounds of dogs). I apologised for my rough
language, and thanked the brave fellow for saving my life; then
readjusting my unmentionables, I said, ‘The boar has not wounded
my body, only my legs, I think,’ for I still felt no pain, but the blood
was trickling down, and I could feel my left boot was full of it.
Taking a handkerchief and a stick, I made a sort of tourniquet
above the knee, and then Ahmed dragged me out of the thicket. I felt
faint, night was approaching, there were fifteen miles to ride to
Tangier; but I decided it would be better to return to town than to go
to camp and next day find my wounds so stiff that I should not be
able to ride. I requested Ahmed to go to camp and send me a flask
of brandy by my groom, and tell the latter he was to accompany me
to town. I told the hunters, who assembled round me with anxious
faces, that I was not seriously hurt, but unfit for riding, and begged
them to remain for next day’s hunt, declining the offer of many
friends to accompany me to town.
It was a long, weary journey of fifteen miles. My horse stumbled
now and then over rocks and mud, for it became pitch dark after the
first hour, and I had constant proof of the malignity of matter, for
every branch or twig we passed seemed to take pleasure in
knocking against my wounds, causing me much pain, and yet I felt
joyous, and thankful to God I had not fared worse.
On arrival at the foot of the stairs of the Legation I gave a cheery
‘view halloo,’ so that my family might know I had arrived in good
spirits. I was carried upstairs and a surgeon was sent for, who sewed
up the wounds. The worst of them was a stab from a tusk, making a
deep hole without ripping the flesh, as in the other cuts. For three
weeks I lay on my back, though, as the surgeon observed, my flesh
was like that of a healthy child, the wound having closed without
inflammation.
When the hunters returned from the camp, I sent for brave Ahmed
Ben Ali who had saved my life, and gave him a gun and a sword.
During the number of years I have hunted in Morocco, I have
killed with gun or spear upwards of five hundred boar, and only once
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like