clear everything

This commit is contained in:
Moez Bhatti
2017-12-27 01:10:56 -05:00
parent fc6eacc142
commit e9b01b2fae
760 changed files with 0 additions and 121352 deletions
Vendored
BIN
View File
Binary file not shown.
-8
View File
@@ -1,8 +0,0 @@
<!--
Please search the existing issues before creating a new one
https://github.com/moezbhatti/qksms/issues?q=is%3Aissue
If you are going to create an issue, please provide:
- A brief description of your issue
- Steps to reproduce the issue
-->
-28
View File
@@ -1,28 +0,0 @@
# Built application files
build/
# Crashlytics configuations
com_crashlytics_export_strings.xml
# Local configuration file (sdk path, etc)
local.properties
# Gradle generated files
.gradle/
build/
# Signing files
.signing/
# User-specific configurations
.idea/
*.iml
# OS-specific files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
-30
View File
@@ -1,30 +0,0 @@
language: android
sudo: required
android:
components:
# Uncomment the lines below if you want to
# use the latest revision of Android SDK Tools
- platform-tools
- tools
# The BuildTools version used by your project
- build-tools-23.0.2
# The SDK version used to compile your project
- android-22
# Additional components
- extra-google-google_play_services
- extra-google-m2repository
- extra-android-m2repository
jdk:
- oraclejdk8
before_install:
- export JAVA8_HOME=$JAVA_HOME
script:
- ./gradlew clean
- ./gradlew build
-674
View File
@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
-116
View File
@@ -1,116 +0,0 @@
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'io.fabric'
repositories {
mavenCentral()
jcenter()
maven { url 'https://maven.fabric.io/public' }
maven { url 'https://clojars.org/repo/' }
}
android {
flavorDimensions "analytics"
productFlavors {
withAnalytics {
dimension "analytics"
}
noAnalytics {
dimension "analytics"
}
}
lintOptions {
checkReleaseBuilds false
abortOnError false
disable 'InvalidPackage'
}
compileSdkVersion 22
buildToolsVersion '25.0.0'
defaultConfig {
versionCode 135
versionName "2.7.3"
minSdkVersion 15
targetSdkVersion 22
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'qksms-proguard.pro'
}
debug {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'qksms-proguard.pro'
}
}
compileOptions {
// Use Java 1.7, requires minSdk 8
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lintOptions {
checkReleaseBuilds false
abortOnError false
// Translations are crowd-sourced
disable 'MissingTranslation'
}
}
buildscript {
repositories {
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'me.tatarka:gradle-retrolambda:3.2.2'
classpath 'io.fabric.tools:gradle:1.21.5'
}
}
String leakCanaryVersion = '1.4-beta2'
dependencies {
// Open source libraries
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.melnykov:floatingactionbutton:1.3.0'
compile 'com.pushbullet:android-extensions:1.0.4'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.klinkerapps:android-chips:1.0.0'
compile 'com.googlecode.libphonenumber:libphonenumber:6.2'
compile 'com.nispok:snackbar:2.10.6'
compile 'com.github.lzyzsd:circleprogress:1.1.0'
debugCompile "com.squareup.leakcanary:leakcanary-android-no-op:$leakCanaryVersion"
releaseCompile "com.squareup.leakcanary:leakcanary-android-no-op:$leakCanaryVersion"
compile 'com.vdurmont:emoji-java:3.1.3'
compile 'me.leolin:ShortcutBadger:1.1.1'
compile 'com.googlecode.ez-vcard:ez-vcard:0.9.6'
compile 'com.google.code.gson:gson:2.4'
compile 'com.koushikdutta.ion:ion:1.1.7'
compile 'org.ligi:snackengage:0.4'
compile 'frankiesardo:icepick:3.2.0'
provided 'frankiesardo:icepick-processor:3.2.0'
// Google libraries
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:support-v13:22.2.1'
compile 'com.android.support:recyclerview-v7:22.2.1'
withAnalyticsCompile 'com.google.android.gms:play-services-analytics:8.3.0'
// External services
withAnalyticsCompile('com.crashlytics.sdk.android:crashlytics:2.5.5@aar') {
transitive = true;
}
}
-99
View File
@@ -1,99 +0,0 @@
-dontobfuscate
#
# To fix an error to do with android.location.Country. We may be able to optimize
# more parts of the android.location package.
#
-keep class android.location.** { *; }
#
# See com.moez.QKSMS.ui.mms.PresenterFactory---it uses reflect
#
-keep class com.moez.QKSMS.ui.mms.MmsThumbnailPresenter { *; }
-keep class com.moez.QKSMS.ui.mms.SlideshowPresenter { *; }
-keep class com.android.internal.util.ArrayUtils { *; }
#
# Klinker's MMS code uses reflection on android.net.ConnectivityManager (and subclasses).
#
-keep class android.net.** { *; }
#
# SlidingMenu
#
-keep class android.view.Display { *; }
#
# SystemBarTint
#
-keep class android.os.SystemProperties { *; }
#
# libphonenumber
#
-keep class com.google.i18n.phonenumbers.** { *; }
#
# Android Volley
# see: http://stackoverflow.com/questions/21816643/volley-seems-not-working-after-proguard-obfuscate
#
-keep class org.apache.commons.logging.** { *; }
#
# Google Play Services proguard
# see: http://developer.android.com/google/play-services/setup.html#Proguard
#
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents();
}
-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
public static final *** NULL;
}
-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
@com.google.android.gms.common.annotation.KeepName *;
}
-keepnames class * implements android.os.Parcelable {
public static final ** CREATOR;
}
#
# Crittercism
# see: http://docs.crittercism.com/android/android.html
#
-keep public class com.crittercism.**
-keepclassmembers public class com.crittercism.* {
*;
}
# To get line numbers, source files from Crittercism:
-keepattributes SourceFile, LineNumberTable
# ez-vcard
# https://github.com/nickel-chrome/CucumberSync/blob/master/proguard-project.txt
-dontwarn com.fasterxml.jackson.** # Jackson JSON Processor (for jCards) not used
-dontwarn freemarker.** # freemarker templating library (for creating hCards) not used
-dontwarn org.jsoup.** # jsoup library (for hCard parsing) not used
-dontwarn sun.misc.Perf
-keep class ezvcard.property.** { *; } # keep all VCard properties (created at runtime)
# ButterKnife
# http://jakewharton.github.io/butterknife/
-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewBinder { *; }
-keepclasseswithmembernames class * {
@butterknife.* <fields>;
}
-keepclasseswithmembernames class * {
@butterknife.* <methods>;
}
# RetroLambda
# https://github.com/evant/gradle-retrolambda
-dontwarn java.lang.invoke.*
@@ -1,70 +0,0 @@
package com.moez.QKSMS.common.emoji;
import com.vdurmont.emoji.EmojiParser;
import junit.framework.TestCase;
public class EmojiRegistryTest extends TestCase {
public void testWhitespaceBothSides() {
String src = " :) ";
String expected = EmojiParser.parseToUnicode(" :" + Emojis.SMILEY + ": ");
assertEquals(EmojiParser.parseToUnicode(expected), EmojiRegistry.parseEmojis(src));
}
public void testJustEmoji() {
String src = ":)";
String expected = EmojiParser.parseToUnicode(":" + Emojis.SMILEY + ":");
assertEquals(EmojiParser.parseToUnicode(expected), EmojiRegistry.parseEmojis(src));
}
public void testPunctuationNothing() {
String src = ".:)";
String expected = EmojiParser.parseToUnicode(".:" + Emojis.SMILEY + ":");
assertEquals(EmojiParser.parseToUnicode(expected), EmojiRegistry.parseEmojis(src));
}
public void testNothingPunctuation() {
String src = ":)!";
String expected = EmojiParser.parseToUnicode(":" + Emojis.SMILEY + ":!");
assertEquals(EmojiParser.parseToUnicode(expected), EmojiRegistry.parseEmojis(src));
}
public void testPunctuationPunctuation() {
String src = ".:)!!!";
String expected = EmojiParser.parseToUnicode(".:" + Emojis.SMILEY + ":!!!");
assertEquals(EmojiParser.parseToUnicode(expected), EmojiRegistry.parseEmojis(src));
}
public void testUrlsWork() {
String src = "http://github.com/srcreigh";
assertEquals(src, EmojiRegistry.parseEmojis(src));
}
public void testMultipleEmojisOnlyReplaceFirst() {
String src = ":):):)";
String expected = EmojiParser.parseToUnicode(":" + Emojis.SMILEY + "::):)");
assertEquals(EmojiParser.parseToUnicode(expected), EmojiRegistry.parseEmojis(src));
}
public void testEmojiWithWordDoesntReplace() {
String src = "hey:)";
assertEquals(src, EmojiRegistry.parseEmojis(src));
}
public void testPoop() {
String src = ":poop:";
assertEquals(EmojiParser.parseToUnicode(src), EmojiRegistry.parseEmojis(src));
}
public void testNewlineAfter() {
String src = ":)\n";
String expected = EmojiParser.parseToUnicode(":" + Emojis.SMILEY + ":\n");
assertEquals(EmojiParser.parseToUnicode(expected), EmojiRegistry.parseEmojis(src));
}
public void testNewlineNewline() {
String src = "\n:)\n";
String expected = EmojiParser.parseToUnicode("\n:" + Emojis.SMILEY + ":\n");
assertEquals(EmojiParser.parseToUnicode(expected), EmojiRegistry.parseEmojis(src));
}
}
@@ -1,19 +0,0 @@
package com.moez.QKSMS.common.utils;
import android.test.AndroidTestCase;
import java.text.SimpleDateFormat;
public class DateFormatterTest extends AndroidTestCase {
protected void setUp() throws Exception {
super.setUp();
}
public void testDateSymbolsAPI(){
assertEquals(new SimpleDateFormat("H:mm a").toPattern(), "H:mm a");
}
protected void tearDown() throws Exception {
super.tearDown();
}
}
@@ -1,237 +0,0 @@
/*
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qklabs.qkms.test;
import android.content.Context;
import android.test.InstrumentationTestCase;
import com.moez.QKSMS.mmssms.Apn;
import com.moez.QKSMS.mmssms.ApnUtils;
import java.util.Arrays;
import java.util.List;
public class ApnTest extends InstrumentationTestCase {
Context context;
public void setUp() {
context = getInstrumentation().getContext();
}
public void testQueryPortInsteadOfMmsPort() {
List<Apn> actual = ApnUtils.query(context, "310", "012");
List<Apn> expected = Arrays.asList(
new Apn("Verizon", "http://mms.vtext.com/servlets/mms", null, "80")
);
assertEquals(expected, actual);
}
public void testQueryMultipleMatching() {
List<Apn> actual = ApnUtils.query(context, "310", "240");
List<Apn> expected = Arrays.asList(
new Apn("T-Mobile US 240", "http://mms.msg.eng.t-mobile.com/mms/wapenc", null, null),
new Apn("MetroPCS 240", "http://metropcs.mmsmvno.com/mms/wapenc", null, null)
);
assertEquals(expected, actual);
}
public void testQueryLeadingZero() {
List<Apn> actual = ApnUtils.query(context, "724", "019");
List<Apn> expected = Arrays.asList(
new Apn("Vivo MMS", "http://termnat.vivomms.com.br:8088/mms", "200.142.130.104", "80")
);
assertEquals(expected, actual);
}
public void testQueryNonLeadingZeroDoesntMatchLeadingZero() {
List<Apn> actual = ApnUtils.query(context, "724", "19");
List<Apn> expected = Arrays.asList(
new Apn("Vivo MMS", "http://termnat.vivomms.com.br:8088/mms", "200.142.130.104", "80")
);
assertEquals(expected, actual);
}
public void testQueryBoostMobile() {
List<Apn> actual = ApnUtils.query(context, "311", "870");
List<Apn> expected = Arrays.asList(
new Apn("Boost Mobile", "http://mm.myboostmobile.com", "68.28.31.7", "80")
);
assertEquals(expected, actual);
}
public void test311480Verizon() {
List<Apn> actual = ApnUtils.query(context, "311", "480");
List<Apn> expected = Arrays.asList(
new Apn("Verizon", "http://mms.vtext.com/servlets/mms", null, null)
);
assertEquals(expected, actual);
}
public void test310260TMobile() {
List<Apn> actual = ApnUtils.query(context, "310", "260");
Apn expected = new Apn("T-Mobile", "http://mms.msg.eng.t-mobile.com/mms/wapenc", null, null);
assertTrue(actual.contains(expected));
}
public void test310120Sprint() {
List<Apn> actual = ApnUtils.query(context, "310", "120");
List<Apn> expected = Arrays.asList(
new Apn("Sprint", "http://mms.sprintpcs.com", "68.28.31.7", "80")
);
assertEquals(expected, actual);
}
public void test26806TMN() {
List<Apn> actual = ApnUtils.query(context, "268", "06");
List<Apn> expected = Arrays.asList(
new Apn("TMN", "http://mmsc/", "10.111.2.16", "8080")
);
assertEquals(expected, actual);
}
public void test311490VirginMobile() {
List<Apn> actual = ApnUtils.query(context, "311", "490");
Apn expected = new Apn("Virgin Mobile", "http://mmsc.vmobl.com:8088/mms?", "205.239.233.136", "81");
assertTrue(actual.contains(expected));
}
public void test23410O2() {
List<Apn> actual = ApnUtils.query(context, "234", "10");
List<Apn> expected = Arrays.asList(
new Apn("O2", "http://mmsc.mms.o2.co.uk:8002", "82.132.254.1", "8080"),
new Apn("TESCO", "http://mmsc.mms.o2.co.uk:8002", "193.113.200.195", "8080")
);
assertEquals(expected, actual);
}
public void testSolaveiBlank() {
List<Apn> actual = ApnUtils.query(context, "310", "260");
Apn expected = new Apn("Solavei", "http://solavei.mmsmvno.com/mms/wapenc", null, null);
assertTrue(actual.contains(expected));
}
public void testNet10() {
List<Apn> actual = ApnUtils.query(context, "310", "410");
Apn expected = new Apn("net10", "http://mms.tracfone.com", null, null);
assertTrue(actual.contains(expected));
}
public void testATTApnSettings() {
List<Apn> actual = ApnUtils.query(context, "310", "410");
Apn expected1 = new Apn("AT&T 4G", "http://mmsc.mobile.att.net", "proxy.mobile.att.net", "80");
Apn expected2 = new Apn("AT&T 3G/WAP", "http://mmsc.cingular.com/", "wireless.cingular.com", "80");
assertTrue(actual.contains(expected1));
assertTrue(actual.contains(expected2));
}
public void testGrameenPhone() {
List<Apn> actual = ApnUtils.query(context, "470", "01");
Apn expected = new Apn("Grameenphone", "http://mmsc.grameenphone.com/servlets/mms", null, null);
assertTrue(actual.contains(expected));
}
public void testAirtel() {
List<Apn> actual = ApnUtils.query(context, "470", "07");
Apn expected = new Apn("Airtel", "http://100.1.201.171:10021/mmsc", "100.1.201.172", "8799");
assertTrue(actual.contains(expected));
}
public void testSMARTFREN() {
List<Apn> actual = ApnUtils.query(context, "510", "09");
Apn expected1 = new Apn("SMARTFREN 0881, 0882", "http://mmsc-jkt.smart-telecom.co.id", "10.17.27.250", "8080");
Apn expected2 = new Apn("SMARTFREN 0887, 0888, 0889", "http://mmsc2.smartfren.com", "10.17.27.250", "8080");
assertTrue(actual.contains(expected1));
assertTrue(actual.contains(expected2));
}
public void testStraightTalk() {
List<Apn> actual = ApnUtils.query(context, "310", "410");
Apn expected = new Apn("Straight Talk", "http://mms-tf.net", "mms3.tracfone.com", "80");
assertTrue(actual.contains(expected));
}
public void testCricket310410() {
List<Apn> actual = ApnUtils.query(context, "310", "410");
Apn expected = new Apn("Cricket", "http://mmsc.aiowireless.net", "proxy.aiowireless.net", "80");
assertTrue(actual.contains(expected));
}
public void testCricket310150() {
List<Apn> actual = ApnUtils.query(context, "310", "150");
Apn expected = new Apn("Cricket", "http://mmsc.aiowireless.net", "proxy.aiowireless.net", "80");
assertTrue(actual.contains(expected));
}
public void testTIGO() {
List<Apn> actual = ApnUtils.query(context, "640", "02");
Apn expected = new Apn("TIGO", "http://mms", "10.16.17.12", "8888");
assertTrue(actual.contains(expected));
}
public void testDSTCom() {
List<Apn> actual = ApnUtils.query(context, "528", "11");
Apn expected = new Apn("DSTCom", "http://mms.dst.com.bn/mmsc", "10.100.6.101", "3130");
assertTrue(actual.contains(expected));
}
public void testVodacomMozambique() {
List<Apn> actual = ApnUtils.query(context, "643", "04");
Apn expected = new Apn("Vodacom", "http://mms.vm.co.mz", "10.201.47.14", "9201");
assertTrue(actual.contains(expected));
}
public void testVirginMobileMms() {
List<Apn> actual = ApnUtils.query(context, "310", "000");
Apn expected = new Apn("Virgin Mobile", "http://mmsc.vmobl.com:8088/mms?", "205.239.233.136", "81");
assertTrue(actual.contains(expected));
}
public void testH2O() {
List<Apn> actual = ApnUtils.query(context, "310", "410");
Apn expected = new Apn("H2O", "http://mmsc.cingular.com", "66.209.11.33", "80");
assertTrue(actual.contains(expected));
}
public void testSpeakOut() {
List<Apn> actual = ApnUtils.query(context, "302", "720");
Apn expected = new Apn("SpeakOut", "http://mms.gprs.rogers.com", "mmsproxy.rogers.com", "80");
assertTrue(actual.contains(expected));
}
public void testApnEquals() {
assertEquals(new Apn(null, null, null, null), new Apn(null, null, null, null));
assertEquals(new Apn("Test", null, null, null), new Apn("Test", null, null, null));
assertEquals(new Apn("A", "B", null, null), new Apn("A", "B", null, null));
assertEquals(new Apn("A", "B", "C", null), new Apn("A", "B", "C", null));
assertEquals(new Apn("A", "B", "C", "D"), new Apn("A", "B", "C", "D"));
assertEquals(new Apn("", "B", "", "D"), new Apn("", "B", "", "D"));
}
public void testApnEmptyConstructor() {
assertEquals(new Apn(), new Apn(null, null, null, null));
}
public void testApnManuallyConstructed() {
Apn manual;
manual = new Apn();
manual.name = "A"; manual.mmsc = "B"; manual.proxy = "C"; manual.port = "D";
assertEquals(new Apn("A", "B", "C", "D"), manual);
manual = new Apn();
manual.name = "A"; manual.proxy = "C";
assertEquals(new Apn("A", null, "C", null), manual);
}
}
-577
View File
@@ -1,577 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.moez.QKSMS">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RECEIVE_MMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="com.android.vending.BILLING" />
<application
android:name=".QKSMSApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:theme="@style/AppThemeDark">
<activity
android:name=".ui.popup.QKComposeActivity"
android:excludeFromRecents="true"
android:taskAffinity=""
android:theme="@style/AppThemeLightDialog"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
<activity
android:name=".ui.MainActivity"
android:enabled="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:logo="@color/transparent"
android:screenOrientation="user"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SENDTO" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.MULTIWINDOW_LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
<data android:scheme="sms_body" />
</intent-filter>
</activity>
<activity
android:name=".ui.messagelist.MessageListActivity"
android:launchMode="singleTop"
android:screenOrientation="user"
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".ui.settings.SettingsActivity"
android:screenOrientation="user"
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".ui.search.SearchActivity"
android:screenOrientation="user"
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".ui.compose.ComposeActivity"
android:screenOrientation="user"
android:windowSoftInputMode="adjustResize" />
<activity-alias
android:name=".ui.MainActivity-Default"
android:enabled="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Dark"
android:enabled="false"
android:icon="@mipmap/ic_launcher_dark"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Teal"
android:enabled="false"
android:icon="@mipmap/ic_launcher_teal"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Red"
android:enabled="false"
android:icon="@mipmap/ic_launcher_red"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Pink"
android:enabled="false"
android:icon="@mipmap/ic_launcher_pink"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Purple"
android:enabled="false"
android:icon="@mipmap/ic_launcher_purple"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-DeepPurple"
android:enabled="false"
android:icon="@mipmap/ic_launcher_deep_purple"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Indigo"
android:enabled="false"
android:icon="@mipmap/ic_launcher_indigo"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Blue"
android:enabled="false"
android:icon="@mipmap/ic_launcher_blue"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-LightBlue"
android:enabled="false"
android:icon="@mipmap/ic_launcher_light_blue"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Cyan"
android:enabled="false"
android:icon="@mipmap/ic_launcher_cyan"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Green"
android:enabled="false"
android:icon="@mipmap/ic_launcher_green"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-LightGreen"
android:enabled="false"
android:icon="@mipmap/ic_launcher_light_green"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Lime"
android:enabled="false"
android:icon="@mipmap/ic_launcher_lime"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Yellow"
android:enabled="false"
android:icon="@mipmap/ic_launcher_yellow"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Amber"
android:enabled="false"
android:icon="@mipmap/ic_launcher_amber"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Orange"
android:enabled="false"
android:icon="@mipmap/ic_launcher_orange"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-DeepOrange"
android:enabled="false"
android:icon="@mipmap/ic_launcher_deep_orange"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Brown"
android:enabled="false"
android:icon="@mipmap/ic_launcher_brown"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-Grey"
android:enabled="false"
android:icon="@mipmap/ic_launcher_grey"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".ui.MainActivity-BlueGrey"
android:enabled="false"
android:icon="@mipmap/ic_launcher_blue_grey"
android:label="@string/app_name"
android:targetActivity=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity
android:name=".ui.welcome.WelcomeActivity"
android:screenOrientation="portrait"
android:theme="@style/AppThemeLight" />
<!-- Popup activity -->
<activity
android:name=".ui.popup.QKReplyActivity"
android:excludeFromRecents="true"
android:screenOrientation="user"
android:taskAffinity=""
android:theme="@style/AppThemeLightDialog"
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".ui.mms.SlideshowActivity"
android:screenOrientation="user" />
<receiver
android:name=".receiver.RemoteMessagingReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.moez.QKSMS.receiver.WearableIntentReceiver.REPLY" />
</intent-filter>
</receiver>
<!-- Broadcast receiver for SMS -->
<receiver
android:name=".receiver.SmsReceiver"
android:enabled="@bool/hasKitKat"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_DELIVER" />
</intent-filter>
</receiver>
<receiver
android:name=".receiver.IconColorReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_CHANGED" />
<data android:scheme="package" />
</intent-filter>
<intent-filter>
<action android:name="com.moez.QKSMS.action.PENDING_PACKAGE_CHANGE" />
</intent-filter>
</receiver>
<!-- Legacy broadcast receiver for SMS -->
<receiver
android:name=".receiver.SmsReceiverLegacy"
android:enabled="@bool/preKitKat"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter android:priority="2147483647">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<!-- Broadcast receiver for MMS -->
<receiver
android:name=".receiver.PushReceiver"
android:permission="android.permission.BROADCAST_WAP_PUSH">
<intent-filter>
<action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />
<action android:name="android.provider.Telephony.WAP_PUSH_DELIVER" />
<data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>
</receiver>
<receiver android:name=".receiver.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver
android:name=".mmssms.SentReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.moez.QKSMS.SMS_SENT" />
</intent-filter>
</receiver>
<receiver
android:name=".receiver.DeliveredReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.moez.QKSMS.SMS_DELIVERED" />
</intent-filter>
</receiver>
<receiver
android:name=".receiver.MessageFailedReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.moez.QKSMS.NOTIFY_SMS_FAILURE" />
</intent-filter>
</receiver>
<receiver
android:name=".receiver.MarkReadReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.moez.QKSMS.MARK_READ" />
</intent-filter>
</receiver>
<receiver
android:name=".receiver.MarkSeenReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.moez.QKSMS.MARK_SEEN" />
</intent-filter>
</receiver>
<receiver android:name=".ui.widget.WidgetProvider">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<intent-filter>
<action android:name="com.moez.QKSMS.intent.action.ACTION_NOTIFY_DATASET_CHANGED" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_info" />
</receiver>
<receiver android:name=".receiver.NightModeAutoReceiver" />
<receiver
android:name="com.mariussoft.endlessjabber.sdk.EndlessJabberReceiver"
android:enabled="true">
<intent-filter>
<action android:name="com.mariussoft.endlessjabber.action.extend" />
</intent-filter>
</receiver>
<receiver android:name=".receiver.AirplaneModeReceiver">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE" />
</intent-filter>
</receiver>
<service android:name="com.mariussoft.endlessjabber.sdk.EndlessJabberWakefulService" />
<service android:name=".service.DeleteOldMessagesService" />
<service
android:name=".receiver.UnreadBadgeService"
android:exported="false" />
<service android:name=".service.ShouldIAnswerService">
<intent-filter>
<action android:name="com.moez.QKSMS.ShouldIAnswerService" />
</intent-filter>
</service>
<!-- Service that delivers messages from the phone "quick response" -->
<service
android:name=".service.HeadlessSmsSendService"
android:exported="true"
android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE">
<intent-filter>
<action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
</intent-filter>
</service>
<service
android:name=".service.PushbulletService"
android:permission="com.pushbullet.android.permission.READ_MESSAGING_EXTENSION_DATA">
<intent-filter>
<action android:name="com.pushbullet.android.extension.MessagingExtension" />
</intent-filter>
<meta-data
android:name="protocolVersion"
android:value="1" />
</service>
<service android:name="com.android.mms.transaction.TransactionService" />
<service android:name=".service.NotificationService" />
<service android:name=".service.MarkReadService" />
<service android:name=".service.MarkSeenService" />
<service android:name=".service.DeleteUnreadMessageService" />
<service android:name=".service.CopyUnreadMessageTextService" />
<service
android:name=".ui.widget.WidgetService"
android:permission="android.permission.BIND_REMOTEVIEWS" />
<meta-data
android:name="io.fabric.ApiKey"
android:value="0" />
<uses-library
android:name="com.sec.android.app.multiwindow"
android:required="false" />
<meta-data
android:name="com.sec.android.support.multiwindow"
android:value="true" />
<meta-data
android:name="com.sec.android.multiwindow.DEFAULT_SIZE_W"
android:value="632dp" />
<meta-data
android:name="com.sec.android.multiwindow.DEFAULT_SIZE_H"
android:value="598dp" />
<meta-data
android:name="com.sec.android.multiwindow.MINIMUM_SIZE_W"
android:value="632dp" />
<meta-data
android:name="com.sec.android.multiwindow.MINIMUM_SIZE_H"
android:value="598dp" />
</application>
</manifest>
@@ -1,144 +0,0 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.vending.billing;
import android.os.Bundle;
/**
* InAppBillingService is the service that provides in-app billing version 3 and beyond.
* This service provides the following features:
* 1. Provides a new API to get details of in-app items published for the app including
* price, type, title and description.
* 2. The purchase flow is synchronous and purchase information is available immediately
* after it completes.
* 3. Purchase information of in-app purchases is maintained within the Google Play system
* till the purchase is consumed.
* 4. An API to consume a purchase of an inapp item. All purchases of one-time
* in-app items are consumable and thereafter can be purchased again.
* 5. An API to get current purchases of the user immediately. This will not contain any
* consumed purchases.
*
* All calls will give a response code with the following possible values
* RESULT_OK = 0 - success
* RESULT_USER_CANCELED = 1 - user pressed back or canceled a dialog
* RESULT_BILLING_UNAVAILABLE = 3 - this billing API version is not supported for the type requested
* RESULT_ITEM_UNAVAILABLE = 4 - requested SKU is not available for purchase
* RESULT_DEVELOPER_ERROR = 5 - invalid arguments provided to the API
* RESULT_ERROR = 6 - Fatal error during the API action
* RESULT_ITEM_ALREADY_OWNED = 7 - Failure to purchase since item is already owned
* RESULT_ITEM_NOT_OWNED = 8 - Failure to consume since item is not owned
*/
interface IInAppBillingService {
/**
* Checks support for the requested billing API version, package and in-app type.
* Minimum API version supported by this interface is 3.
* @param apiVersion the billing version which the app is using
* @param packageName the package name of the calling app
* @param type type of the in-app item being purchased "inapp" for one-time purchases
* and "subs" for subscription.
* @return RESULT_OK(0) on success, corresponding result code on failures
*/
int isBillingSupported(int apiVersion, String packageName, String type);
/**
* Provides details of a list of SKUs
* Given a list of SKUs of a valid type in the skusBundle, this returns a bundle
* with a list JSON strings containing the productId, price, title and description.
* This API can be called with a maximum of 20 SKUs.
* @param apiVersion billing API version that the Third-party is using
* @param packageName the package name of the calling app
* @param skusBundle bundle containing a StringArrayList of SKUs with key "ITEM_ID_LIST"
* @return Bundle containing the following key-value pairs
* "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on
* failure as listed above.
* "DETAILS_LIST" with a StringArrayList containing purchase information
* in JSON format similar to:
* '{ "productId" : "exampleSku", "type" : "inapp", "price" : "$5.00",
* "title : "Example Title", "description" : "This is an example description" }'
*/
Bundle getSkuDetails(int apiVersion, String packageName, String type, in Bundle skusBundle);
/**
* Returns a pending intent to launch the purchase flow for an in-app item by providing a SKU,
* the type, a unique purchase token and an optional developer payload.
* @param apiVersion billing API version that the app is using
* @param packageName package name of the calling app
* @param sku the SKU of the in-app item as published in the developer console
* @param type the type of the in-app item ("inapp" for one-time purchases
* and "subs" for subscription).
* @param developerPayload optional argument to be sent back with the purchase information
* @return Bundle containing the following key-value pairs
* "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on
* failure as listed above.
* "BUY_INTENT" - PendingIntent to start the purchase flow
*
* The Pending intent should be launched with startIntentSenderForResult. When purchase flow
* has completed, the onActivityResult() will give a resultCode of OK or CANCELED.
* If the purchase is successful, the result data will contain the following key-value pairs
* "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on
* failure as listed above.
* "INAPP_PURCHASE_DATA" - String in JSON format similar to
* '{"orderId":"12999763169054705758.1371079406387615",
* "packageName":"com.example.app",
* "productId":"exampleSku",
* "purchaseTime":1345678900000,
* "purchaseToken" : "122333444455555",
* "developerPayload":"example developer payload" }'
* "INAPP_DATA_SIGNATURE" - String containing the signature of the purchase data that
* was signed with the private key of the developer
* TODO: change this to app-specific keys.
*/
Bundle getBuyIntent(int apiVersion, String packageName, String sku, String type,
String developerPayload);
/**
* Returns the current SKUs owned by the user of the type and package name specified along with
* purchase information and a signature of the data to be validated.
* This will return all SKUs that have been purchased in V3 and managed items purchased using
* V1 and V2 that have not been consumed.
* @param apiVersion billing API version that the app is using
* @param packageName package name of the calling app
* @param type the type of the in-app items being requested
* ("inapp" for one-time purchases and "subs" for subscription).
* @param continuationToken to be set as null for the first call, if the number of owned
* skus are too many, a continuationToken is returned in the response bundle.
* This method can be called again with the continuation token to get the next set of
* owned skus.
* @return Bundle containing the following key-value pairs
* "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on
* failure as listed above.
* "INAPP_PURCHASE_ITEM_LIST" - StringArrayList containing the list of SKUs
* "INAPP_PURCHASE_DATA_LIST" - StringArrayList containing the purchase information
* "INAPP_DATA_SIGNATURE_LIST"- StringArrayList containing the signatures
* of the purchase information
* "INAPP_CONTINUATION_TOKEN" - String containing a continuation token for the
* next set of in-app purchases. Only set if the
* user has more owned skus than the current list.
*/
Bundle getPurchases(int apiVersion, String packageName, String type, String continuationToken);
/**
* Consume the last purchase of the given SKU. This will result in this item being removed
* from all subsequent responses to getPurchases() and allow re-purchase of this item.
* @param apiVersion billing API version that the app is using
* @param packageName package name of the calling app
* @param purchaseToken token in the purchase information JSON that identifies the purchase
* to be consumed
* @return 0 if consumption succeeded. Appropriate error values for failures.
*/
int consumePurchase(int apiVersion, String packageName, String purchaseToken);
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,37 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates a constant field value should be exported to be used in the SDK tools.
*
* @hide
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.SOURCE)
public @interface SdkConstant {
public enum SdkConstantType {
ACTIVITY_INTENT_ACTION, BROADCAST_INTENT_ACTION, SERVICE_ACTION, INTENT_CATEGORY, FEATURE
}
SdkConstantType value();
}
@@ -1,110 +0,0 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.database.sqlite;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
/**
* @hide
*/
public final class SqliteWrapper {
private static final String TAG = "SqliteWrapper";
private static final String SQLITE_EXCEPTION_DETAIL_MESSAGE
= "unable to open database file";
private SqliteWrapper() {
// Forbidden being instantiated.
}
// FIXME: need to optimize this method.
private static boolean isLowMemory(SQLiteException e) {
return e.getMessage().equals(SQLITE_EXCEPTION_DETAIL_MESSAGE);
}
public static void checkSQLiteException(Context context, SQLiteException e) {
if (isLowMemory(e)) {
Toast.makeText(context, "Low Memory",
Toast.LENGTH_SHORT).show();
} else {
throw e;
}
}
public static Cursor query(Context context, ContentResolver resolver, Uri uri,
String[] projection, String selection, String[] selectionArgs, String sortOrder) {
try {
return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
} catch (SQLiteException e) {
Log.e(TAG, "Catch a SQLiteException when query: ", e);
checkSQLiteException(context, e);
return null;
}
}
@SuppressWarnings("deprecation")
public static boolean requery(Context context, Cursor cursor) {
try {
return cursor.requery();
} catch (SQLiteException e) {
Log.e(TAG, "Catch a SQLiteException when requery: ", e);
checkSQLiteException(context, e);
return false;
}
}
public static int update(Context context, ContentResolver resolver, Uri uri,
ContentValues values, String where, String[] selectionArgs) {
try {
return resolver.update(uri, values, where, selectionArgs);
} catch (SQLiteException e) {
Log.e(TAG, "Catch a SQLiteException when update: ", e);
checkSQLiteException(context, e);
return -1;
}
}
public static int delete(Context context, ContentResolver resolver, Uri uri,
String where, String[] selectionArgs) {
try {
return resolver.delete(uri, where, selectionArgs);
} catch (SQLiteException e) {
Log.e(TAG, "Catch a SQLiteException when delete: ", e);
checkSQLiteException(context, e);
return -1;
}
}
public static Uri insert(Context context, ContentResolver resolver,
Uri uri, ContentValues values) {
try {
return resolver.insert(uri, values);
} catch (SQLiteException e) {
Log.e(TAG, "Catch a SQLiteException when insert: ", e);
checkSQLiteException(context, e);
return null;
}
}
}
@@ -1,202 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package android.location;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import java.util.Locale;
/**
* This class wraps the country information.
*
* @hide
*/
public class Country implements Parcelable {
/**
* The country code came from the mobile network
*/
public static final int COUNTRY_SOURCE_NETWORK = 0;
/**
* The country code came from the location service
*/
public static final int COUNTRY_SOURCE_LOCATION = 1;
/**
* The country code was read from the SIM card
*/
public static final int COUNTRY_SOURCE_SIM = 2;
/**
* The country code came from the system locale setting
*/
public static final int COUNTRY_SOURCE_LOCALE = 3;
/**
* The ISO 3166-1 two letters country code.
*/
private final String mCountryIso;
/**
* Where the country code came from.
*/
private final int mSource;
private int mHashCode;
/**
* Time that this object was created (which we assume to be the time that the source was
* consulted). This time is in milliseconds since boot up.
*/
private final long mTimestamp;
/**
* @param countryIso the ISO 3166-1 two letters country code.
* @param source where the countryIso came from, could be one of below
* values
* <p>
* <ul>
* <li>{@link #COUNTRY_SOURCE_NETWORK}</li>
* <li>{@link #COUNTRY_SOURCE_LOCATION}</li>
* <li>{@link #COUNTRY_SOURCE_SIM}</li>
* <li>{@link #COUNTRY_SOURCE_LOCALE}</li>
* </ul>
*/
public Country(final String countryIso, final int source) {
if (countryIso == null || source < COUNTRY_SOURCE_NETWORK
|| source > COUNTRY_SOURCE_LOCALE) {
throw new IllegalArgumentException();
}
mCountryIso = countryIso.toUpperCase(Locale.US);
mSource = source;
mTimestamp = SystemClock.elapsedRealtime();
}
private Country(final String countryIso, final int source, long timestamp) {
if (countryIso == null || source < COUNTRY_SOURCE_NETWORK
|| source > COUNTRY_SOURCE_LOCALE) {
throw new IllegalArgumentException();
}
mCountryIso = countryIso.toUpperCase(Locale.US);
mSource = source;
mTimestamp = timestamp;
}
public Country(Country country) {
mCountryIso = country.mCountryIso;
mSource = country.mSource;
mTimestamp = country.mTimestamp;
}
/**
* @return the ISO 3166-1 two letters country code
*/
public final String getCountryIso() {
return mCountryIso;
}
/**
* @return where the country code came from, could be one of below values
* <p>
* <ul>
* <li>{@link #COUNTRY_SOURCE_NETWORK}</li>
* <li>{@link #COUNTRY_SOURCE_LOCATION}</li>
* <li>{@link #COUNTRY_SOURCE_SIM}</li>
* <li>{@link #COUNTRY_SOURCE_LOCALE}</li>
* </ul>
*/
public final int getSource() {
return mSource;
}
/**
* Returns the time that this object was created (which we assume to be the time that the source
* was consulted).
*/
public final long getTimestamp() {
return mTimestamp;
}
public static final Parcelable.Creator<Country> CREATOR = new Parcelable.Creator<Country>() {
public Country createFromParcel(Parcel in) {
return new Country(in.readString(), in.readInt(), in.readLong());
}
public Country[] newArray(int size) {
return new Country[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(mCountryIso);
parcel.writeInt(mSource);
parcel.writeLong(mTimestamp);
}
/**
* Returns true if this {@link Country} is equivalent to the given object. This ignores
* the timestamp value and just checks for equivalence of countryIso and source values.
* Returns false otherwise.
*/
@Override
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof Country) {
Country c = (Country) object;
// No need to check the equivalence of the timestamp
return mCountryIso.equals(c.getCountryIso()) && mSource == c.getSource();
}
return false;
}
@Override
public int hashCode() {
int hash = mHashCode;
if (hash == 0) {
hash = 17;
hash = hash * 13 + mCountryIso.hashCode();
hash = hash * 13 + mSource;
mHashCode = hash;
}
return mHashCode;
}
/**
* Compare the specified country to this country object ignoring the source
* and timestamp fields, return true if the countryIso fields are equal
*
* @param country the country to compare
* @return true if the specified country's countryIso field is equal to this
* country's, false otherwise.
*/
public boolean equalsIgnoreSource(Country country) {
return country != null && mCountryIso.equals(country.getCountryIso());
}
@Override
public String toString() {
return "Country {ISO=" + mCountryIso + ", source=" + mSource + ", time=" + mTimestamp + "}";
}
}
@@ -1,137 +0,0 @@
/*
* Copyright (C) 2010, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.location;
import android.os.Handler;
import android.os.Looper;
import java.util.HashMap;
/**
* This class provides access to the system country detector service. This
* service allows applications to obtain the country that the user is in.
* <p>
* The country will be detected in order of reliability, like
* <ul>
* <li>Mobile network</li>
* <li>Location</li>
* <li>SIM's country</li>
* <li>Phone's locale</li>
* </ul>
* <p>
* Call the {@link #detectCountry()} to get the available country immediately.
* <p>
* To be notified of the future country change, use the
* {@link #addCountryListener}
* <p>
* <p>
* You do not instantiate this class directly; instead, retrieve it through
* {@link android.content.Context#getSystemService
* Context.getSystemService(Context.COUNTRY_DETECTOR)}.
* <p>
* Both ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION permissions are needed.
*
* @hide
*/
public class CountryDetector {
/**
* The class to wrap the ICountryListener.Stub and CountryListener objects
* together. The CountryListener will be notified through the specific
* looper once the country changed and detected.
*/
private final static class ListenerTransport implements ICountryListener {
private final CountryListener mListener;
private final Handler mHandler;
public ListenerTransport(CountryListener listener, Looper looper) {
mListener = listener;
if (looper != null) {
mHandler = new Handler(looper);
} else {
mHandler = new Handler();
}
}
public void onCountryDetected(final Country country) {
mHandler.post(new Runnable() {
public void run() {
mListener.onCountryDetected(country);
}
});
}
}
private final static String TAG = "CountryDetector";
private final ICountryDetector mService;
private final HashMap<CountryListener, ListenerTransport> mListeners;
/**
* @hide - hide this constructor because it has a parameter of type
* ICountryDetector, which is a system private class. The right way to
* create an instance of this class is using the factory
* Context.getSystemService.
*/
public CountryDetector(ICountryDetector service) {
mService = service;
mListeners = new HashMap<>();
}
/**
* Start detecting the country that the user is in.
*
* @return the country if it is available immediately, otherwise null will
* be returned.
*/
public Country detectCountry() {
return mService.detectCountry();
}
/**
* Add a listener to receive the notification when the country is detected
* or changed.
*
* @param listener will be called when the country is detected or changed.
* @param looper a Looper object whose message queue will be used to
* implement the callback mechanism. If looper is null then the
* callbacks will be called on the main thread.
*/
public void addCountryListener(CountryListener listener, Looper looper) {
synchronized (mListeners) {
if (!mListeners.containsKey(listener)) {
ListenerTransport transport = new ListenerTransport(listener, looper);
mService.addCountryListener(transport);
mListeners.put(listener, transport);
}
}
}
/**
* Remove the listener
*/
public void removeCountryListener(CountryListener listener) {
synchronized (mListeners) {
ListenerTransport transport = mListeners.get(listener);
if (transport != null) {
mListeners.remove(listener);
mService.removeCountryListener(transport);
}
}
}
}
@@ -1,30 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package android.location;
/**
* The listener for receiving the notification when the country is detected or
* changed
*
* @hide
*/
public interface CountryListener {
/**
* @param country the changed or detected country.
*/
void onCountryDetected(Country country);
}
@@ -1,41 +0,0 @@
/*
* Copyright (C) 2010, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.location;
/**
* The API for detecting the country where the user is.
*
* {@hide}
*/
interface ICountryDetector
{
/**
* Start detecting the country that the user is in.
* @return the country if it is available immediately, otherwise null will be returned.
*/
Country detectCountry();
/**
* Add a listener to receive the notification when the country is detected or changed.
*/
void addCountryListener(ICountryListener listener);
/**
* Remove the listener
*/
void removeCountryListener(ICountryListener listener);
}
@@ -1,26 +0,0 @@
/*
* Copyright (C) 2010, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.location;
/**
* {@hide}
*/
interface ICountryListener
{
void onCountryDetected(Country country);
}
@@ -1,989 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.content.Context;
import android.os.Binder;
import android.os.Build.VERSION_CODES;
import android.os.RemoteException;
import android.provider.Settings;
import java.net.InetAddress;
import static com.android.internal.util.Preconditions.checkNotNull;
/**
* Class that answers queries about the state of network connectivity. It also
* notifies applications when network connectivity changes. Get an instance
* of this class by calling
* {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.CONNECTIVITY_SERVICE)}.
* <p/>
* The primary responsibilities of this class are to:
* <ol>
* <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
* <li>Send broadcast intents when network connectivity changes</li>
* <li>Attempt to "fail over" to another network when connectivity to a network
* is lost</li>
* <li>Provide an API that allows applications to query the coarse-grained or fine-grained
* state of the available networks</li>
* </ol>
*/
public class ConnectivityManager {
/**
* A change in network connectivity has occurred. A connection has either
* been established or lost. The NetworkInfo for the affected network is
* sent as an extra; it should be consulted to see what kind of
* connectivity event occurred.
* <p/>
* If this is a connection that was the result of failing over from a
* disconnected network, then the FAILOVER_CONNECTION boolean extra is
* set to true.
* <p/>
* For a loss of connectivity, if the connectivity manager is attempting
* to connect (or has already connected) to another network, the
* NetworkInfo for the new network is also passed as an extra. This lets
* any receivers of the broadcast know that they should not necessarily
* tell the user that no data traffic will be possible. Instead, the
* reciever should expect another broadcast soon, indicating either that
* the failover attempt succeeded (and so there is still overall data
* connectivity), or that the failover attempt failed, meaning that all
* connectivity has been lost.
* <p/>
* For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
* is set to {@code true} if there are no connected networks at all.
*/
public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
/**
* Identical to {@link #CONNECTIVITY_ACTION} broadcast, but sent without any
* applicable {@link Settings.Secure#CONNECTIVITY_CHANGE_DELAY}.
*
* @hide
*/
public static final String CONNECTIVITY_ACTION_IMMEDIATE =
"android.net.conn.CONNECTIVITY_CHANGE_IMMEDIATE";
/**
* The lookup key for a {@link NetworkInfo} object. Retrieve with
* {@link android.content.Intent#getParcelableExtra(String)}.
*
* @see #EXTRA_NETWORK_TYPE
* @deprecated Since {@link NetworkInfo} can vary based on UID, applications
* should always obtain network information through
* {@link #getActiveNetworkInfo()} or
* {@link #getAllNetworkInfo()}.
*/
@Deprecated
public static final String EXTRA_NETWORK_INFO = "networkInfo";
/**
* Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
* Can be used with {@link #getNetworkInfo(int)} to get {@link NetworkInfo}
* state based on the calling application.
*
* @see android.content.Intent#getIntExtra(String, int)
*/
public static final String EXTRA_NETWORK_TYPE = "networkType";
/**
* The lookup key for a boolean that indicates whether a connect event
* is for a network to which the connectivity manager was failing over
* following a disconnect on another network.
* Retrieve it with {@link android.content.Intent#getBooleanExtra(String, boolean)}.
*/
public static final String EXTRA_IS_FAILOVER = "isFailover";
/**
* The lookup key for a {@link NetworkInfo} object. This is supplied when
* there is another network that it may be possible to connect to. Retrieve with
* {@link android.content.Intent#getParcelableExtra(String)}.
*/
public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
/**
* The lookup key for a boolean that indicates whether there is a
* complete lack of connectivity, i.e., no network is available.
* Retrieve it with {@link android.content.Intent#getBooleanExtra(String, boolean)}.
*/
public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
/**
* The lookup key for a string that indicates why an attempt to connect
* to a network failed. The string has no particular structure. It is
* intended to be used in notifications presented to users. Retrieve
* it with {@link android.content.Intent#getStringExtra(String)}.
*/
public static final String EXTRA_REASON = "reason";
/**
* The lookup key for a string that provides optionally supplied
* extra information about the network state. The information
* may be passed up from the lower networking layers, and its
* meaning may be specific to a particular network type. Retrieve
* it with {@link android.content.Intent#getStringExtra(String)}.
*/
public static final String EXTRA_EXTRA_INFO = "extraInfo";
/**
* The lookup key for an int that provides information about
* our connection to the internet at large. 0 indicates no connection,
* 100 indicates a great connection. Retrieve it with
* {@link android.content.Intent#getIntExtra(String, int)}.
* {@hide}
*/
public static final String EXTRA_INET_CONDITION = "inetCondition";
/**
* Broadcast action to indicate the change of data activity status
* (idle or active) on a network in a recent period.
* The network becomes active when data transimission is started, or
* idle if there is no data transimition for a period of time.
* {@hide}
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_DATA_ACTIVITY_CHANGE = "android.net.conn.DATA_ACTIVITY_CHANGE";
/**
* The lookup key for an enum that indicates the network device type on which this data activity
* change happens.
* {@hide}
*/
public static final String EXTRA_DEVICE_TYPE = "deviceType";
/**
* The lookup key for a boolean that indicates the device is active or not. {@code true} means
* it is actively sending or receiving data and {@code false} means it is idle.
* {@hide}
*/
public static final String EXTRA_IS_ACTIVE = "isActive";
/**
* Broadcast Action: The setting for background data usage has changed
* values. Use {@link #getBackgroundDataSetting()} to get the current value.
* <p/>
* If an application uses the network in the background, it should listen
* for this broadcast and stop using the background data if the value is
* {@code false}.
* <p/>
*
* @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
* of background data depends on several combined factors, and
* this broadcast is no longer sent. Instead, when background
* data is unavailable, {@link #getActiveNetworkInfo()} will now
* appear disconnected. During first boot after a platform
* upgrade, this broadcast will be sent once if
* {@link #getBackgroundDataSetting()} was {@code false} before
* the upgrade.
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
@Deprecated
public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
"android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
/**
* Broadcast Action: The network connection may not be good
* uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
* {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
* the network and it's condition.
*
* @hide
*/
public static final String INET_CONDITION_ACTION =
"android.net.conn.INET_CONDITION_ACTION";
/**
* Broadcast Action: A tetherable connection has come or gone
* TODO - finish the doc
*
* @hide
*/
public static final String ACTION_TETHER_STATE_CHANGED =
"android.net.conn.TETHER_STATE_CHANGED";
/**
* @hide gives a String[]
*/
public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
/**
* @hide gives a String[]
*/
public static final String EXTRA_ACTIVE_TETHER = "activeArray";
/**
* @hide gives a String[]
*/
public static final String EXTRA_ERRORED_TETHER = "erroredArray";
/**
* The absence of APN..
*
* @hide
*/
public static final int TYPE_NONE = -1;
/**
* The Default Mobile data connection. When active, all data traffic
* will use this connection by default.
*/
public static final int TYPE_MOBILE = 0;
/**
* The Default WIFI data connection. When active, all data traffic
* will use this connection by default.
*/
public static final int TYPE_WIFI = 1;
/**
* An MMS-specific Mobile data connection. This connection may be the
* same as {@link #TYPE_MOBILE} but it may be different. This is used
* by applications needing to talk to the carrier's Multimedia Messaging
* Service servers. It may coexist with default data connections.
*/
public static final int TYPE_MOBILE_MMS = 2;
/**
* A SUPL-specific Mobile data connection. This connection may be the
* same as {@link #TYPE_MOBILE} but it may be different. This is used
* by applications needing to talk to the carrier's Secure User Plane
* Location servers for help locating the device. It may coexist with
* default data connections.
*/
public static final int TYPE_MOBILE_SUPL = 3;
/**
* A DUN-specific Mobile data connection. This connection may be the
* same as {@link #TYPE_MOBILE} but it may be different. This is used
* by applicaitons performing a Dial Up Networking bridge so that
* the carrier is aware of DUN traffic. It may coexist with default data
* connections.
*/
public static final int TYPE_MOBILE_DUN = 4;
/**
* A High Priority Mobile data connection. This connection is typically
* the same as {@link #TYPE_MOBILE} but the routing setup is different.
* Only requesting processes will have access to the Mobile DNS servers
* and only IP's explicitly requested via {@link #requestRouteToHost}
* will route over this interface if a default route exists.
*/
public static final int TYPE_MOBILE_HIPRI = 5;
/**
* The Default WiMAX data connection. When active, all data traffic
* will use this connection by default.
*/
public static final int TYPE_WIMAX = 6;
/**
* The Default Bluetooth data connection. When active, all data traffic
* will use this connection by default.
*/
public static final int TYPE_BLUETOOTH = 7;
/**
* Dummy data connection. This should not be used on shipping devices.
*/
public static final int TYPE_DUMMY = 8;
/**
* The Default Ethernet data connection. When active, all data traffic
* will use this connection by default.
*/
public static final int TYPE_ETHERNET = 9;
/**
* Over the air Adminstration.
* {@hide}
*/
public static final int TYPE_MOBILE_FOTA = 10;
/**
* IP Multimedia Subsystem
* {@hide}
*/
public static final int TYPE_MOBILE_IMS = 11;
/**
* Carrier Branded Services
* {@hide}
*/
public static final int TYPE_MOBILE_CBS = 12;
/**
* A Wi-Fi p2p connection. Only requesting processes will have access to
* the peers connected.
* {@hide}
*/
public static final int TYPE_WIFI_P2P = 13;
/**
* {@hide}
*/
public static final int MAX_RADIO_TYPE = TYPE_WIFI_P2P;
/**
* {@hide}
*/
public static final int MAX_NETWORK_TYPE = TYPE_WIFI_P2P;
public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
/**
* Default value for {@link Settings.Global#CONNECTIVITY_CHANGE_DELAY} in
* milliseconds.
*
* @hide
*/
public static final int CONNECTIVITY_CHANGE_DELAY_DEFAULT = 3000;
private final IConnectivityManager mService;
public static boolean isNetworkTypeValid(int networkType) {
return networkType >= 0 && networkType <= MAX_NETWORK_TYPE;
}
/**
* {@hide}
*/
public static String getNetworkTypeName(int type) {
switch (type) {
case TYPE_MOBILE:
return "MOBILE";
case TYPE_WIFI:
return "WIFI";
case TYPE_MOBILE_MMS:
return "MOBILE_MMS";
case TYPE_MOBILE_SUPL:
return "MOBILE_SUPL";
case TYPE_MOBILE_DUN:
return "MOBILE_DUN";
case TYPE_MOBILE_HIPRI:
return "MOBILE_HIPRI";
case TYPE_WIMAX:
return "WIMAX";
case TYPE_BLUETOOTH:
return "BLUETOOTH";
case TYPE_DUMMY:
return "DUMMY";
case TYPE_ETHERNET:
return "ETHERNET";
case TYPE_MOBILE_FOTA:
return "MOBILE_FOTA";
case TYPE_MOBILE_IMS:
return "MOBILE_IMS";
case TYPE_MOBILE_CBS:
return "MOBILE_CBS";
case TYPE_WIFI_P2P:
return "WIFI_P2P";
default:
return Integer.toString(type);
}
}
/**
* {@hide}
*/
public static boolean isNetworkTypeMobile(int networkType) {
switch (networkType) {
case TYPE_MOBILE:
case TYPE_MOBILE_MMS:
case TYPE_MOBILE_SUPL:
case TYPE_MOBILE_DUN:
case TYPE_MOBILE_HIPRI:
case TYPE_MOBILE_FOTA:
case TYPE_MOBILE_IMS:
case TYPE_MOBILE_CBS:
return true;
default:
return false;
}
}
public void setNetworkPreference(int preference) {
try {
mService.setNetworkPreference(preference);
} catch (RemoteException e) {
}
}
public int getNetworkPreference() {
try {
return mService.getNetworkPreference();
} catch (RemoteException e) {
return -1;
}
}
/**
* Returns details about the currently active data network. When connected,
* this network is the default route for outgoing connections. You should
* always check {@link NetworkInfo#isConnected()} before initiating network
* traffic. This may return {@code null} when no networks are available.
* <p>This method requires the caller to hold the permission
* {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
*/
public NetworkInfo getActiveNetworkInfo() {
try {
return mService.getActiveNetworkInfo();
} catch (RemoteException e) {
return null;
}
}
/**
* {@hide}
*/
public NetworkInfo getActiveNetworkInfoForUid(int uid) {
try {
return mService.getActiveNetworkInfoForUid(uid);
} catch (RemoteException e) {
return null;
}
}
public NetworkInfo getNetworkInfo(int networkType) {
try {
return mService.getNetworkInfo(networkType);
} catch (RemoteException e) {
return null;
}
}
public NetworkInfo[] getAllNetworkInfo() {
try {
return mService.getAllNetworkInfo();
} catch (RemoteException e) {
return null;
}
}
/**
* {@hide}
*/
public LinkProperties getActiveLinkProperties() {
try {
return mService.getActiveLinkProperties();
} catch (RemoteException e) {
return null;
}
}
/**
* {@hide}
*/
public LinkProperties getLinkProperties(int networkType) {
try {
return mService.getLinkProperties(networkType);
} catch (RemoteException e) {
return null;
}
}
/**
* {@hide}
*/
public boolean setRadios(boolean turnOn) {
try {
return mService.setRadios(turnOn);
} catch (RemoteException e) {
return false;
}
}
/**
* {@hide}
*/
public boolean setRadio(int networkType, boolean turnOn) {
try {
return mService.setRadio(networkType, turnOn);
} catch (RemoteException e) {
return false;
}
}
/**
* Tells the underlying networking system that the caller wants to
* begin using the named feature. The interpretation of {@code feature}
* is completely up to each networking implementation.
* <p>This method requires the caller to hold the permission
* {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
*
* @param networkType specifies which network the request pertains to
* @param feature the name of the feature to be used
* @return an integer value representing the outcome of the request.
* The interpretation of this value is specific to each networking
* implementation+feature combination, except that the value {@code -1}
* always indicates failure.
*/
public int startUsingNetworkFeature(int networkType, String feature) {
try {
return mService.startUsingNetworkFeature(networkType, feature,
new Binder());
} catch (RemoteException e) {
return -1;
}
}
/**
* Tells the underlying networking system that the caller is finished
* using the named feature. The interpretation of {@code feature}
* is completely up to each networking implementation.
* <p>This method requires the caller to hold the permission
* {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
*
* @param networkType specifies which network the request pertains to
* @param feature the name of the feature that is no longer needed
* @return an integer value representing the outcome of the request.
* The interpretation of this value is specific to each networking
* implementation+feature combination, except that the value {@code -1}
* always indicates failure.
*/
public int stopUsingNetworkFeature(int networkType, String feature) {
try {
return mService.stopUsingNetworkFeature(networkType, feature);
} catch (RemoteException e) {
return -1;
}
}
/**
* Ensure that a network route exists to deliver traffic to the specified
* host via the specified network interface. An attempt to add a route that
* already exists is ignored, but treated as successful.
* <p>This method requires the caller to hold the permission
* {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
*
* @param networkType the type of the network over which traffic to the specified
* host is to be routed
* @param hostAddress the IP address of the host to which the route is desired
* @return {@code true} on success, {@code false} on failure
*/
public boolean requestRouteToHost(int networkType, int hostAddress) {
InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
return inetAddress != null && requestRouteToHostAddress(networkType, inetAddress);
}
/**
* Ensure that a network route exists to deliver traffic to the specified
* host via the specified network interface. An attempt to add a route that
* already exists is ignored, but treated as successful.
*
* @param networkType the type of the network over which traffic to the specified
* host is to be routed
* @param hostAddress the IP address of the host to which the route is desired
* @return {@code true} on success, {@code false} on failure
* @hide
*/
public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
byte[] address = hostAddress.getAddress();
try {
return mService.requestRouteToHostAddress(networkType, address);
} catch (RemoteException e) {
return false;
}
}
/**
* Returns the value of the setting for background data usage. If false,
* applications should not use the network if the application is not in the
* foreground. Developers should respect this setting, and check the value
* of this before performing any background data operations.
* <p/>
* All applications that have background services that use the network
* should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
* <p/>
*
* @return Whether background data usage is allowed.
* @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
* background data depends on several combined factors, and this method will
* always return {@code true}. Instead, when background data is unavailable,
* {@link #getActiveNetworkInfo()} will now appear disconnected.
*/
@Deprecated
public boolean getBackgroundDataSetting() {
// assume that background data is allowed; final authority is
// NetworkInfo which may be blocked.
return true;
}
/**
* Sets the value of the setting for background data usage.
*
* @param allowBackgroundData Whether an application should use data while
* it is in the background.
* @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
* @hide
* @see #getBackgroundDataSetting()
*/
@Deprecated
public void setBackgroundDataSetting(boolean allowBackgroundData) {
// ignored
}
/**
* Return quota status for the current active network, or {@code null} if no
* network is active. Quota status can change rapidly, so these values
* shouldn't be cached.
*
* @hide
*/
public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
try {
return mService.getActiveNetworkQuotaInfo();
} catch (RemoteException e) {
return null;
}
}
/**
* Gets the value of the setting for enabling Mobile data.
*
* @return Whether mobile data is enabled.
* @hide
*/
public boolean getMobileDataEnabled() {
try {
return mService.getMobileDataEnabled();
} catch (RemoteException e) {
return true;
}
}
/**
* Sets the persisted value for enabling/disabling Mobile data.
*
* @param enabled Whether the mobile data connection should be
* used or not.
* @hide
*/
public void setMobileDataEnabled(boolean enabled) {
try {
mService.setMobileDataEnabled(enabled);
} catch (RemoteException e) {
}
}
/**
* {@hide}
*/
public ConnectivityManager(IConnectivityManager service) {
mService = checkNotNull(service, "missing IConnectivityManager");
}
/**
* {@hide}
*/
public static ConnectivityManager from(Context context) {
return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
/**
* {@hide}
*/
public String[] getTetherableIfaces() {
try {
return mService.getTetherableIfaces();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* {@hide}
*/
public String[] getTetheredIfaces() {
try {
return mService.getTetheredIfaces();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* {@hide}
*/
public String[] getTetheringErroredIfaces() {
try {
return mService.getTetheringErroredIfaces();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* @return error A TETHER_ERROR value indicating success or failure type
* {@hide}
*/
public int tether(String iface) {
try {
return mService.tether(iface);
} catch (RemoteException e) {
return TETHER_ERROR_SERVICE_UNAVAIL;
}
}
/**
* @return error A TETHER_ERROR value indicating success or failure type
* {@hide}
*/
public int untether(String iface) {
try {
return mService.untether(iface);
} catch (RemoteException e) {
return TETHER_ERROR_SERVICE_UNAVAIL;
}
}
/**
* {@hide}
*/
public boolean isTetheringSupported() {
try {
return mService.isTetheringSupported();
} catch (RemoteException e) {
return false;
}
}
/**
* {@hide}
*/
public String[] getTetherableUsbRegexs() {
try {
return mService.getTetherableUsbRegexs();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* {@hide}
*/
public String[] getTetherableWifiRegexs() {
try {
return mService.getTetherableWifiRegexs();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* {@hide}
*/
public String[] getTetherableBluetoothRegexs() {
try {
return mService.getTetherableBluetoothRegexs();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* {@hide}
*/
public int setUsbTethering(boolean enable) {
try {
return mService.setUsbTethering(enable);
} catch (RemoteException e) {
return TETHER_ERROR_SERVICE_UNAVAIL;
}
}
/**
* {@hide}
*/
public static final int TETHER_ERROR_NO_ERROR = 0;
/**
* {@hide}
*/
public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
/**
* {@hide}
*/
public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
/**
* {@hide}
*/
public static final int TETHER_ERROR_UNSUPPORTED = 3;
/**
* {@hide}
*/
public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
/**
* {@hide}
*/
public static final int TETHER_ERROR_MASTER_ERROR = 5;
/**
* {@hide}
*/
public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
/**
* {@hide}
*/
public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
/**
* {@hide}
*/
public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
/**
* {@hide}
*/
public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
/**
* {@hide}
*/
public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
/**
* @param iface The name of the interface we're interested in
* @return error The error code of the last error tethering or untethering the named
* interface
* {@hide}
*/
public int getLastTetherError(String iface) {
try {
return mService.getLastTetherError(iface);
} catch (RemoteException e) {
return TETHER_ERROR_SERVICE_UNAVAIL;
}
}
/**
* Ensure the device stays awake until we connect with the next network
*
* @param forWhome The name of the network going down for logging purposes
* @return {@code true} on success, {@code false} on failure
* {@hide}
*/
public boolean requestNetworkTransitionWakelock(String forWhom) {
try {
mService.requestNetworkTransitionWakelock(forWhom);
return true;
} catch (RemoteException e) {
return false;
}
}
/**
* @param networkType The type of network you want to report on
* @param percentage The quality of the connection 0 is bad, 100 is good
* {@hide}
*/
public void reportInetCondition(int networkType, int percentage) {
try {
mService.reportInetCondition(networkType, percentage);
} catch (RemoteException e) {
}
}
/**
* @param proxyProperties The definition for the new global http proxy
* {@hide}
*/
public void setGlobalProxy(ProxyProperties p) {
try {
mService.setGlobalProxy(p);
} catch (RemoteException e) {
}
}
/**
* @return proxyProperties for the current global proxy
* {@hide}
*/
public ProxyProperties getGlobalProxy() {
try {
return mService.getGlobalProxy();
} catch (RemoteException e) {
return null;
}
}
/**
* @return proxyProperties for the current proxy (global if set, network specific if not)
* {@hide}
*/
public ProxyProperties getProxy() {
try {
return mService.getProxy();
} catch (RemoteException e) {
return null;
}
}
/**
* @param networkType The network who's dependence has changed
* @param met Boolean - true if network use is ok, false if not
* {@hide}
*/
public void setDataDependency(int networkType, boolean met) {
try {
mService.setDataDependency(networkType, met);
} catch (RemoteException e) {
}
}
/**
* Returns true if the hardware supports the given network type
* else it returns false. This doesn't indicate we have coverage
* or are authorized onto a network, just whether or not the
* hardware supports it. For example a gsm phone without a sim
* should still return true for mobile data, but a wifi only tablet
* would return false.
*
* @param networkType The nework type we'd like to check
* @return true if supported, else false
* @hide
*/
public boolean isNetworkSupported(int networkType) {
try {
return mService.isNetworkSupported(networkType);
} catch (RemoteException e) {
}
return false;
}
/**
* Returns if the currently active data network is metered. A network is
* classified as metered when the user is sensitive to heavy data usage on
* that connection. You should check this before doing large data transfers,
* and warn the user or delay the operation until another network is
* available.
*/
public boolean isActiveNetworkMetered() {
try {
return mService.isActiveNetworkMetered();
} catch (RemoteException e) {
return false;
}
}
/**
* {@hide}
*/
public boolean updateLockdownVpn() {
try {
return mService.updateLockdownVpn();
} catch (RemoteException e) {
return false;
}
}
/**
* {@hide}
*/
public void captivePortalCheckComplete(NetworkInfo info) {
try {
mService.captivePortalCheckComplete(info);
} catch (RemoteException e) {
}
}
}
@@ -1,167 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.text.TextUtils;
import android.util.Log;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* A simple object for retrieving the results of a DHCP request.
* Replaces (internally) the IPv4-only DhcpInfo class.
*
* @hide
*/
public class DhcpInfoInternal {
private static final String TAG = "DhcpInfoInternal";
private static final boolean LOCAL_LOGV = false;
public String ipAddress;
public int prefixLength;
public String dns1;
public String dns2;
public String serverAddress;
public int leaseDuration;
/**
* Vendor specific information (from RFC 2132).
*/
public String vendorInfo;
private Collection<RouteInfo> mRoutes;
public DhcpInfoInternal() {
mRoutes = new ArrayList<>();
}
public void addRoute(RouteInfo routeInfo) {
mRoutes.add(routeInfo);
}
public Collection<RouteInfo> getRoutes() {
return Collections.unmodifiableCollection(mRoutes);
}
private int convertToInt(String addr) {
if (addr != null) {
try {
InetAddress inetAddress = NetworkUtils.numericToInetAddress(addr);
if (inetAddress instanceof Inet4Address) {
return NetworkUtils.inetAddressToInt(inetAddress);
}
} catch (IllegalArgumentException e) {
}
}
return 0;
}
public DhcpInfo makeDhcpInfo() {
DhcpInfo info = new DhcpInfo();
info.ipAddress = convertToInt(ipAddress);
for (RouteInfo route : mRoutes) {
if (route.isDefaultRoute()) {
info.gateway = convertToInt(route.getGateway().getHostAddress());
break;
}
}
try {
info.netmask = NetworkUtils.prefixLengthToNetmaskInt(prefixLength);
} catch (IllegalArgumentException e) {
}
info.dns1 = convertToInt(dns1);
info.dns2 = convertToInt(dns2);
info.serverAddress = convertToInt(serverAddress);
info.leaseDuration = leaseDuration;
return info;
}
public LinkAddress makeLinkAddress() {
if (TextUtils.isEmpty(ipAddress)) {
Log.e(TAG, "makeLinkAddress with empty ipAddress");
return null;
}
return new LinkAddress(NetworkUtils.numericToInetAddress(ipAddress), prefixLength);
}
public LinkProperties makeLinkProperties() {
LinkProperties p = new LinkProperties();
p.addLinkAddress(makeLinkAddress());
for (RouteInfo route : mRoutes) {
p.addRoute(route);
}
//if empty, connectivity configures default DNS
if (!TextUtils.isEmpty(dns1)) {
p.addDns(NetworkUtils.numericToInetAddress(dns1));
} else {
if (LOCAL_LOGV) Log.v(TAG, "makeLinkProperties with empty dns1!");
}
if (!TextUtils.isEmpty(dns2)) {
p.addDns(NetworkUtils.numericToInetAddress(dns2));
} else {
if (LOCAL_LOGV) Log.v(TAG, "makeLinkProperties with empty dns2!");
}
return p;
}
/* Updates the DHCP fields that need to be retained from
* original DHCP request if the DHCP renewal shows them as
* being empty
*/
public void updateFromDhcpRequest(DhcpInfoInternal orig) {
if (orig == null) return;
if (TextUtils.isEmpty(dns1)) {
dns1 = orig.dns1;
}
if (TextUtils.isEmpty(dns2)) {
dns2 = orig.dns2;
}
if (mRoutes.isEmpty()) {
for (RouteInfo route : orig.getRoutes()) {
addRoute(route);
}
}
}
/**
* Test if this DHCP lease includes vendor hint that network link is
* metered, and sensitive to heavy data transfers.
*/
public boolean hasMeteredHint() {
return vendorInfo != null && vendorInfo.contains("ANDROID_METERED");
}
public String toString() {
String routeString = "";
for (RouteInfo route : mRoutes) routeString += route.toString() + " | ";
return "addr: " + ipAddress + "/" + prefixLength +
" mRoutes: " + routeString +
" dns: " + dns1 + "," + dns2 +
" dhcpServer: " + serverAddress +
" leaseDuration: " + leaseDuration;
}
}
File diff suppressed because it is too large Load Diff
@@ -1,138 +0,0 @@
/*
* This file is auto-generated. DO NOT MODIFY.
* Original file: frameworks/base/core/java/android/net/INetworkPolicyListener.aidl
*/
package android.net;
/**
* {@hide}
*/
public interface INetworkPolicyListener extends android.os.IInterface {
/**
* Local-side IPC implementation stub class.
*/
public abstract static class Stub extends android.os.Binder implements android.net.INetworkPolicyListener {
private static final String DESCRIPTOR = "android.net.INetworkPolicyListener";
/**
* Construct the stub at attach it to the interface.
*/
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an android.net.INetworkPolicyListener interface,
* generating a proxy if needed.
*/
public static android.net.INetworkPolicyListener asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof android.net.INetworkPolicyListener))) {
return ((android.net.INetworkPolicyListener) iin);
}
return new android.net.INetworkPolicyListener.Stub.Proxy(obj);
}
@Override
public android.os.IBinder asBinder() {
return this;
}
@Override
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_onUidRulesChanged: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int _arg1;
_arg1 = data.readInt();
this.onUidRulesChanged(_arg0, _arg1);
return true;
}
case TRANSACTION_onMeteredIfacesChanged: {
data.enforceInterface(DESCRIPTOR);
String[] _arg0;
_arg0 = data.createStringArray();
this.onMeteredIfacesChanged(_arg0);
return true;
}
case TRANSACTION_onRestrictBackgroundChanged: {
data.enforceInterface(DESCRIPTOR);
boolean _arg0;
_arg0 = (0 != data.readInt());
this.onRestrictBackgroundChanged(_arg0);
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements android.net.INetworkPolicyListener {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
@Override
public android.os.IBinder asBinder() {
return mRemote;
}
@Override
public void onUidRulesChanged(int uid, int uidRules) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(uid);
_data.writeInt(uidRules);
mRemote.transact(Stub.TRANSACTION_onUidRulesChanged, _data, null, android.os.IBinder.FLAG_ONEWAY);
} finally {
_data.recycle();
}
}
@Override
public void onMeteredIfacesChanged(String[] meteredIfaces) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeStringArray(meteredIfaces);
mRemote.transact(Stub.TRANSACTION_onMeteredIfacesChanged, _data, null, android.os.IBinder.FLAG_ONEWAY);
} finally {
_data.recycle();
}
}
@Override
public void onRestrictBackgroundChanged(boolean restrictBackground) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(((restrictBackground) ? (1) : (0)));
mRemote.transact(Stub.TRANSACTION_onRestrictBackgroundChanged, _data, null, android.os.IBinder.FLAG_ONEWAY);
} finally {
_data.recycle();
}
}
}
static final int TRANSACTION_onUidRulesChanged = (android.os.IBinder.FIRST_CALL_TRANSACTION);
static final int TRANSACTION_onMeteredIfacesChanged = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
static final int TRANSACTION_onRestrictBackgroundChanged = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2);
}
public void onUidRulesChanged(int uid, int uidRules) throws android.os.RemoteException;
public void onMeteredIfacesChanged(String[] meteredIfaces) throws android.os.RemoteException;
public void onRestrictBackgroundChanged(boolean restrictBackground) throws android.os.RemoteException;
}
@@ -1,494 +0,0 @@
/*
* This file is auto-generated. DO NOT MODIFY.
* Original file: frameworks/base/core/java/android/net/INetworkPolicyManager.aidl
*/
package android.net;
/**
* Interface that creates and modifies network policy rules.
* <p/>
* {@hide}
*/
public interface INetworkPolicyManager extends android.os.IInterface {
/**
* Local-side IPC implementation stub class.
*/
public abstract static class Stub extends android.os.Binder implements android.net.INetworkPolicyManager {
private static final String DESCRIPTOR = "android.net.INetworkPolicyManager";
/**
* Construct the stub at attach it to the interface.
*/
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an android.net.INetworkPolicyManager interface,
* generating a proxy if needed.
*/
public static android.net.INetworkPolicyManager asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof android.net.INetworkPolicyManager))) {
return ((android.net.INetworkPolicyManager) iin);
}
return new android.net.INetworkPolicyManager.Stub.Proxy(obj);
}
@Override
public android.os.IBinder asBinder() {
return this;
}
@Override
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_setUidPolicy: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int _arg1;
_arg1 = data.readInt();
this.setUidPolicy(_arg0, _arg1);
reply.writeNoException();
return true;
}
case TRANSACTION_getUidPolicy: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int _result = this.getUidPolicy(_arg0);
reply.writeNoException();
reply.writeInt(_result);
return true;
}
case TRANSACTION_getUidsWithPolicy: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int[] _result = this.getUidsWithPolicy(_arg0);
reply.writeNoException();
reply.writeIntArray(_result);
return true;
}
case TRANSACTION_isUidForeground: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
boolean _result = this.isUidForeground(_arg0);
reply.writeNoException();
reply.writeInt(((_result) ? (1) : (0)));
return true;
}
case TRANSACTION_registerListener: {
data.enforceInterface(DESCRIPTOR);
android.net.INetworkPolicyListener _arg0;
_arg0 = android.net.INetworkPolicyListener.Stub.asInterface(data.readStrongBinder());
this.registerListener(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_unregisterListener: {
data.enforceInterface(DESCRIPTOR);
android.net.INetworkPolicyListener _arg0;
_arg0 = android.net.INetworkPolicyListener.Stub.asInterface(data.readStrongBinder());
this.unregisterListener(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_setNetworkPolicies: {
data.enforceInterface(DESCRIPTOR);
android.net.NetworkPolicy[] _arg0;
_arg0 = data.createTypedArray(android.net.NetworkPolicy.CREATOR);
this.setNetworkPolicies(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_getNetworkPolicies: {
data.enforceInterface(DESCRIPTOR);
android.net.NetworkPolicy[] _result = this.getNetworkPolicies();
reply.writeNoException();
reply.writeTypedArray(_result, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
return true;
}
case TRANSACTION_snoozeLimit: {
data.enforceInterface(DESCRIPTOR);
android.net.NetworkTemplate _arg0;
if ((0 != data.readInt())) {
_arg0 = android.net.NetworkTemplate.CREATOR.createFromParcel(data);
} else {
_arg0 = null;
}
this.snoozeLimit(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_setRestrictBackground: {
data.enforceInterface(DESCRIPTOR);
boolean _arg0;
_arg0 = (0 != data.readInt());
this.setRestrictBackground(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_getRestrictBackground: {
data.enforceInterface(DESCRIPTOR);
boolean _result = this.getRestrictBackground();
reply.writeNoException();
reply.writeInt(((_result) ? (1) : (0)));
return true;
}
case TRANSACTION_getNetworkQuotaInfo: {
data.enforceInterface(DESCRIPTOR);
android.net.NetworkState _arg0;
if ((0 != data.readInt())) {
_arg0 = android.net.NetworkState.CREATOR.createFromParcel(data);
} else {
_arg0 = null;
}
android.net.NetworkQuotaInfo _result = this.getNetworkQuotaInfo(_arg0);
reply.writeNoException();
if ((_result != null)) {
reply.writeInt(1);
_result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
} else {
reply.writeInt(0);
}
return true;
}
case TRANSACTION_isNetworkMetered: {
data.enforceInterface(DESCRIPTOR);
android.net.NetworkState _arg0;
if ((0 != data.readInt())) {
_arg0 = android.net.NetworkState.CREATOR.createFromParcel(data);
} else {
_arg0 = null;
}
boolean _result = this.isNetworkMetered(_arg0);
reply.writeNoException();
reply.writeInt(((_result) ? (1) : (0)));
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements android.net.INetworkPolicyManager {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
@Override
public android.os.IBinder asBinder() {
return mRemote;
}
/**
* Control UID policies.
*/
@Override
public void setUidPolicy(int uid, int policy) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(uid);
_data.writeInt(policy);
mRemote.transact(Stub.TRANSACTION_setUidPolicy, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public int getUidPolicy(int uid) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(uid);
mRemote.transact(Stub.TRANSACTION_getUidPolicy, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public int[] getUidsWithPolicy(int policy) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int[] _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(policy);
mRemote.transact(Stub.TRANSACTION_getUidsWithPolicy, _data, _reply, 0);
_reply.readException();
_result = _reply.createIntArray();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public boolean isUidForeground(int uid) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
boolean _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(uid);
mRemote.transact(Stub.TRANSACTION_isUidForeground, _data, _reply, 0);
_reply.readException();
_result = (0 != _reply.readInt());
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public void registerListener(android.net.INetworkPolicyListener listener) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeStrongBinder((((listener != null)) ? (listener.asBinder()) : (null)));
mRemote.transact(Stub.TRANSACTION_registerListener, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public void unregisterListener(android.net.INetworkPolicyListener listener) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeStrongBinder((((listener != null)) ? (listener.asBinder()) : (null)));
mRemote.transact(Stub.TRANSACTION_unregisterListener, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
/**
* Control network policies atomically.
*/
@Override
public void setNetworkPolicies(android.net.NetworkPolicy[] policies) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeTypedArray(policies, 0);
mRemote.transact(Stub.TRANSACTION_setNetworkPolicies, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public android.net.NetworkPolicy[] getNetworkPolicies() throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
android.net.NetworkPolicy[] _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_getNetworkPolicies, _data, _reply, 0);
_reply.readException();
_result = _reply.createTypedArray(android.net.NetworkPolicy.CREATOR);
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
/**
* Snooze limit on policy matching given template.
*/
@Override
public void snoozeLimit(android.net.NetworkTemplate template) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
if ((template != null)) {
_data.writeInt(1);
template.writeToParcel(_data, 0);
} else {
_data.writeInt(0);
}
mRemote.transact(Stub.TRANSACTION_snoozeLimit, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
/**
* Control if background data is restricted system-wide.
*/
@Override
public void setRestrictBackground(boolean restrictBackground) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(((restrictBackground) ? (1) : (0)));
mRemote.transact(Stub.TRANSACTION_setRestrictBackground, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public boolean getRestrictBackground() throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
boolean _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_getRestrictBackground, _data, _reply, 0);
_reply.readException();
_result = (0 != _reply.readInt());
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public android.net.NetworkQuotaInfo getNetworkQuotaInfo(android.net.NetworkState state) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
android.net.NetworkQuotaInfo _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
if ((state != null)) {
_data.writeInt(1);
state.writeToParcel(_data, 0);
} else {
_data.writeInt(0);
}
mRemote.transact(Stub.TRANSACTION_getNetworkQuotaInfo, _data, _reply, 0);
_reply.readException();
if ((0 != _reply.readInt())) {
_result = android.net.NetworkQuotaInfo.CREATOR.createFromParcel(_reply);
} else {
_result = null;
}
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public boolean isNetworkMetered(android.net.NetworkState state) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
boolean _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
if ((state != null)) {
_data.writeInt(1);
state.writeToParcel(_data, 0);
} else {
_data.writeInt(0);
}
mRemote.transact(Stub.TRANSACTION_isNetworkMetered, _data, _reply, 0);
_reply.readException();
_result = (0 != _reply.readInt());
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
static final int TRANSACTION_setUidPolicy = (android.os.IBinder.FIRST_CALL_TRANSACTION);
static final int TRANSACTION_getUidPolicy = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
static final int TRANSACTION_getUidsWithPolicy = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2);
static final int TRANSACTION_isUidForeground = (android.os.IBinder.FIRST_CALL_TRANSACTION + 3);
static final int TRANSACTION_registerListener = (android.os.IBinder.FIRST_CALL_TRANSACTION + 4);
static final int TRANSACTION_unregisterListener = (android.os.IBinder.FIRST_CALL_TRANSACTION + 5);
static final int TRANSACTION_setNetworkPolicies = (android.os.IBinder.FIRST_CALL_TRANSACTION + 6);
static final int TRANSACTION_getNetworkPolicies = (android.os.IBinder.FIRST_CALL_TRANSACTION + 7);
static final int TRANSACTION_snoozeLimit = (android.os.IBinder.FIRST_CALL_TRANSACTION + 8);
static final int TRANSACTION_setRestrictBackground = (android.os.IBinder.FIRST_CALL_TRANSACTION + 9);
static final int TRANSACTION_getRestrictBackground = (android.os.IBinder.FIRST_CALL_TRANSACTION + 10);
static final int TRANSACTION_getNetworkQuotaInfo = (android.os.IBinder.FIRST_CALL_TRANSACTION + 11);
static final int TRANSACTION_isNetworkMetered = (android.os.IBinder.FIRST_CALL_TRANSACTION + 12);
}
/**
* Control UID policies.
*/
public void setUidPolicy(int uid, int policy) throws android.os.RemoteException;
public int getUidPolicy(int uid) throws android.os.RemoteException;
public int[] getUidsWithPolicy(int policy) throws android.os.RemoteException;
public boolean isUidForeground(int uid) throws android.os.RemoteException;
public void registerListener(android.net.INetworkPolicyListener listener) throws android.os.RemoteException;
public void unregisterListener(android.net.INetworkPolicyListener listener) throws android.os.RemoteException;
/**
* Control network policies atomically.
*/
public void setNetworkPolicies(android.net.NetworkPolicy[] policies) throws android.os.RemoteException;
public android.net.NetworkPolicy[] getNetworkPolicies() throws android.os.RemoteException;
/**
* Snooze limit on policy matching given template.
*/
public void snoozeLimit(android.net.NetworkTemplate template) throws android.os.RemoteException;
/**
* Control if background data is restricted system-wide.
*/
public void setRestrictBackground(boolean restrictBackground) throws android.os.RemoteException;
public boolean getRestrictBackground() throws android.os.RemoteException;
public android.net.NetworkQuotaInfo getNetworkQuotaInfo(android.net.NetworkState state) throws android.os.RemoteException;
public boolean isNetworkMetered(android.net.NetworkState state) throws android.os.RemoteException;
}
@@ -1,152 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.UnknownHostException;
/**
* Identifies an address of a network link
*
* @hide
*/
public class LinkAddress implements Parcelable {
/**
* IPv4 or IPv6 address.
*/
private final InetAddress address;
/**
* Network prefix length
*/
private final int prefixLength;
public LinkAddress(InetAddress address, int prefixLength) {
if (address == null || prefixLength < 0 ||
((address instanceof Inet4Address) && prefixLength > 32) ||
(prefixLength > 128)) {
throw new IllegalArgumentException("Bad LinkAddress haloParams " + address +
prefixLength);
}
this.address = address;
this.prefixLength = prefixLength;
}
public LinkAddress(InterfaceAddress interfaceAddress) {
this.address = interfaceAddress.getAddress();
this.prefixLength = interfaceAddress.getNetworkPrefixLength();
}
@Override
public String toString() {
return (address == null ? "" : (address.getHostAddress() + "/" + prefixLength));
}
/**
* Compares this {@code LinkAddress} instance against the specified address
* in {@code obj}. Two addresses are equal if their InetAddress and prefixLength
* are equal
*
* @param obj the object to be tested for equality.
* @return {@code true} if both objects are equal, {@code false} otherwise.
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LinkAddress)) {
return false;
}
LinkAddress linkAddress = (LinkAddress) obj;
return this.address.equals(linkAddress.address) &&
this.prefixLength == linkAddress.prefixLength;
}
@Override
/*
* generate hashcode based on significant fields
*/
public int hashCode() {
return ((null == address) ? 0 : address.hashCode()) + prefixLength;
}
/**
* Returns the InetAddress for this address.
*/
public InetAddress getAddress() {
return address;
}
/**
* Get network prefix length
*/
public int getNetworkPrefixLength() {
return prefixLength;
}
/**
* Implement the Parcelable interface
*
* @hide
*/
public int describeContents() {
return 0;
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public void writeToParcel(Parcel dest, int flags) {
if (address != null) {
dest.writeByte((byte) 1);
dest.writeByteArray(address.getAddress());
dest.writeInt(prefixLength);
} else {
dest.writeByte((byte) 0);
}
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public static final Creator<LinkAddress> CREATOR =
new Creator<LinkAddress>() {
public LinkAddress createFromParcel(Parcel in) {
InetAddress address = null;
int prefixLength = 0;
if (in.readByte() == 1) {
try {
address = InetAddress.getByAddress(in.createByteArray());
prefixLength = in.readInt();
} catch (UnknownHostException e) {
}
}
return new LinkAddress(address, prefixLength);
}
public LinkAddress[] newArray(int size) {
return new LinkAddress[size];
}
};
}
@@ -1,393 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
/**
* A class representing the capabilities of a link
*
* @hide
*/
public class LinkCapabilities implements Parcelable {
private static final String TAG = "LinkCapabilities";
private static final boolean LOCAL_LOGV = false;
/**
* The Map of Keys to Values
*/
private HashMap<Integer, String> mCapabilities;
/**
* The set of keys defined for a links capabilities.
* <p/>
* Keys starting with RW are read + write, i.e. the application
* can request for a certain requirement corresponding to that key.
* Keys starting with RO are read only, i.e. the the application
* can read the value of that key from the socket but cannot request
* a corresponding requirement.
* <p/>
* TODO: Provide a documentation technique for concisely and precisely
* define the syntax for each value string associated with a key.
*/
public static final class Key {
/**
* No constructor
*/
private Key() {
}
/**
* An integer representing the network type.
*
* @see ConnectivityManager
*/
public static final int RO_NETWORK_TYPE = 1;
/**
* Desired minimum forward link (download) bandwidth for the
* in kilobits per second (kbps). Values should be strings such
* "50", "100", "1500", etc.
*/
public static final int RW_DESIRED_FWD_BW = 2;
/**
* Required minimum forward link (download) bandwidth, in
* per second (kbps), below which the socket cannot function.
* Values should be strings such as "50", "100", "1500", etc.
*/
public static final int RW_REQUIRED_FWD_BW = 3;
/**
* Available forward link (download) bandwidth for the socket.
* This value is in kilobits per second (kbps).
* Values will be strings such as "50", "100", "1500", etc.
*/
public static final int RO_AVAILABLE_FWD_BW = 4;
/**
* Desired minimum reverse link (upload) bandwidth for the socket
* in kilobits per second (kbps).
* Values should be strings such as "50", "100", "1500", etc.
* <p/>
* This key is set via the needs map.
*/
public static final int RW_DESIRED_REV_BW = 5;
/**
* Required minimum reverse link (upload) bandwidth, in kilobits
* per second (kbps), below which the socket cannot function.
* If a rate is not specified, the default rate of kbps will be
* Values should be strings such as "50", "100", "1500", etc.
*/
public static final int RW_REQUIRED_REV_BW = 6;
/**
* Available reverse link (upload) bandwidth for the socket.
* This value is in kilobits per second (kbps).
* Values will be strings such as "50", "100", "1500", etc.
*/
public static final int RO_AVAILABLE_REV_BW = 7;
/**
* Maximum latency for the socket, in milliseconds, above which
* socket cannot function.
* Values should be strings such as "50", "300", "500", etc.
*/
public static final int RW_MAX_ALLOWED_LATENCY = 8;
/**
* Interface that the socket is bound to. This can be a virtual
* interface (e.g. VPN or Mobile IP) or a physical interface
* (e.g. wlan0 or rmnet0).
* Values will be strings such as "wlan0", "rmnet0"
*/
public static final int RO_BOUND_INTERFACE = 9;
/**
* Physical interface that the socket is routed on.
* This can be different from BOUND_INTERFACE in cases such as
* VPN or Mobile IP. The physical interface may change over time
* if seamless mobility is supported.
* Values will be strings such as "wlan0", "rmnet0"
*/
public static final int RO_PHYSICAL_INTERFACE = 10;
}
/**
* Role informs the LinkSocket about the data usage patterns of your
* application.
* <p/>
* {@code Role.DEFAULT} is the default role, and is used whenever
* a role isn't set.
*/
public static final class Role {
/**
* No constructor
*/
private Role() {
}
// examples only, discuss which roles should be defined, and then
// code these to match
/**
* Default Role
*/
public static final String DEFAULT = "default";
/**
* Bulk down load
*/
public static final String BULK_DOWNLOAD = "bulk.download";
/**
* Bulk upload
*/
public static final String BULK_UPLOAD = "bulk.upload";
/**
* VoIP Application at 24kbps
*/
public static final String VOIP_24KBPS = "voip.24k";
/**
* VoIP Application at 32kbps
*/
public static final String VOIP_32KBPS = "voip.32k";
/**
* Video Streaming at 480p
*/
public static final String VIDEO_STREAMING_480P = "video.streaming.480p";
/**
* Video Streaming at 720p
*/
public static final String VIDEO_STREAMING_720I = "video.streaming.720i";
/**
* Video Chat Application at 360p
*/
public static final String VIDEO_CHAT_360P = "video.chat.360p";
/**
* Video Chat Application at 480p
*/
public static final String VIDEO_CHAT_480P = "video.chat.480i";
}
/**
* Constructor
*/
public LinkCapabilities() {
mCapabilities = new HashMap<>();
}
/**
* Copy constructor.
*
* @param source
*/
public LinkCapabilities(LinkCapabilities source) {
if (source != null) {
mCapabilities = new HashMap<>(source.mCapabilities);
} else {
mCapabilities = new HashMap<>();
}
}
/**
* Create the {@code LinkCapabilities} with values depending on role type.
*
* @param applicationRole a {@code LinkSocket.Role}
* @return the {@code LinkCapabilities} associated with the applicationRole, empty if none
*/
public static LinkCapabilities createNeedsMap(String applicationRole) {
log("createNeededCapabilities(applicationRole) EX");
return new LinkCapabilities();
}
/**
* Remove all capabilities
*/
public void clear() {
mCapabilities.clear();
}
/**
* Returns whether this map is empty.
*/
public boolean isEmpty() {
return mCapabilities.isEmpty();
}
/**
* Returns the number of elements in this map.
*
* @return the number of elements in this map.
*/
public int size() {
return mCapabilities.size();
}
/**
* Given the key return the capability string
*
* @param key
* @return the capability string
*/
public String get(int key) {
return mCapabilities.get(key);
}
/**
* Store the key/value capability pair
*
* @param key
* @param value
*/
public void put(int key, String value) {
mCapabilities.put(key, value);
}
/**
* Returns whether this map contains the specified key.
*
* @param key to search for.
* @return {@code true} if this map contains the specified key,
* {@code false} otherwise.
*/
public boolean containsKey(int key) {
return mCapabilities.containsKey(key);
}
/**
* Returns whether this map contains the specified value.
*
* @param value to search for.
* @return {@code true} if this map contains the specified value,
* {@code false} otherwise.
*/
public boolean containsValue(String value) {
return mCapabilities.containsValue(value);
}
/**
* Returns a set containing all of the mappings in this map. Each mapping is
* an instance of {@link java.util.Map.Entry}. As the set is backed by this map,
* changes in one will be reflected in the other.
*
* @return a set of the mappings.
*/
public Set<Entry<Integer, String>> entrySet() {
return mCapabilities.entrySet();
}
/**
* @return the set of the keys.
*/
public Set<Integer> keySet() {
return mCapabilities.keySet();
}
/**
* @return the set of values
*/
public Collection<String> values() {
return mCapabilities.values();
}
/**
* Implement the Parcelable interface
*
* @hide
*/
public int describeContents() {
return 0;
}
/**
* Convert to string for debugging
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
boolean firstTime = true;
for (Entry<Integer, String> entry : mCapabilities.entrySet()) {
if (firstTime) {
firstTime = false;
} else {
sb.append(",");
}
sb.append(entry.getKey());
sb.append(":\"");
sb.append(entry.getValue());
sb.append("\"");
return mCapabilities.toString();
}
return sb.toString();
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mCapabilities.size());
for (Entry<Integer, String> entry : mCapabilities.entrySet()) {
dest.writeInt(entry.getKey());
dest.writeString(entry.getValue());
}
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public static final Creator<LinkCapabilities> CREATOR =
new Creator<LinkCapabilities>() {
public LinkCapabilities createFromParcel(Parcel in) {
LinkCapabilities capabilities = new LinkCapabilities();
int size = in.readInt();
while (size-- != 0) {
int key = in.readInt();
String value = in.readString();
capabilities.mCapabilities.put(key, value);
}
return capabilities;
}
public LinkCapabilities[] newArray(int size) {
return new LinkCapabilities[size];
}
};
/**
* Debug logging
*/
protected static void log(String s) {
if (LOCAL_LOGV) Log.v(TAG, s);
}
}
@@ -1,438 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* Describes the properties of a network link.
* <p/>
* A link represents a connection to a network.
* It may have multiple addresses and multiple gateways,
* multiple dns servers but only one http proxy.
* <p/>
* Because it's a single network, the dns's
* are interchangeable and don't need associating with
* particular addresses. The gateways similarly don't
* need associating with particular addresses.
* <p/>
* A dual stack interface works fine in this model:
* each address has it's own prefix length to describe
* the local network. The dns servers all return
* both v4 addresses and v6 addresses regardless of the
* address family of the server itself (rfc4213) and we
* don't care which is used. The gateways will be
* selected based on the destination address and the
* source address has no relavence.
*
* @hide
*/
public class LinkProperties implements Parcelable {
String mIfaceName;
private Collection<LinkAddress> mLinkAddresses = new ArrayList<>();
private Collection<InetAddress> mDnses = new ArrayList<>();
private Collection<RouteInfo> mRoutes = new ArrayList<>();
private ProxyProperties mHttpProxy;
public static class CompareResult<T> {
public Collection<T> removed = new ArrayList<>();
public Collection<T> added = new ArrayList<>();
@Override
public String toString() {
String retVal = "removed=[";
for (T addr : removed) retVal += addr.toString() + ",";
retVal += "] added=[";
for (T addr : added) retVal += addr.toString() + ",";
retVal += "]";
return retVal;
}
}
public LinkProperties() {
clear();
}
// copy constructor instead of clone
public LinkProperties(LinkProperties source) {
if (source != null) {
mIfaceName = source.getInterfaceName();
for (LinkAddress l : source.getLinkAddresses()) mLinkAddresses.add(l);
for (InetAddress i : source.getDnses()) mDnses.add(i);
for (RouteInfo r : source.getRoutes()) mRoutes.add(r);
mHttpProxy = (source.getHttpProxy() == null) ?
null : new ProxyProperties(source.getHttpProxy());
}
}
public void setInterfaceName(String iface) {
mIfaceName = iface;
}
public String getInterfaceName() {
return mIfaceName;
}
public Collection<InetAddress> getAddresses() {
Collection<InetAddress> addresses = new ArrayList<>();
for (LinkAddress linkAddress : mLinkAddresses) {
addresses.add(linkAddress.getAddress());
}
return Collections.unmodifiableCollection(addresses);
}
public void addLinkAddress(LinkAddress address) {
if (address != null) mLinkAddresses.add(address);
}
public Collection<LinkAddress> getLinkAddresses() {
return Collections.unmodifiableCollection(mLinkAddresses);
}
public void addDns(InetAddress dns) {
if (dns != null) mDnses.add(dns);
}
public Collection<InetAddress> getDnses() {
return Collections.unmodifiableCollection(mDnses);
}
public void addRoute(RouteInfo route) {
if (route != null) mRoutes.add(route);
}
public Collection<RouteInfo> getRoutes() {
return Collections.unmodifiableCollection(mRoutes);
}
public void setHttpProxy(ProxyProperties proxy) {
mHttpProxy = proxy;
}
public ProxyProperties getHttpProxy() {
return mHttpProxy;
}
public void clear() {
mIfaceName = null;
mLinkAddresses.clear();
mDnses.clear();
mRoutes.clear();
mHttpProxy = null;
}
/**
* Implement the Parcelable interface
*
* @hide
*/
public int describeContents() {
return 0;
}
@Override
public String toString() {
String ifaceName = (mIfaceName == null ? "" : "InterfaceName: " + mIfaceName + " ");
String linkAddresses = "LinkAddresses: [";
for (LinkAddress addr : mLinkAddresses) linkAddresses += addr.toString() + ",";
linkAddresses += "] ";
String dns = "DnsAddresses: [";
for (InetAddress addr : mDnses) dns += addr.getHostAddress() + ",";
dns += "] ";
String routes = "Routes: [";
for (RouteInfo route : mRoutes) routes += route.toString() + ",";
routes += "] ";
String proxy = (mHttpProxy == null ? "" : "HttpProxy: " + mHttpProxy.toString() + " ");
return ifaceName + linkAddresses + routes + dns + proxy;
}
/**
* Compares this {@code LinkProperties} interface name against the target
*
* @param target LinkProperties to compare.
* @return {@code true} if both are identical, {@code false} otherwise.
*/
public boolean isIdenticalInterfaceName(LinkProperties target) {
return TextUtils.equals(getInterfaceName(), target.getInterfaceName());
}
/**
* Compares this {@code LinkProperties} interface name against the target
*
* @param target LinkProperties to compare.
* @return {@code true} if both are identical, {@code false} otherwise.
*/
public boolean isIdenticalAddresses(LinkProperties target) {
Collection<InetAddress> targetAddresses = target.getAddresses();
Collection<InetAddress> sourceAddresses = getAddresses();
return (sourceAddresses.size() == targetAddresses.size()) && sourceAddresses.containsAll(targetAddresses);
}
/**
* Compares this {@code LinkProperties} DNS addresses against the target
*
* @param target LinkProperties to compare.
* @return {@code true} if both are identical, {@code false} otherwise.
*/
public boolean isIdenticalDnses(LinkProperties target) {
Collection<InetAddress> targetDnses = target.getDnses();
return (mDnses.size() == targetDnses.size()) && mDnses.containsAll(targetDnses);
}
/**
* Compares this {@code LinkProperties} Routes against the target
*
* @param target LinkProperties to compare.
* @return {@code true} if both are identical, {@code false} otherwise.
*/
public boolean isIdenticalRoutes(LinkProperties target) {
Collection<RouteInfo> targetRoutes = target.getRoutes();
return (mRoutes.size() == targetRoutes.size()) && mRoutes.containsAll(targetRoutes);
}
/**
* Compares this {@code LinkProperties} HttpProxy against the target
*
* @param target LinkProperties to compare.
* @return {@code true} if both are identical, {@code false} otherwise.
*/
public boolean isIdenticalHttpProxy(LinkProperties target) {
return getHttpProxy() == null ? target.getHttpProxy() == null :
getHttpProxy().equals(target.getHttpProxy());
}
@Override
/**
* Compares this {@code LinkProperties} instance against the target
* LinkProperties in {@code obj}. Two LinkPropertieses are equal if
* all their fields are equal in values.
*
* For collection fields, such as mDnses, containsAll() is used to check
* if two collections contains the same elements, independent of order.
* There are two thoughts regarding containsAll()
* 1. Duplicated elements. eg, (A, B, B) and (A, A, B) are equal.
* 2. Worst case performance is O(n^2).
*
* @param obj the object to be tested for equality.
* @return {@code true} if both objects are equal, {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof LinkProperties)) return false;
LinkProperties target = (LinkProperties) obj;
return isIdenticalInterfaceName(target) &&
isIdenticalAddresses(target) &&
isIdenticalDnses(target) &&
isIdenticalRoutes(target) &&
isIdenticalHttpProxy(target);
}
/**
* Return two lists, a list of addresses that would be removed from
* mLinkAddresses and a list of addresses that would be added to
* mLinkAddress which would then result in target and mLinkAddresses
* being the same list.
*
* @param target is a LinkProperties with the new list of addresses
* @return the removed and added lists.
*/
public CompareResult<LinkAddress> compareAddresses(LinkProperties target) {
/*
* Duplicate the LinkAddresses into removed, we will be removing
* address which are common between mLinkAddresses and target
* leaving the addresses that are different. And address which
* are in target but not in mLinkAddresses are placed in the
* addedAddresses.
*/
CompareResult<LinkAddress> result = new CompareResult<>();
result.removed = new ArrayList<>(mLinkAddresses);
result.added.clear();
if (target != null) {
for (LinkAddress newAddress : target.getLinkAddresses()) {
if (!result.removed.remove(newAddress)) {
result.added.add(newAddress);
}
}
}
return result;
}
/**
* Return two lists, a list of dns addresses that would be removed from
* mDnses and a list of addresses that would be added to
* mDnses which would then result in target and mDnses
* being the same list.
*
* @param target is a LinkProperties with the new list of dns addresses
* @return the removed and added lists.
*/
public CompareResult<InetAddress> compareDnses(LinkProperties target) {
/*
* Duplicate the InetAddresses into removed, we will be removing
* dns address which are common between mDnses and target
* leaving the addresses that are different. And dns address which
* are in target but not in mDnses are placed in the
* addedAddresses.
*/
CompareResult<InetAddress> result = new CompareResult<>();
result.removed = new ArrayList<>(mDnses);
result.added.clear();
if (target != null) {
for (InetAddress newAddress : target.getDnses()) {
if (!result.removed.remove(newAddress)) {
result.added.add(newAddress);
}
}
}
return result;
}
/**
* Return two lists, a list of routes that would be removed from
* mRoutes and a list of routes that would be added to
* mRoutes which would then result in target and mRoutes
* being the same list.
*
* @param target is a LinkProperties with the new list of routes
* @return the removed and added lists.
*/
public CompareResult<RouteInfo> compareRoutes(LinkProperties target) {
/*
* Duplicate the RouteInfos into removed, we will be removing
* routes which are common between mDnses and target
* leaving the routes that are different. And route address which
* are in target but not in mRoutes are placed in added.
*/
CompareResult<RouteInfo> result = new CompareResult<>();
result.removed = new ArrayList<>(mRoutes);
result.added.clear();
if (target != null) {
for (RouteInfo r : target.getRoutes()) {
if (!result.removed.remove(r)) {
result.added.add(r);
}
}
}
return result;
}
@Override
/**
* generate hashcode based on significant fields
* Equal objects must produce the same hash code, while unequal objects
* may have the same hash codes.
*/
public int hashCode() {
return ((null == mIfaceName) ? 0 : mIfaceName.hashCode()
+ mLinkAddresses.size() * 31
+ mDnses.size() * 37
+ mRoutes.size() * 41
+ ((null == mHttpProxy) ? 0 : mHttpProxy.hashCode()));
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getInterfaceName());
dest.writeInt(mLinkAddresses.size());
for (LinkAddress linkAddress : mLinkAddresses) {
dest.writeParcelable(linkAddress, flags);
}
dest.writeInt(mDnses.size());
for (InetAddress d : mDnses) {
dest.writeByteArray(d.getAddress());
}
dest.writeInt(mRoutes.size());
for (RouteInfo route : mRoutes) {
dest.writeParcelable(route, flags);
}
if (mHttpProxy != null) {
dest.writeByte((byte) 1);
dest.writeParcelable(mHttpProxy, flags);
} else {
dest.writeByte((byte) 0);
}
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public static final Creator<LinkProperties> CREATOR =
new Creator<LinkProperties>() {
public LinkProperties createFromParcel(Parcel in) {
LinkProperties netProp = new LinkProperties();
String iface = in.readString();
if (iface != null) {
try {
netProp.setInterfaceName(iface);
} catch (Exception e) {
return null;
}
}
int addressCount = in.readInt();
for (int i = 0; i < addressCount; i++) {
netProp.addLinkAddress((LinkAddress) in.readParcelable(null));
}
addressCount = in.readInt();
for (int i = 0; i < addressCount; i++) {
try {
netProp.addDns(InetAddress.getByAddress(in.createByteArray()));
} catch (UnknownHostException e) {
}
}
addressCount = in.readInt();
for (int i = 0; i < addressCount; i++) {
netProp.addRoute((RouteInfo) in.readParcelable(null));
}
if (in.readByte() == 1) {
netProp.setHttpProxy((ProxyProperties) in.readParcelable(null));
}
return netProp;
}
public LinkProperties[] newArray(int size) {
return new LinkProperties[size];
}
};
}
@@ -1,229 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import com.android.internal.util.Objects;
import static android.net.ConnectivityManager.TYPE_WIFI;
/**
* Network definition that includes strong identity. Analogous to combining
* {@link NetworkInfo} and an IMSI.
*
* @hide
*/
public class NetworkIdentity {
/**
* When enabled, combine all {@link #mSubType} together under
* {@link #SUBTYPE_COMBINED}.
*/
public static final boolean COMBINE_SUBTYPE_ENABLED = true;
public static final int SUBTYPE_COMBINED = -1;
final int mType;
final int mSubType;
final String mSubscriberId;
final String mNetworkId;
final boolean mRoaming;
public NetworkIdentity(
int type, int subType, String subscriberId, String networkId, boolean roaming) {
mType = type;
mSubType = COMBINE_SUBTYPE_ENABLED ? SUBTYPE_COMBINED : subType;
mSubscriberId = subscriberId;
mNetworkId = networkId;
mRoaming = roaming;
}
/**
* {@hide}
*/
public static String getNetworkTypeName(int type) {
switch (type) {
case 0:
return "MOBILE";
case TYPE_WIFI:
return "WIFI";
case 2:
return "MOBILE_MMS";
case 3:
return "MOBILE_SUPL";
case 4:
return "MOBILE_DUN";
case 5:
return "MOBILE_HIPRI";
case 6:
return "WIMAX";
case 7:
return "BLUETOOTH";
case 8:
return "DUMMY";
case 9:
return "ETHERNET";
case 10:
return "MOBILE_FOTA";
case 11:
return "MOBILE_IMS";
case 12:
return "MOBILE_CBS";
case 13:
return "WIFI_P2P";
default:
return Integer.toString(type);
}
}
/**
* {@hide}
*/
public static boolean isNetworkTypeMobile(int networkType) {
switch (networkType) {
case 0:
case 2:
case 3:
case 4:
case 5:
case 10:
case 11:
case 12:
return true;
default:
return false;
}
}
@Override
public int hashCode() {
return Objects.hashCode(mType, mSubType, mSubscriberId, mNetworkId, mRoaming);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof NetworkIdentity) {
final NetworkIdentity ident = (NetworkIdentity) obj;
return mType == ident.mType && mSubType == ident.mSubType && mRoaming == ident.mRoaming
&& Objects.equal(mSubscriberId, ident.mSubscriberId)
&& Objects.equal(mNetworkId, ident.mNetworkId);
}
return false;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder("[");
builder.append("type=").append(getNetworkTypeName(mType));
builder.append(", subType=");
if (COMBINE_SUBTYPE_ENABLED) {
builder.append("COMBINED");
} else if (isNetworkTypeMobile(mType)) {
builder.append(getNetworkTypeName(mSubType));
} else {
builder.append(mSubType);
}
if (mSubscriberId != null) {
builder.append(", subscriberId=").append(scrubSubscriberId(mSubscriberId));
}
if (mNetworkId != null) {
builder.append(", networkId=").append(mNetworkId);
}
if (mRoaming) {
builder.append(", ROAMING");
}
return builder.append("]").toString();
}
public int getType() {
return mType;
}
public int getSubType() {
return mSubType;
}
public String getSubscriberId() {
return mSubscriberId;
}
public String getNetworkId() {
return mNetworkId;
}
public boolean getRoaming() {
return mRoaming;
}
/**
* Scrub given IMSI on production builds.
*/
public static String scrubSubscriberId(String subscriberId) {
if ("eng".equals(Build.TYPE)) {
return subscriberId;
} else if (subscriberId != null) {
// TODO: parse this as MCC+MNC instead of hard-coding
return subscriberId.substring(0, Math.min(6, subscriberId.length())) + "...";
} else {
return "null";
}
}
/**
* Build a {@link android.net.NetworkIdentity} from the given {@link NetworkState},
* assuming that any mobile networks are using the current IMSI.
*/
public static NetworkIdentity buildNetworkIdentity(Context context, NetworkState state) {
final int type = state.networkInfo.getType();
final int subType = state.networkInfo.getSubtype();
// TODO: consider moving subscriberId over to LinkCapabilities, so it
// comes from an authoritative source.
String subscriberId = null;
String networkId = null;
boolean roaming = false;
if (isNetworkTypeMobile(type)) {
final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
roaming = telephony.isNetworkRoaming();
if (state.subscriberId != null) {
subscriberId = state.subscriberId;
} else {
subscriberId = telephony.getSubscriberId();
}
} else if (type == TYPE_WIFI) {
if (state.networkId != null) {
networkId = state.networkId;
} else {
final WifiManager wifi = (WifiManager) context.getSystemService(
Context.WIFI_SERVICE);
final WifiInfo info = wifi.getConnectionInfo();
networkId = info != null ? info.getSSID() : null;
}
}
return new NetworkIdentity(type, subType, subscriberId, networkId, roaming);
}
}
@@ -1,185 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import com.android.internal.util.Objects;
import static com.android.internal.util.Preconditions.checkNotNull;
/**
* Policy for networks matching a {@link NetworkTemplate}, including usage cycle
* and limits to be enforced.
*
* @hide
*/
public class NetworkPolicy implements Parcelable, Comparable<NetworkPolicy> {
public static final int CYCLE_NONE = -1;
public static final long WARNING_DISABLED = -1;
public static final long LIMIT_DISABLED = -1;
public static final long SNOOZE_NEVER = -1;
public final NetworkTemplate template;
public int cycleDay;
public String cycleTimezone;
public long warningBytes;
public long limitBytes;
public long lastWarningSnooze;
public long lastLimitSnooze;
public boolean metered;
public boolean inferred;
private static final long DEFAULT_MTU = 1500;
@Deprecated
public NetworkPolicy(NetworkTemplate template, int cycleDay, String cycleTimezone,
long warningBytes, long limitBytes, boolean metered) {
this(template, cycleDay, cycleTimezone, warningBytes, limitBytes, SNOOZE_NEVER,
SNOOZE_NEVER, metered, false);
}
public NetworkPolicy(NetworkTemplate template, int cycleDay, String cycleTimezone,
long warningBytes, long limitBytes, long lastWarningSnooze, long lastLimitSnooze,
boolean metered, boolean inferred) {
this.template = checkNotNull(template, "missing NetworkTemplate");
this.cycleDay = cycleDay;
this.cycleTimezone = checkNotNull(cycleTimezone, "missing cycleTimezone");
this.warningBytes = warningBytes;
this.limitBytes = limitBytes;
this.lastWarningSnooze = lastWarningSnooze;
this.lastLimitSnooze = lastLimitSnooze;
this.metered = metered;
this.inferred = inferred;
}
public NetworkPolicy(Parcel in) {
template = in.readParcelable(null);
cycleDay = in.readInt();
cycleTimezone = in.readString();
warningBytes = in.readLong();
limitBytes = in.readLong();
lastWarningSnooze = in.readLong();
lastLimitSnooze = in.readLong();
metered = in.readInt() != 0;
inferred = in.readInt() != 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(template, flags);
dest.writeInt(cycleDay);
dest.writeString(cycleTimezone);
dest.writeLong(warningBytes);
dest.writeLong(limitBytes);
dest.writeLong(lastWarningSnooze);
dest.writeLong(lastLimitSnooze);
dest.writeInt(metered ? 1 : 0);
dest.writeInt(inferred ? 1 : 0);
}
@Override
public int describeContents() {
return 0;
}
/**
* Test if given measurement is over {@link #warningBytes}.
*/
public boolean isOverWarning(long totalBytes) {
return warningBytes != WARNING_DISABLED && totalBytes >= warningBytes;
}
/**
* Test if given measurement is near enough to {@link #limitBytes} to be
* considered over-limit.
*/
public boolean isOverLimit(long totalBytes) {
// over-estimate, since kernel will trigger limit once first packet
// trips over limit.
totalBytes += 2 * DEFAULT_MTU;
return limitBytes != LIMIT_DISABLED && totalBytes >= limitBytes;
}
/**
* Clear any existing snooze values, setting to {@link #SNOOZE_NEVER}.
*/
public void clearSnooze() {
lastWarningSnooze = SNOOZE_NEVER;
lastLimitSnooze = SNOOZE_NEVER;
}
/**
* Test if this policy has a cycle defined, after which usage should reset.
*/
public boolean hasCycle() {
return cycleDay != CYCLE_NONE;
}
@Override
public int compareTo(NetworkPolicy another) {
if (another == null || another.limitBytes == LIMIT_DISABLED) {
// other value is missing or disabled; we win
return -1;
}
if (limitBytes == LIMIT_DISABLED || another.limitBytes < limitBytes) {
// we're disabled or other limit is smaller; they win
return 1;
}
return 0;
}
@Override
public int hashCode() {
return Objects.hashCode(template, cycleDay, cycleTimezone, warningBytes, limitBytes,
lastWarningSnooze, lastLimitSnooze, metered, inferred);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof NetworkPolicy) {
final NetworkPolicy other = (NetworkPolicy) obj;
return cycleDay == other.cycleDay && warningBytes == other.warningBytes
&& limitBytes == other.limitBytes
&& lastWarningSnooze == other.lastWarningSnooze
&& lastLimitSnooze == other.lastLimitSnooze && metered == other.metered
&& inferred == other.inferred
&& Objects.equal(cycleTimezone, other.cycleTimezone)
&& Objects.equal(template, other.template);
}
return false;
}
@Override
public String toString() {
return "NetworkPolicy" + "[" + template + "]:" + " cycleDay=" + cycleDay + ", cycleTimezone=" + cycleTimezone + ", warningBytes=" + warningBytes + ", limitBytes=" + limitBytes + ", lastWarningSnooze=" + lastWarningSnooze + ", lastLimitSnooze=" + lastLimitSnooze + ", metered=" + metered + ", inferred=" + inferred;
}
public static final Creator<NetworkPolicy> CREATOR = new Creator<NetworkPolicy>() {
@Override
public NetworkPolicy createFromParcel(Parcel in) {
return new NetworkPolicy(in);
}
@Override
public NetworkPolicy[] newArray(int size) {
return new NetworkPolicy[size];
}
};
}
@@ -1,299 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.RemoteException;
import android.text.format.Time;
import com.google.android.collect.Sets;
import java.io.PrintWriter;
import java.util.HashSet;
import static android.content.pm.PackageManager.GET_SIGNATURES;
import static android.net.NetworkPolicy.CYCLE_NONE;
import static android.text.format.Time.MONTH_DAY;
/**
* Manager for creating and modifying network policy rules.
* <p/>
* {@hide}
*/
public class NetworkPolicyManager {
/**
* No specific network policy, use system default.
*/
public static final int POLICY_NONE = 0x0;
/**
* Reject network usage on metered networks when application in background.
*/
public static final int POLICY_REJECT_METERED_BACKGROUND = 0x1;
/**
* All network traffic should be allowed.
*/
public static final int RULE_ALLOW_ALL = 0x0;
/**
* Reject traffic on metered networks.
*/
public static final int RULE_REJECT_METERED = 0x1;
private static final boolean ALLOW_PLATFORM_APP_POLICY = true;
/**
* {@link Intent} extra that indicates which {@link NetworkTemplate} rule it
* applies to.
*/
public static final String EXTRA_NETWORK_TEMPLATE = "android.net.NETWORK_TEMPLATE";
private INetworkPolicyManager mService;
public NetworkPolicyManager(INetworkPolicyManager service) {
if (service == null) {
throw new IllegalArgumentException("missing INetworkPolicyManager");
}
mService = service;
}
public static NetworkPolicyManager from(Context context) {
return (NetworkPolicyManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
/**
* Set policy flags for specific UID.
*
* @param policy {@link #POLICY_NONE} or combination of flags like
* {@link #POLICY_REJECT_METERED_BACKGROUND}.
*/
public void setUidPolicy(int uid, int policy) {
try {
mService.setUidPolicy(uid, policy);
} catch (RemoteException e) {
}
}
public int getUidPolicy(int uid) {
try {
return mService.getUidPolicy(uid);
} catch (RemoteException e) {
return POLICY_NONE;
}
}
public int[] getUidsWithPolicy(int policy) {
try {
return mService.getUidsWithPolicy(policy);
} catch (RemoteException e) {
return new int[0];
}
}
public void registerListener(INetworkPolicyListener listener) {
try {
mService.registerListener(listener);
} catch (RemoteException e) {
}
}
public void unregisterListener(INetworkPolicyListener listener) {
try {
mService.unregisterListener(listener);
} catch (RemoteException e) {
}
}
public void setNetworkPolicies(NetworkPolicy[] policies) {
try {
mService.setNetworkPolicies(policies);
} catch (RemoteException e) {
}
}
public NetworkPolicy[] getNetworkPolicies() {
try {
return mService.getNetworkPolicies();
} catch (RemoteException e) {
return null;
}
}
public void setRestrictBackground(boolean restrictBackground) {
try {
mService.setRestrictBackground(restrictBackground);
} catch (RemoteException e) {
}
}
public boolean getRestrictBackground() {
try {
return mService.getRestrictBackground();
} catch (RemoteException e) {
return false;
}
}
/**
* Compute the last cycle boundary for the given {@link NetworkPolicy}. For
* example, if cycle day is 20th, and today is June 15th, it will return May
* 20th. When cycle day doesn't exist in current month, it snaps to the 1st
* of following month.
*
* @hide
*/
public static long computeLastCycleBoundary(long currentTime, NetworkPolicy policy) {
if (policy.cycleDay == CYCLE_NONE) {
throw new IllegalArgumentException("Unable to compute boundary without cycleDay");
}
final Time now = new Time(policy.cycleTimezone);
now.set(currentTime);
// first, find cycle boundary for current month
final Time cycle = new Time(now);
cycle.hour = cycle.minute = cycle.second = 0;
snapToCycleDay(cycle, policy.cycleDay);
if (Time.compare(cycle, now) >= 0) {
// cycle boundary is beyond now, use last cycle boundary; start by
// pushing ourselves squarely into last month.
final Time lastMonth = new Time(now);
lastMonth.hour = lastMonth.minute = lastMonth.second = 0;
lastMonth.monthDay = 1;
lastMonth.month -= 1;
lastMonth.normalize(true);
cycle.set(lastMonth);
snapToCycleDay(cycle, policy.cycleDay);
}
return cycle.toMillis(true);
}
/**
* {@hide}
*/
public static long computeNextCycleBoundary(long currentTime, NetworkPolicy policy) {
if (policy.cycleDay == CYCLE_NONE) {
throw new IllegalArgumentException("Unable to compute boundary without cycleDay");
}
final Time now = new Time(policy.cycleTimezone);
now.set(currentTime);
// first, find cycle boundary for current month
final Time cycle = new Time(now);
cycle.hour = cycle.minute = cycle.second = 0;
snapToCycleDay(cycle, policy.cycleDay);
if (Time.compare(cycle, now) <= 0) {
// cycle boundary is before now, use next cycle boundary; start by
// pushing ourselves squarely into next month.
final Time nextMonth = new Time(now);
nextMonth.hour = nextMonth.minute = nextMonth.second = 0;
nextMonth.monthDay = 1;
nextMonth.month += 1;
nextMonth.normalize(true);
cycle.set(nextMonth);
snapToCycleDay(cycle, policy.cycleDay);
}
return cycle.toMillis(true);
}
/**
* Snap to the cycle day for the current month given; when cycle day doesn't
* exist, it snaps to last second of current month.
*
* @hide
*/
public static void snapToCycleDay(Time time, int cycleDay) {
if (cycleDay > time.getActualMaximum(MONTH_DAY)) {
// cycle day isn't valid this month; snap to last second of month
time.month += 1;
time.monthDay = 1;
time.second = -1;
} else {
time.monthDay = cycleDay;
}
time.normalize(true);
}
/**
* Check if given UID can have a {@link #setUidPolicy(int, int)} defined,
* usually to protect critical system services.
*/
@Deprecated
public static boolean isUidValidForPolicy(Context context, int uid) {
if (!ALLOW_PLATFORM_APP_POLICY) {
final PackageManager pm = context.getPackageManager();
final HashSet<Signature> systemSignature;
try {
systemSignature = Sets.newHashSet(
pm.getPackageInfo("android", GET_SIGNATURES).signatures);
} catch (NameNotFoundException e) {
throw new RuntimeException("problem finding system signature", e);
}
try {
// reject apps signed with platform cert
for (String packageName : pm.getPackagesForUid(uid)) {
final HashSet<Signature> packageSignature = Sets.newHashSet(
pm.getPackageInfo(packageName, GET_SIGNATURES).signatures);
if (packageSignature.containsAll(systemSignature)) {
return false;
}
}
} catch (NameNotFoundException e) {
}
}
// nothing found above; we can apply policy to UID
return true;
}
/**
* {@hide}
*/
public static void dumpPolicy(PrintWriter fout, int policy) {
fout.write("[");
if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
fout.write("REJECT_METERED_BACKGROUND");
}
fout.write("]");
}
/**
* {@hide}
*/
public static void dumpRules(PrintWriter fout, int rules) {
fout.write("[");
if ((rules & RULE_REJECT_METERED) != 0) {
fout.write("REJECT_METERED");
}
fout.write("]");
}
}
@@ -1,87 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Information about quota status on a specific network.
*
* @hide
*/
public class NetworkQuotaInfo implements Parcelable {
private final long mEstimatedBytes;
private final long mSoftLimitBytes;
private final long mHardLimitBytes;
public static final long NO_LIMIT = -1;
/**
* {@hide}
*/
public NetworkQuotaInfo(long estimatedBytes, long softLimitBytes, long hardLimitBytes) {
mEstimatedBytes = estimatedBytes;
mSoftLimitBytes = softLimitBytes;
mHardLimitBytes = hardLimitBytes;
}
/**
* {@hide}
*/
public NetworkQuotaInfo(Parcel in) {
mEstimatedBytes = in.readLong();
mSoftLimitBytes = in.readLong();
mHardLimitBytes = in.readLong();
}
public long getEstimatedBytes() {
return mEstimatedBytes;
}
public long getSoftLimitBytes() {
return mSoftLimitBytes;
}
public long getHardLimitBytes() {
return mHardLimitBytes;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeLong(mEstimatedBytes);
out.writeLong(mSoftLimitBytes);
out.writeLong(mHardLimitBytes);
}
public static final Creator<NetworkQuotaInfo> CREATOR = new Creator<NetworkQuotaInfo>() {
@Override
public NetworkQuotaInfo createFromParcel(Parcel in) {
return new NetworkQuotaInfo(in);
}
@Override
public NetworkQuotaInfo[] newArray(int size) {
return new NetworkQuotaInfo[size];
}
};
}
@@ -1,86 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Snapshot of network state.
*
* @hide
*/
public class NetworkState implements Parcelable {
public final NetworkInfo networkInfo;
public final LinkProperties linkProperties;
public final LinkCapabilities linkCapabilities;
/**
* Currently only used by testing.
*/
public final String subscriberId;
public final String networkId;
public NetworkState(NetworkInfo networkInfo, LinkProperties linkProperties,
LinkCapabilities linkCapabilities) {
this(networkInfo, linkProperties, linkCapabilities, null, null);
}
public NetworkState(NetworkInfo networkInfo, LinkProperties linkProperties,
LinkCapabilities linkCapabilities, String subscriberId, String networkId) {
this.networkInfo = networkInfo;
this.linkProperties = linkProperties;
this.linkCapabilities = linkCapabilities;
this.subscriberId = subscriberId;
this.networkId = networkId;
}
public NetworkState(Parcel in) {
networkInfo = in.readParcelable(null);
linkProperties = in.readParcelable(null);
linkCapabilities = in.readParcelable(null);
subscriberId = in.readString();
networkId = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeParcelable(networkInfo, flags);
out.writeParcelable(linkProperties, flags);
out.writeParcelable(linkCapabilities, flags);
out.writeString(subscriberId);
out.writeString(networkId);
}
public static final Creator<NetworkState> CREATOR = new Creator<NetworkState>() {
@Override
public NetworkState createFromParcel(Parcel in) {
return new NetworkState(in);
}
@Override
public NetworkState[] newArray(int size) {
return new NetworkState[size];
}
};
}
@@ -1,445 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.Objects;
import static android.net.ConnectivityManager.TYPE_ETHERNET;
import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.net.ConnectivityManager.TYPE_WIMAX;
import static android.net.NetworkIdentity.COMBINE_SUBTYPE_ENABLED;
import static android.net.NetworkIdentity.scrubSubscriberId;
import static com.android.internal.util.ArrayUtils.contains;
/**
* Template definition used to generically match {@link NetworkIdentity},
* usually when collecting statistics.
*
* @hide
*/
public class NetworkTemplate implements Parcelable {
public static final int MATCH_MOBILE_ALL = 1;
public static final int MATCH_MOBILE_3G_LOWER = 2;
public static final int MATCH_MOBILE_4G = 3;
public static final int MATCH_WIFI = 4;
public static final int MATCH_ETHERNET = 5;
public static final int MATCH_MOBILE_WILDCARD = 6;
public static final int MATCH_WIFI_WILDCARD = 7;
/**
* Network type is unknown
*/
public static final int NETWORK_TYPE_UNKNOWN = 0;
/**
* Current network is GPRS
*/
public static final int NETWORK_TYPE_GPRS = 1;
/**
* Current network is EDGE
*/
public static final int NETWORK_TYPE_EDGE = 2;
/**
* Current network is UMTS
*/
public static final int NETWORK_TYPE_UMTS = 3;
/**
* Current network is CDMA: Either IS95A or IS95B
*/
public static final int NETWORK_TYPE_CDMA = 4;
/**
* Current network is EVDO revision 0
*/
public static final int NETWORK_TYPE_EVDO_0 = 5;
/**
* Current network is EVDO revision A
*/
public static final int NETWORK_TYPE_EVDO_A = 6;
/**
* Current network is 1xRTT
*/
public static final int NETWORK_TYPE_1xRTT = 7;
/**
* Current network is HSDPA
*/
public static final int NETWORK_TYPE_HSDPA = 8;
/**
* Current network is HSUPA
*/
public static final int NETWORK_TYPE_HSUPA = 9;
/**
* Current network is HSPA
*/
public static final int NETWORK_TYPE_HSPA = 10;
/**
* Current network is iDen
*/
public static final int NETWORK_TYPE_IDEN = 11;
/**
* Current network is EVDO revision B
*/
public static final int NETWORK_TYPE_EVDO_B = 12;
/**
* Current network is LTE
*/
public static final int NETWORK_TYPE_LTE = 13;
/**
* Current network is eHRPD
*/
public static final int NETWORK_TYPE_EHRPD = 14;
/**
* Current network is HSPA+
*/
public static final int NETWORK_TYPE_HSPAP = 15;
/**
* Unknown network class. {@hide}
*/
public static final int NETWORK_CLASS_UNKNOWN = 0;
/**
* Class of broadly defined "2G" networks. {@hide}
*/
public static final int NETWORK_CLASS_2_G = 1;
/**
* Class of broadly defined "3G" networks. {@hide}
*/
public static final int NETWORK_CLASS_3_G = 2;
/**
* Class of broadly defined "4G" networks. {@hide}
*/
public static final int NETWORK_CLASS_4_G = 3;
/**
* Return general class of network type, such as "3G" or "4G". In cases
* where classification is contentious, this method is conservative.
*
* @hide
*/
public static int getNetworkClass(int networkType) {
switch (networkType) {
case NETWORK_TYPE_GPRS:
case NETWORK_TYPE_EDGE:
case NETWORK_TYPE_CDMA:
case NETWORK_TYPE_1xRTT:
case NETWORK_TYPE_IDEN:
return NETWORK_CLASS_2_G;
case NETWORK_TYPE_UMTS:
case NETWORK_TYPE_EVDO_0:
case NETWORK_TYPE_EVDO_A:
case NETWORK_TYPE_HSDPA:
case NETWORK_TYPE_HSUPA:
case NETWORK_TYPE_HSPA:
case NETWORK_TYPE_EVDO_B:
case NETWORK_TYPE_EHRPD:
case NETWORK_TYPE_HSPAP:
return NETWORK_CLASS_3_G;
case NETWORK_TYPE_LTE:
return NETWORK_CLASS_4_G;
default:
return NETWORK_CLASS_UNKNOWN;
}
}
/**
* Set of {@link NetworkInfo#getType()} that reflect data usage.
*/
private static final int[] DATA_USAGE_NETWORK_TYPES = {0};
private static boolean sForceAllNetworkTypes = false;
@VisibleForTesting
public static void forceAllNetworkTypes() {
sForceAllNetworkTypes = true;
}
/**
* Template to match {@link ConnectivityManager#TYPE_MOBILE} networks with
* the given IMSI.
*/
public static NetworkTemplate buildTemplateMobileAll(String subscriberId) {
return new NetworkTemplate(MATCH_MOBILE_ALL, subscriberId, null);
}
/**
* Template to match {@link ConnectivityManager#TYPE_MOBILE} networks with
* the given IMSI that roughly meet a "3G" definition, or lower.
*/
@Deprecated
public static NetworkTemplate buildTemplateMobile3gLower(String subscriberId) {
return new NetworkTemplate(MATCH_MOBILE_3G_LOWER, subscriberId, null);
}
/**
* Template to match {@link ConnectivityManager#TYPE_MOBILE} networks with
* the given IMSI that roughly meet a "4G" definition.
*/
@Deprecated
public static NetworkTemplate buildTemplateMobile4g(String subscriberId) {
return new NetworkTemplate(MATCH_MOBILE_4G, subscriberId, null);
}
/**
* Template to match {@link ConnectivityManager#TYPE_MOBILE} networks,
* regardless of IMSI.
*/
public static NetworkTemplate buildTemplateMobileWildcard() {
return new NetworkTemplate(MATCH_MOBILE_WILDCARD, null, null);
}
/**
* Template to match all {@link ConnectivityManager#TYPE_WIFI} networks,
* regardless of SSID.
*/
public static NetworkTemplate buildTemplateWifiWildcard() {
return new NetworkTemplate(MATCH_WIFI_WILDCARD, null, null);
}
@Deprecated
public static NetworkTemplate buildTemplateWifi() {
return buildTemplateWifiWildcard();
}
/**
* Template to match {@link ConnectivityManager#TYPE_WIFI} networks with the
* given SSID.
*/
public static NetworkTemplate buildTemplateWifi(String networkId) {
return new NetworkTemplate(MATCH_WIFI, null, networkId);
}
/**
* Template to combine all {@link ConnectivityManager#TYPE_ETHERNET} style
* networks together.
*/
public static NetworkTemplate buildTemplateEthernet() {
return new NetworkTemplate(MATCH_ETHERNET, null, null);
}
private final int mMatchRule;
private final String mSubscriberId;
private final String mNetworkId;
public NetworkTemplate(int matchRule, String subscriberId, String networkId) {
mMatchRule = matchRule;
mSubscriberId = subscriberId;
mNetworkId = networkId;
}
private NetworkTemplate(Parcel in) {
mMatchRule = in.readInt();
mSubscriberId = in.readString();
mNetworkId = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mMatchRule);
dest.writeString(mSubscriberId);
dest.writeString(mNetworkId);
}
@Override
public int describeContents() {
return 0;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder("NetworkTemplate: ");
builder.append("matchRule=").append(getMatchRuleName(mMatchRule));
if (mSubscriberId != null) {
builder.append(", subscriberId=").append(scrubSubscriberId(mSubscriberId));
}
if (mNetworkId != null) {
builder.append(", networkId=").append(mNetworkId);
}
return builder.toString();
}
@Override
public int hashCode() {
return Objects.hashCode(mMatchRule, mSubscriberId, mNetworkId);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof NetworkTemplate) {
final NetworkTemplate other = (NetworkTemplate) obj;
return mMatchRule == other.mMatchRule
&& Objects.equal(mSubscriberId, other.mSubscriberId)
&& Objects.equal(mNetworkId, other.mNetworkId);
}
return false;
}
public int getMatchRule() {
return mMatchRule;
}
public String getSubscriberId() {
return mSubscriberId;
}
public String getNetworkId() {
return mNetworkId;
}
/**
* Test if given {@link NetworkIdentity} matches this template.
*/
public boolean matches(NetworkIdentity ident) {
switch (mMatchRule) {
case MATCH_MOBILE_ALL:
return matchesMobile(ident);
case MATCH_MOBILE_3G_LOWER:
return matchesMobile3gLower(ident);
case MATCH_MOBILE_4G:
return matchesMobile4g(ident);
case MATCH_WIFI:
return matchesWifi(ident);
case MATCH_ETHERNET:
return matchesEthernet(ident);
case MATCH_MOBILE_WILDCARD:
return matchesMobileWildcard(ident);
case MATCH_WIFI_WILDCARD:
return matchesWifiWildcard(ident);
default:
throw new IllegalArgumentException("unknown network template");
}
}
/**
* Check if mobile network with matching IMSI.
*/
private boolean matchesMobile(NetworkIdentity ident) {
// TODO: consider matching against WiMAX subscriber identity
return ident.mType == TYPE_WIMAX || ((sForceAllNetworkTypes || contains(DATA_USAGE_NETWORK_TYPES, ident.mType)) && Objects.equal(mSubscriberId, ident.mSubscriberId));
}
/**
* Check if mobile network classified 3G or lower with matching IMSI.
*/
private boolean matchesMobile3gLower(NetworkIdentity ident) {
ensureSubtypeAvailable();
if (ident.mType == TYPE_WIMAX) {
return false;
} else if (matchesMobile(ident)) {
switch (getNetworkClass(ident.mSubType)) {
case 0:
case 1:
case 2:
return true;
}
}
return false;
}
/**
* Check if mobile network classified 4G with matching IMSI.
*/
private boolean matchesMobile4g(NetworkIdentity ident) {
ensureSubtypeAvailable();
if (ident.mType == TYPE_WIMAX) {
// TODO: consider matching against WiMAX subscriber identity
return true;
} else if (matchesMobile(ident)) {
switch (getNetworkClass(ident.mSubType)) {
case 3:
return true;
}
}
return false;
}
/**
* Check if matches Wi-Fi network template.
*/
private boolean matchesWifi(NetworkIdentity ident) {
switch (ident.mType) {
case TYPE_WIFI:
return Objects.equal(mNetworkId, ident.mNetworkId);
default:
return false;
}
}
/**
* Check if matches Ethernet network template.
*/
private boolean matchesEthernet(NetworkIdentity ident) {
return ident.mType == TYPE_ETHERNET;
}
private boolean matchesMobileWildcard(NetworkIdentity ident) {
return ident.mType == TYPE_WIMAX || sForceAllNetworkTypes || contains(DATA_USAGE_NETWORK_TYPES, ident.mType);
}
private boolean matchesWifiWildcard(NetworkIdentity ident) {
switch (ident.mType) {
case TYPE_WIFI:
case 13:
return true;
default:
return false;
}
}
private static String getMatchRuleName(int matchRule) {
switch (matchRule) {
case MATCH_MOBILE_3G_LOWER:
return "MOBILE_3G_LOWER";
case MATCH_MOBILE_4G:
return "MOBILE_4G";
case MATCH_MOBILE_ALL:
return "MOBILE_ALL";
case MATCH_WIFI:
return "WIFI";
case MATCH_ETHERNET:
return "ETHERNET";
case MATCH_MOBILE_WILDCARD:
return "MOBILE_WILDCARD";
case MATCH_WIFI_WILDCARD:
return "WIFI_WILDCARD";
default:
return "UNKNOWN";
}
}
private static void ensureSubtypeAvailable() {
if (COMBINE_SUBTYPE_ENABLED) {
throw new IllegalArgumentException(
"Unable to enforce 3G_LOWER template on combined data.");
}
}
public static final Creator<NetworkTemplate> CREATOR = new Creator<NetworkTemplate>() {
@Override
public NetworkTemplate createFromParcel(Parcel in) {
return new NetworkTemplate(in);
}
@Override
public NetworkTemplate[] newArray(int size) {
return new NetworkTemplate[size];
}
};
}
@@ -1,307 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.util.Log;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
/**
* Native methods for managing network interfaces.
* <p/>
* {@hide}
*/
public class NetworkUtils {
private static final String TAG = "NetworkUtils";
/**
* Bring the named network interface up.
*/
public native static int enableInterface(String interfaceName);
/**
* Bring the named network interface down.
*/
public native static int disableInterface(String interfaceName);
/**
* Setting bit 0 indicates reseting of IPv4 addresses required
*/
public static final int RESET_IPV4_ADDRESSES = 0x01;
/**
* Setting bit 1 indicates reseting of IPv4 addresses required
*/
public static final int RESET_IPV6_ADDRESSES = 0x02;
/**
* Reset all addresses
*/
public static final int RESET_ALL_ADDRESSES = RESET_IPV4_ADDRESSES | RESET_IPV6_ADDRESSES;
/**
* Reset IPv6 or IPv4 sockets that are connected via the named interface.
*
* @param interfaceName is the interface to reset
* @param mask {@see #RESET_IPV4_ADDRESSES} and {@see #RESET_IPV6_ADDRESSES}
*/
public native static int resetConnections(String interfaceName, int mask);
/**
* Start the DHCP client daemon, in order to have it request addresses
* for the named interface, and then configure the interface with those
* addresses. This call blocks until it obtains a result (either success
* or failure) from the daemon.
*
* @param interfaceName the name of the interface to configure
* @param ipInfo if the request succeeds, this object is filled in with
* the IP address information.
* @return {@code true} for success, {@code false} for failure
*/
public native static boolean runDhcp(String interfaceName, DhcpInfoInternal ipInfo);
/**
* Initiate renewal on the Dhcp client daemon. This call blocks until it obtains
* a result (either success or failure) from the daemon.
*
* @param interfaceName the name of the interface to configure
* @param ipInfo if the request succeeds, this object is filled in with
* the IP address information.
* @return {@code true} for success, {@code false} for failure
*/
public native static boolean runDhcpRenew(String interfaceName, DhcpInfoInternal ipInfo);
/**
* Shut down the DHCP client daemon.
*
* @param interfaceName the name of the interface for which the daemon
* should be stopped
* @return {@code true} for success, {@code false} for failure
*/
public native static boolean stopDhcp(String interfaceName);
/**
* Release the current DHCP lease.
*
* @param interfaceName the name of the interface for which the lease should
* be released
* @return {@code true} for success, {@code false} for failure
*/
public native static boolean releaseDhcpLease(String interfaceName);
/**
* Return the last DHCP-related error message that was recorded.
* <p/>NOTE: This string is not localized, but currently it is only
* used in logging.
*
* @return the most recent error message, if any
*/
public native static String getDhcpError();
/**
* Convert a IPv4 address from an integer to an InetAddress.
*
* @param hostAddress an int corresponding to the IPv4 address in network byte order
*/
public static InetAddress intToInetAddress(int hostAddress) {
byte[] addressBytes = {(byte) (0xff & hostAddress),
(byte) (0xff & (hostAddress >> 8)),
(byte) (0xff & (hostAddress >> 16)),
(byte) (0xff & (hostAddress >> 24))};
try {
return InetAddress.getByAddress(addressBytes);
} catch (UnknownHostException e) {
throw new AssertionError();
}
}
/**
* Convert a IPv4 address from an InetAddress to an integer
*
* @param inetAddr is an InetAddress corresponding to the IPv4 address
* @return the IP address as an integer in network byte order
*/
public static int inetAddressToInt(InetAddress inetAddr)
throws IllegalArgumentException {
byte[] addr = inetAddr.getAddress();
if (addr.length != 4) {
throw new IllegalArgumentException("Not an IPv4 address");
}
return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
}
/**
* Convert a network prefix length to an IPv4 netmask integer
*
* @param prefixLength
* @return the IPv4 netmask as an integer in network byte order
*/
public static int prefixLengthToNetmaskInt(int prefixLength)
throws IllegalArgumentException {
if (prefixLength < 0 || prefixLength > 32) {
throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
}
int value = 0xffffffff << (32 - prefixLength);
return Integer.reverseBytes(value);
}
/**
* Convert a IPv4 netmask integer to a prefix length
*
* @param netmask as an integer in network byte order
* @return the network prefix length
*/
public static int netmaskIntToPrefixLength(int netmask) {
return Integer.bitCount(netmask);
}
/**
* Create an InetAddress from a string where the string must be a standard
* representation of a V4 or V6 address. Avoids doing a DNS lookup on failure
* but it will throw an IllegalArgumentException in that case.
*
* @param addrString
* @return the InetAddress
* @hide
*/
public static InetAddress numericToInetAddress(String addrString)
throws IllegalArgumentException {
return null;
}
/**
* Get InetAddress masked with prefixLength. Will never return null.
*
* @param IP address which will be masked with specified prefixLength
* @param prefixLength the prefixLength used to mask the IP
*/
public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
if (address == null) {
throw new RuntimeException("getNetworkPart doesn't accept null address");
}
byte[] array = address.getAddress();
if (prefixLength < 0 || prefixLength > array.length * 8) {
throw new RuntimeException("getNetworkPart - bad prefixLength");
}
int offset = prefixLength / 8;
int reminder = prefixLength % 8;
byte mask = (byte) (0xFF << (8 - reminder));
if (offset < array.length) array[offset] = (byte) (array[offset] & mask);
offset++;
for (; offset < array.length; offset++) {
array[offset] = 0;
}
InetAddress netPart = null;
try {
netPart = InetAddress.getByAddress(array);
} catch (UnknownHostException e) {
throw new RuntimeException("getNetworkPart error - " + e.toString());
}
return netPart;
}
/**
* Check if IP address type is consistent between two InetAddress.
*
* @return true if both are the same type. False otherwise.
*/
public static boolean addressTypeMatches(InetAddress left, InetAddress right) {
return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) ||
((left instanceof Inet6Address) && (right instanceof Inet6Address)));
}
/**
* Convert a 32 char hex string into a Inet6Address.
* throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
* made into an Inet6Address
*
* @param addrHexString a 32 character hex string representing an IPv6 addr
* @return addr an InetAddress representation for the string
*/
public static InetAddress hexToInet6Address(String addrHexString)
throws IllegalArgumentException {
try {
return numericToInetAddress(String.format("%s:%s:%s:%s:%s:%s:%s:%s",
addrHexString.substring(0, 4), addrHexString.substring(4, 8),
addrHexString.substring(8, 12), addrHexString.substring(12, 16),
addrHexString.substring(16, 20), addrHexString.substring(20, 24),
addrHexString.substring(24, 28), addrHexString.substring(28, 32)));
} catch (Exception e) {
Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
throw new IllegalArgumentException(e);
}
}
/**
* Create a string array of host addresses from a collection of InetAddresses
*
* @param addrs a Collection of InetAddresses
* @return an array of Strings containing their host addresses
*/
public static String[] makeStrings(Collection<InetAddress> addrs) {
String[] result = new String[addrs.size()];
int i = 0;
for (InetAddress addr : addrs) {
result[i++] = addr.getHostAddress();
}
return result;
}
/**
* Trim leading zeros from IPv4 address strings
* Our base libraries will interpret that as octel..
* Must leave non v4 addresses and host names alone.
* For example, 192.168.000.010 -> 192.168.0.10
* TODO - fix base libraries and remove this function
*
* @param addr a string representing an ip addr
* @return a string propertly trimmed
*/
public static String trimV4AddrZeros(String addr) {
if (addr == null) return null;
String[] octets = addr.split("\\.");
if (octets.length != 4) return addr;
StringBuilder builder = new StringBuilder(16);
String result = null;
for (int i = 0; i < 4; i++) {
try {
if (octets[i].length() > 3) return addr;
builder.append(Integer.parseInt(octets[i]));
} catch (NumberFormatException e) {
return addr;
}
if (i < 3) builder.append('.');
}
result = builder.toString();
return result;
}
}
@@ -1,220 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.annotation.SuppressLint;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import java.net.InetSocketAddress;
/**
* A container class for the http proxy info
*
* @hide
*/
public class ProxyProperties implements Parcelable {
private String mHost;
private int mPort;
private String mExclusionList;
private String[] mParsedExclusionList;
public ProxyProperties(String host, int port, String exclList) {
mHost = host;
mPort = port;
setExclusionList(exclList);
}
private ProxyProperties(String host, int port, String exclList, String[] parsedExclList) {
mHost = host;
mPort = port;
mExclusionList = exclList;
mParsedExclusionList = parsedExclList;
}
// copy constructor instead of clone
public ProxyProperties(ProxyProperties source) {
if (source != null) {
mHost = source.getHost();
mPort = source.getPort();
mExclusionList = source.getExclusionList();
mParsedExclusionList = source.mParsedExclusionList;
}
}
public InetSocketAddress getSocketAddress() {
InetSocketAddress inetSocketAddress = null;
try {
inetSocketAddress = new InetSocketAddress(mHost, mPort);
} catch (IllegalArgumentException e) {
}
return inetSocketAddress;
}
public String getHost() {
return mHost;
}
public int getPort() {
return mPort;
}
// comma separated
public String getExclusionList() {
return mExclusionList;
}
// comma separated
@SuppressLint("DefaultLocale")
private void setExclusionList(String exclusionList) {
mExclusionList = exclusionList;
if (mExclusionList == null) {
mParsedExclusionList = new String[0];
} else {
String splitExclusionList[] = exclusionList.toLowerCase().split(",");
mParsedExclusionList = new String[splitExclusionList.length * 2];
for (int i = 0; i < splitExclusionList.length; i++) {
String s = splitExclusionList[i].trim();
if (s.startsWith(".")) s = s.substring(1);
mParsedExclusionList[i * 2] = s;
mParsedExclusionList[(i * 2) + 1] = "." + s;
}
}
}
public boolean isExcluded(String url) {
if (TextUtils.isEmpty(url) || mParsedExclusionList == null ||
mParsedExclusionList.length == 0) return false;
Uri u = Uri.parse(url);
String urlDomain = u.getHost();
if (urlDomain == null) return false;
for (int i = 0; i < mParsedExclusionList.length; i += 2) {
if (urlDomain.equals(mParsedExclusionList[i]) ||
urlDomain.endsWith(mParsedExclusionList[i + 1])) {
return true;
}
}
return false;
}
public java.net.Proxy makeProxy() {
java.net.Proxy proxy = java.net.Proxy.NO_PROXY;
if (mHost != null) {
try {
InetSocketAddress inetSocketAddress = new InetSocketAddress(mHost, mPort);
proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, inetSocketAddress);
} catch (IllegalArgumentException e) {
}
}
return proxy;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (mHost != null) {
sb.append("[");
sb.append(mHost);
sb.append("] ");
sb.append(Integer.toString(mPort));
if (mExclusionList != null) {
sb.append(" xl=").append(mExclusionList);
}
} else {
sb.append("[ProxyProperties.mHost == null]");
}
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ProxyProperties)) return false;
ProxyProperties p = (ProxyProperties) o;
if (mExclusionList != null && !mExclusionList.equals(p.getExclusionList())) return false;
if (mHost != null && p.getHost() != null && !mHost.equals(p.getHost())) {
return false;
}
if (mHost != null && p.mHost == null) return false;
return !(mHost == null && p.mHost != null) && mPort == p.mPort;
}
/**
* Implement the Parcelable interface
*
* @hide
*/
public int describeContents() {
return 0;
}
@Override
/*
* generate hashcode based on significant fields
*/
public int hashCode() {
return ((null == mHost) ? 0 : mHost.hashCode())
+ ((null == mExclusionList) ? 0 : mExclusionList.hashCode())
+ mPort;
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public void writeToParcel(Parcel dest, int flags) {
if (mHost != null) {
dest.writeByte((byte) 1);
dest.writeString(mHost);
dest.writeInt(mPort);
} else {
dest.writeByte((byte) 0);
}
dest.writeString(mExclusionList);
dest.writeStringArray(mParsedExclusionList);
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public static final Creator<ProxyProperties> CREATOR =
new Creator<ProxyProperties>() {
public ProxyProperties createFromParcel(Parcel in) {
String host = null;
int port = 0;
if (in.readByte() == 1) {
host = in.readString();
port = in.readInt();
}
String exclList = in.readString();
//String[] parsedExclList = in.readStringArray();
ProxyProperties proxyProperties =
new ProxyProperties(host, port, exclList, null);
return proxyProperties;
}
public ProxyProperties[] newArray(int size) {
return new ProxyProperties[size];
}
};
}
@@ -1,287 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
/**
* A simple container for route information.
*
* @hide
*/
public class RouteInfo implements Parcelable {
private static final String TAG = "RouteInfo";
/**
* The IP destination address for this route.
*/
private final LinkAddress mDestination;
/**
* The gateway address for this route.
*/
private final InetAddress mGateway;
private final boolean mIsDefault;
private final boolean mIsHost;
public RouteInfo(LinkAddress destination, InetAddress gateway) {
if (destination == null) {
if (gateway != null) {
if (gateway instanceof Inet4Address) {
try {
destination = new LinkAddress(Inet4Address.getLocalHost(), 0);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "exception thrown", e);
}
} else {
try {
destination = new LinkAddress(Inet6Address.getLocalHost(), 0);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "exception thrown", e);
}
}
} else {
// no destination, no gateway. invalid.
throw new RuntimeException("Invalid arguments passed in.");
}
}
if (gateway == null) {
if (destination.getAddress() instanceof Inet4Address) {
try {
gateway = Inet4Address.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "exception thrown", e);
}
} else {
try {
gateway = Inet6Address.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "exception thrown", e);
}
}
}
mDestination = new LinkAddress(NetworkUtils.getNetworkPart(destination.getAddress(),
destination.getNetworkPrefixLength()), destination.getNetworkPrefixLength());
mGateway = gateway;
mIsDefault = isDefault();
mIsHost = isHost();
}
public RouteInfo(InetAddress gateway) {
this(null, gateway);
}
public static RouteInfo makeHostRoute(InetAddress host) {
return makeHostRoute(host, null);
}
public static RouteInfo makeHostRoute(InetAddress host, InetAddress gateway) {
if (host == null) return null;
if (host instanceof Inet4Address) {
return new RouteInfo(new LinkAddress(host, 32), gateway);
} else {
return new RouteInfo(new LinkAddress(host, 128), gateway);
}
}
private boolean isHost() {
try {
return (mGateway.equals(Inet4Address.getLocalHost()) || mGateway.equals(Inet6Address.getLocalHost()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
return false;
}
}
private boolean isDefault() {
boolean val = false;
if (mGateway != null) {
if (mGateway instanceof Inet4Address) {
val = (mDestination == null || mDestination.getNetworkPrefixLength() == 0);
} else {
val = (mDestination == null || mDestination.getNetworkPrefixLength() == 0);
}
}
return val;
}
public LinkAddress getDestination() {
return mDestination;
}
public InetAddress getGateway() {
return mGateway;
}
public boolean isDefaultRoute() {
return mIsDefault;
}
public boolean isHostRoute() {
return mIsHost;
}
public String toString() {
String val = "";
if (mDestination != null) val = mDestination.toString();
if (mGateway != null) val += " -> " + mGateway.getHostAddress();
return val;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
if (mDestination == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeByteArray(mDestination.getAddress().getAddress());
dest.writeInt(mDestination.getNetworkPrefixLength());
}
if (mGateway == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeByteArray(mGateway.getAddress());
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof RouteInfo)) return false;
RouteInfo target = (RouteInfo) obj;
boolean sameDestination = (mDestination == null) ?
target.getDestination() == null
: mDestination.equals(target.getDestination());
boolean sameAddress = (mGateway == null) ?
target.getGateway() == null
: mGateway.equals(target.getGateway());
return sameDestination && sameAddress
&& mIsDefault == target.mIsDefault;
}
@Override
public int hashCode() {
return (mDestination == null ? 0 : mDestination.hashCode())
+ (mGateway == null ? 0 : mGateway.hashCode())
+ (mIsDefault ? 3 : 7);
}
public static final Creator<RouteInfo> CREATOR =
new Creator<RouteInfo>() {
public RouteInfo createFromParcel(Parcel in) {
InetAddress destAddr = null;
int prefix = 0;
InetAddress gateway = null;
if (in.readByte() == 1) {
byte[] addr = in.createByteArray();
prefix = in.readInt();
try {
destAddr = InetAddress.getByAddress(addr);
} catch (UnknownHostException e) {
}
}
if (in.readByte() == 1) {
byte[] addr = in.createByteArray();
try {
gateway = InetAddress.getByAddress(addr);
} catch (UnknownHostException e) {
}
}
LinkAddress dest = null;
if (destAddr != null) {
dest = new LinkAddress(destAddr, prefix);
}
return new RouteInfo(dest, gateway);
}
public RouteInfo[] newArray(int size) {
return new RouteInfo[size];
}
};
private boolean matches(InetAddress destination) {
if (destination == null) return false;
// if the destination is present and the route is default.
// return true
if (isDefault()) return true;
// match the route destination and destination with prefix length
InetAddress dstNet = NetworkUtils.getNetworkPart(destination,
mDestination.getNetworkPrefixLength());
return mDestination.getAddress().equals(dstNet);
}
/**
* Find the route from a Collection of routes that best matches a given address.
* May return null if no routes are applicable.
*
* @param routes a Collection of RouteInfos to chose from
* @param dest the InetAddress your trying to get to
* @return the RouteInfo from the Collection that best fits the given address
*/
public static RouteInfo selectBestRoute(Collection<RouteInfo> routes, InetAddress dest) {
if ((routes == null) || (dest == null)) return null;
RouteInfo bestRoute = null;
// pick a longest prefix match under same address type
for (RouteInfo route : routes) {
if (NetworkUtils.addressTypeMatches(route.mDestination.getAddress(), dest)) {
if ((bestRoute != null) &&
(bestRoute.mDestination.getNetworkPrefixLength() >=
route.mDestination.getNetworkPrefixLength())) {
continue;
}
if (route.matches(dest)) bestRoute = route;
}
}
return bestRoute;
}
}
@@ -1,835 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.provider;
import android.app.DownloadManager;
import android.content.Context;
import android.net.NetworkPolicyManager;
import android.net.Uri;
/**
* The Download Manager
*
* @pending
*/
public final class Downloads {
private Downloads() {
}
/**
* Implementation details
* <p/>
* Exposes constants used to interact with the download manager's
* content provider.
* The constants URI ... STATUS are the names of columns in the downloads table.
*
* @hide
*/
public static final class Impl implements BaseColumns {
private Impl() {
}
/**
* The permission to access the download manager
*/
public static final String PERMISSION_ACCESS = "android.permission.ACCESS_DOWNLOAD_MANAGER";
/**
* The permission to access the download manager's advanced functions
*/
public static final String PERMISSION_ACCESS_ADVANCED =
"android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED";
/**
* The permission to access the all the downloads in the manager.
*/
public static final String PERMISSION_ACCESS_ALL =
"android.permission.ACCESS_ALL_DOWNLOADS";
/**
* The permission to directly access the download manager's cache
* directory
*/
public static final String PERMISSION_CACHE = "android.permission.ACCESS_CACHE_FILESYSTEM";
/**
* The permission to send broadcasts on download completion
*/
public static final String PERMISSION_SEND_INTENTS =
"android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS";
/**
* The permission to download files to the cache partition that won't be automatically
* purged when space is needed.
*/
public static final String PERMISSION_CACHE_NON_PURGEABLE =
"android.permission.DOWNLOAD_CACHE_NON_PURGEABLE";
/**
* The permission to download files without any system notification being shown.
*/
public static final String PERMISSION_NO_NOTIFICATION =
"android.permission.DOWNLOAD_WITHOUT_NOTIFICATION";
/**
* The content:// URI to access downloads owned by the caller's UID.
*/
public static final Uri CONTENT_URI =
Uri.parse("content://downloads/my_downloads");
/**
* The content URI for accessing all downloads across all UIDs (requires the
* ACCESS_ALL_DOWNLOADS permission).
*/
public static final Uri ALL_DOWNLOADS_CONTENT_URI =
Uri.parse("content://downloads/all_downloads");
/**
* URI segment to access a publicly accessible downloaded file
*/
public static final String PUBLICLY_ACCESSIBLE_DOWNLOADS_URI_SEGMENT = "public_downloads";
/**
* The content URI for accessing publicly accessible downloads (i.e., it requires no
* permissions to access this downloaded file)
*/
public static final Uri PUBLICLY_ACCESSIBLE_DOWNLOADS_URI =
Uri.parse("content://downloads/" + PUBLICLY_ACCESSIBLE_DOWNLOADS_URI_SEGMENT);
/**
* Broadcast Action: this is sent by the download manager to the app
* that had initiated a download when that download completes. The
* download's content: uri is specified in the intent's data.
*/
public static final String ACTION_DOWNLOAD_COMPLETED =
"android.intent.action.DOWNLOAD_COMPLETED";
/**
* Broadcast Action: this is sent by the download manager to the app
* that had initiated a download when the user selects the notification
* associated with that download. The download's content: uri is specified
* in the intent's data if the click is associated with a single download,
* or Downloads.CONTENT_URI if the notification is associated with
* multiple downloads.
* Note: this is not currently sent for downloads that have completed
* successfully.
*/
public static final String ACTION_NOTIFICATION_CLICKED =
"android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
/**
* The name of the column containing the URI of the data being downloaded.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_URI = "uri";
/**
* The name of the column containing application-specific data.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read/Write</P>
*/
public static final String COLUMN_APP_DATA = "entity";
/**
* The name of the column containing the flags that indicates whether
* the initiating application is capable of verifying the integrity of
* the downloaded file. When this flag is set, the download manager
* performs downloads and reports success even in some situations where
* it can't guarantee that the download has completed (e.g. when doing
* a byte-range request without an ETag, or when it can't determine
* whether a download fully completed).
* <P>Type: BOOLEAN</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_NO_INTEGRITY = "no_integrity";
/**
* The name of the column containing the filename that the initiating
* application recommends. When possible, the download manager will attempt
* to use this filename, or a variation, as the actual name for the file.
* <P>Type: TEXT</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_FILE_NAME_HINT = "hint";
/**
* The name of the column containing the filename where the downloaded data
* was actually stored.
* <P>Type: TEXT</P>
* <P>Owner can Read</P>
*/
public static final String _DATA = "_data";
/**
* The name of the column containing the MIME type of the downloaded data.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_MIME_TYPE = "mimetype";
/**
* The name of the column containing the flag that controls the destination
* of the download. See the DESTINATION_* constants for a list of legal values.
* <P>Type: INTEGER</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_DESTINATION = "destination";
/**
* The name of the column containing the flags that controls whether the
* download is displayed by the UI. See the VISIBILITY_* constants for
* a list of legal values.
* <P>Type: INTEGER</P>
* <P>Owner can Init/Read/Write</P>
*/
public static final String COLUMN_VISIBILITY = "visibility";
/**
* The name of the column containing the current control state of the download.
* Applications can write to this to control (pause/resume) the download.
* the CONTROL_* constants for a list of legal values.
* <P>Type: INTEGER</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_CONTROL = "control";
/**
* The name of the column containing the current status of the download.
* Applications can read this to follow the progress of each download. See
* the STATUS_* constants for a list of legal values.
* <P>Type: INTEGER</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_STATUS = "status";
/**
* The name of the column containing the date at which some interesting
* status changed in the download. Stored as a System.currentTimeMillis()
* value.
* <P>Type: BIGINT</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_LAST_MODIFICATION = "lastmod";
/**
* The name of the column containing the package name of the application
* that initiating the download. The download manager will send
* notifications to a component in this package when the download completes.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_NOTIFICATION_PACKAGE = "notificationpackage";
/**
* The name of the column containing the component name of the class that
* will receive notifications associated with the download. The
* package/class combination is passed to
* Intent.setClassName(String,String).
* <P>Type: TEXT</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_NOTIFICATION_CLASS = "notificationclass";
/**
* If extras are specified when requesting a download they will be provided in the intent that
* is sent to the specified class and package when a download has finished.
* <P>Type: TEXT</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_NOTIFICATION_EXTRAS = "notificationextras";
/**
* The name of the column contain the values of the cookie to be used for
* the download. This is used directly as the value for the Cookie: HTTP
* header that gets sent with the request.
* <P>Type: TEXT</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_COOKIE_DATA = "cookiedata";
/**
* The name of the column containing the user agent that the initiating
* application wants the download manager to use for this download.
* <P>Type: TEXT</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_USER_AGENT = "useragent";
/**
* The name of the column containing the referer (sic) that the initiating
* application wants the download manager to use for this download.
* <P>Type: TEXT</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_REFERER = "referer";
/**
* The name of the column containing the total size of the file being
* downloaded.
* <P>Type: INTEGER</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_TOTAL_BYTES = "total_bytes";
/**
* The name of the column containing the size of the part of the file that
* has been downloaded so far.
* <P>Type: INTEGER</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_CURRENT_BYTES = "current_bytes";
/**
* The name of the column where the initiating application can provide the
* UID of another application that is allowed to access this download. If
* multiple applications share the same UID, all those applications will be
* allowed to access this download. This column can be updated after the
* download is initiated. This requires the permission
* android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED.
* <P>Type: INTEGER</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_OTHER_UID = "otheruid";
/**
* The name of the column where the initiating application can provided the
* title of this download. The title will be displayed ito the user in the
* list of downloads.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read/Write</P>
*/
public static final String COLUMN_TITLE = "title";
/**
* The name of the column where the initiating application can provide the
* description of this download. The description will be displayed to the
* user in the list of downloads.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read/Write</P>
*/
public static final String COLUMN_DESCRIPTION = "description";
/**
* The name of the column indicating whether the download was requesting through the public
* API. This controls some differences in behavior.
* <P>Type: BOOLEAN</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_IS_PUBLIC_API = "is_public_api";
/**
* The name of the column holding a bitmask of allowed network types. This is only used for
* public API downloads.
* <P>Type: INTEGER</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_ALLOWED_NETWORK_TYPES = "allowed_network_types";
/**
* The name of the column indicating whether roaming connections can be used. This is only
* used for public API downloads.
* <P>Type: BOOLEAN</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_ALLOW_ROAMING = "allow_roaming";
/**
* The name of the column indicating whether metered connections can be used. This is only
* used for public API downloads.
* <P>Type: BOOLEAN</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_ALLOW_METERED = "allow_metered";
/**
* Whether or not this download should be displayed in the system's Downloads UI. Defaults
* to true.
* <P>Type: INTEGER</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI = "is_visible_in_downloads_ui";
/**
* If true, the user has confirmed that this download can proceed over the mobile network
* even though it exceeds the recommended maximum size.
* <P>Type: BOOLEAN</P>
*/
public static final String COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT =
"bypass_recommended_size_limit";
/**
* Set to true if this download is deleted. It is completely removed from the database
* when MediaProvider database also deletes the metadata asociated with this downloaded file.
* <P>Type: BOOLEAN</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_DELETED = "deleted";
/**
* The URI to the corresponding entry in MediaProvider for this downloaded entry. It is
* used to delete the entries from MediaProvider database when it is deleted from the
* downloaded list.
* <P>Type: TEXT</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_MEDIAPROVIDER_URI = "mediaprovider_uri";
/**
* The column that is used to remember whether the media scanner was invoked.
* It can take the values: null or 0(not scanned), 1(scanned), 2 (not scannable).
* <P>Type: TEXT</P>
*/
public static final String COLUMN_MEDIA_SCANNED = "scanned";
/**
* The column with errorMsg for a failed downloaded.
* Used only for debugging purposes.
* <P>Type: TEXT</P>
*/
public static final String COLUMN_ERROR_MSG = "errorMsg";
/**
* This column stores the source of the last update to this row.
* This column is only for internal use.
* Valid values are indicated by LAST_UPDATESRC_* constants.
* <P>Type: INT</P>
*/
public static final String COLUMN_LAST_UPDATESRC = "lastUpdateSrc";
/**
* default value for {@link #COLUMN_LAST_UPDATESRC}.
* This value is used when this column's value is not relevant.
*/
public static final int LAST_UPDATESRC_NOT_RELEVANT = 0;
/**
* One of the values taken by {@link #COLUMN_LAST_UPDATESRC}.
* This value is used when the update is NOT to be relayed to the DownloadService
* (and thus spare DownloadService from scanning the database when this change occurs)
*/
public static final int LAST_UPDATESRC_DONT_NOTIFY_DOWNLOADSVC = 1;
/*
* Lists the destinations that an application can specify for a download.
*/
/**
* This download will be saved to the external storage. This is the
* default behavior, and should be used for any file that the user
* can freely access, copy, delete. Even with that destination,
* unencrypted DRM files are saved in secure internal storage.
* Downloads to the external destination only write files for which
* there is a registered handler. The resulting files are accessible
* by filename to all applications.
*/
public static final int DESTINATION_EXTERNAL = 0;
/**
* This download will be saved to the download manager's private
* partition. This is the behavior used by applications that want to
* download private files that are used and deleted soon after they
* get downloaded. All file types are allowed, and only the initiating
* application can access the file (indirectly through a content
* provider). This requires the
* android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED permission.
*/
public static final int DESTINATION_CACHE_PARTITION = 1;
/**
* This download will be saved to the download manager's private
* partition and will be purged as necessary to make space. This is
* for private files (similar to CACHE_PARTITION) that aren't deleted
* immediately after they are used, and are kept around by the download
* manager as long as space is available.
*/
public static final int DESTINATION_CACHE_PARTITION_PURGEABLE = 2;
/**
* This download will be saved to the download manager's private
* partition, as with DESTINATION_CACHE_PARTITION, but the download
* will not proceed if the user is on a roaming data connection.
*/
public static final int DESTINATION_CACHE_PARTITION_NOROAMING = 3;
/**
* This download will be saved to the location given by the file URI in
* {@link #COLUMN_FILE_NAME_HINT}.
*/
public static final int DESTINATION_FILE_URI = 4;
/**
* This download will be saved to the system cache ("/cache")
* partition. This option is only used by system apps and so it requires
* android.permission.ACCESS_CACHE_FILESYSTEM permission.
*/
public static final int DESTINATION_SYSTEMCACHE_PARTITION = 5;
/**
* This download was completed by the caller (i.e., NOT downloadmanager)
* and caller wants to have this download displayed in Downloads App.
*/
public static final int DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD = 6;
/**
* This download is allowed to run.
*/
public static final int CONTROL_RUN = 0;
/**
* This download must pause at the first opportunity.
*/
public static final int CONTROL_PAUSED = 1;
/*
* Lists the states that the download manager can set on a download
* to notify applications of the download progress.
* The codes follow the HTTP families:<br>
* 1xx: informational<br>
* 2xx: success<br>
* 3xx: redirects (not used by the download manager)<br>
* 4xx: client errors<br>
* 5xx: server errors
*/
/**
* Returns whether the status is informational (i.e. 1xx).
*/
public static boolean isStatusInformational(int status) {
return (status >= 100 && status < 200);
}
/**
* Returns whether the status is a success (i.e. 2xx).
*/
public static boolean isStatusSuccess(int status) {
return (status >= 200 && status < 300);
}
/**
* Returns whether the status is an error (i.e. 4xx or 5xx).
*/
public static boolean isStatusError(int status) {
return (status >= 400 && status < 600);
}
/**
* Returns whether the status is a client error (i.e. 4xx).
*/
public static boolean isStatusClientError(int status) {
return (status >= 400 && status < 500);
}
/**
* Returns whether the status is a server error (i.e. 5xx).
*/
public static boolean isStatusServerError(int status) {
return (status >= 500 && status < 600);
}
/**
* this method determines if a notification should be displayed for a
* given {@link #COLUMN_VISIBILITY} value
*
* @param visibility the value of {@link #COLUMN_VISIBILITY}.
* @return true if the notification should be displayed. false otherwise.
*/
public static boolean isNotificationToBeDisplayed(int visibility) {
return visibility == DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED ||
visibility == DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION;
}
/**
* Returns whether the download has completed (either with success or
* error).
*/
public static boolean isStatusCompleted(int status) {
return (status >= 200 && status < 300) || (status >= 400 && status < 600);
}
/**
* This download hasn't stated yet
*/
public static final int STATUS_PENDING = 190;
/**
* This download has started
*/
public static final int STATUS_RUNNING = 192;
/**
* This download has been paused by the owning app.
*/
public static final int STATUS_PAUSED_BY_APP = 193;
/**
* This download encountered some network error and is waiting before retrying the request.
*/
public static final int STATUS_WAITING_TO_RETRY = 194;
/**
* This download is waiting for network connectivity to proceed.
*/
public static final int STATUS_WAITING_FOR_NETWORK = 195;
/**
* This download exceeded a size limit for mobile networks and is waiting for a Wi-Fi
* connection to proceed.
*/
public static final int STATUS_QUEUED_FOR_WIFI = 196;
/**
* This download couldn't be completed due to insufficient storage
* space. Typically, this is because the SD card is full.
*/
public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 198;
/**
* This download couldn't be completed because no external storage
* device was found. Typically, this is because the SD card is not
* mounted.
*/
public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 199;
/**
* This download has successfully completed.
* Warning: there might be other status values that indicate success
* in the future.
* Use isSucccess() to capture the entire category.
*/
public static final int STATUS_SUCCESS = 200;
/**
* This request couldn't be parsed. This is also used when processing
* requests with unknown/unsupported URI schemes.
*/
public static final int STATUS_BAD_REQUEST = 400;
/**
* This download can't be performed because the content type cannot be
* handled.
*/
public static final int STATUS_NOT_ACCEPTABLE = 406;
/**
* This download cannot be performed because the length cannot be
* determined accurately. This is the code for the HTTP error "Length
* Required", which is typically used when making requests that require
* a content length but don't have one, and it is also used in the
* client when a response is received whose length cannot be determined
* accurately (therefore making it impossible to know when a download
* completes).
*/
public static final int STATUS_LENGTH_REQUIRED = 411;
/**
* This download was interrupted and cannot be resumed.
* This is the code for the HTTP error "Precondition Failed", and it is
* also used in situations where the client doesn't have an ETag at all.
*/
public static final int STATUS_PRECONDITION_FAILED = 412;
/**
* The lowest-valued error status that is not an actual HTTP status code.
*/
public static final int MIN_ARTIFICIAL_ERROR_STATUS = 488;
/**
* The requested destination file already exists.
*/
public static final int STATUS_FILE_ALREADY_EXISTS_ERROR = 488;
/**
* Some possibly transient error occurred, but we can't resume the download.
*/
public static final int STATUS_CANNOT_RESUME = 489;
/**
* This download was canceled
*/
public static final int STATUS_CANCELED = 490;
/**
* This download has completed with an error.
* Warning: there will be other status values that indicate errors in
* the future. Use isStatusError() to capture the entire category.
*/
public static final int STATUS_UNKNOWN_ERROR = 491;
/**
* This download couldn't be completed because of a storage issue.
* Typically, that's because the filesystem is missing or full.
* Use the more specific {@link #STATUS_INSUFFICIENT_SPACE_ERROR}
* and {@link #STATUS_DEVICE_NOT_FOUND_ERROR} when appropriate.
*/
public static final int STATUS_FILE_ERROR = 492;
/**
* This download couldn't be completed because of an HTTP
* redirect response that the download manager couldn't
* handle.
*/
public static final int STATUS_UNHANDLED_REDIRECT = 493;
/**
* This download couldn't be completed because of an
* unspecified unhandled HTTP code.
*/
public static final int STATUS_UNHANDLED_HTTP_CODE = 494;
/**
* This download couldn't be completed because of an
* error receiving or processing data at the HTTP level.
*/
public static final int STATUS_HTTP_DATA_ERROR = 495;
/**
* This download couldn't be completed because of an
* HttpException while setting up the request.
*/
public static final int STATUS_HTTP_EXCEPTION = 496;
/**
* This download couldn't be completed because there were
* too many redirects.
*/
public static final int STATUS_TOO_MANY_REDIRECTS = 497;
/**
* This download has failed because requesting application has been
* blocked by {@link NetworkPolicyManager}.
*
* @hide
* @deprecated since behavior now uses
* {@link #STATUS_WAITING_FOR_NETWORK}
*/
@Deprecated
public static final int STATUS_BLOCKED = 498;
/**
* {@hide}
*/
public static String statusToString(int status) {
switch (status) {
case STATUS_PENDING:
return "PENDING";
case STATUS_RUNNING:
return "RUNNING";
case STATUS_PAUSED_BY_APP:
return "PAUSED_BY_APP";
case STATUS_WAITING_TO_RETRY:
return "WAITING_TO_RETRY";
case STATUS_WAITING_FOR_NETWORK:
return "WAITING_FOR_NETWORK";
case STATUS_QUEUED_FOR_WIFI:
return "QUEUED_FOR_WIFI";
case STATUS_INSUFFICIENT_SPACE_ERROR:
return "INSUFFICIENT_SPACE_ERROR";
case STATUS_DEVICE_NOT_FOUND_ERROR:
return "DEVICE_NOT_FOUND_ERROR";
case STATUS_SUCCESS:
return "SUCCESS";
case STATUS_BAD_REQUEST:
return "BAD_REQUEST";
case STATUS_NOT_ACCEPTABLE:
return "NOT_ACCEPTABLE";
case STATUS_LENGTH_REQUIRED:
return "LENGTH_REQUIRED";
case STATUS_PRECONDITION_FAILED:
return "PRECONDITION_FAILED";
case STATUS_FILE_ALREADY_EXISTS_ERROR:
return "FILE_ALREADY_EXISTS_ERROR";
case STATUS_CANNOT_RESUME:
return "CANNOT_RESUME";
case STATUS_CANCELED:
return "CANCELED";
case STATUS_UNKNOWN_ERROR:
return "UNKNOWN_ERROR";
case STATUS_FILE_ERROR:
return "FILE_ERROR";
case STATUS_UNHANDLED_REDIRECT:
return "UNHANDLED_REDIRECT";
case STATUS_UNHANDLED_HTTP_CODE:
return "UNHANDLED_HTTP_CODE";
case STATUS_HTTP_DATA_ERROR:
return "HTTP_DATA_ERROR";
case STATUS_HTTP_EXCEPTION:
return "HTTP_EXCEPTION";
case STATUS_TOO_MANY_REDIRECTS:
return "TOO_MANY_REDIRECTS";
case STATUS_BLOCKED:
return "BLOCKED";
default:
return Integer.toString(status);
}
}
/**
* This download is visible but only shows in the notifications
* while it's in progress.
*/
public static final int VISIBILITY_VISIBLE = DownloadManager.Request.VISIBILITY_VISIBLE;
/**
* This download is visible and shows in the notifications while
* in progress and after completion.
*/
public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED =
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED;
/**
* This download doesn't show in the UI or in the notifications.
*/
public static final int VISIBILITY_HIDDEN = DownloadManager.Request.VISIBILITY_HIDDEN;
/**
* Constants related to HTTP request headers associated with each download.
*/
public static class RequestHeaders {
public static final String HEADERS_DB_TABLE = "request_headers";
public static final String COLUMN_DOWNLOAD_ID = "download_id";
public static final String COLUMN_HEADER = "header";
public static final String COLUMN_VALUE = "value";
/**
* Path segment to add to a download URI to retrieve request headers
*/
public static final String URI_SEGMENT = "headers";
/**
* Prefix for ContentValues keys that contain HTTP header lines, to be passed to
* DownloadProvider.insert().
*/
public static final String INSERT_KEY_PREFIX = "http_header_";
}
}
/**
* Query where clause for general querying.
*/
private static final String QUERY_WHERE_CLAUSE = Impl.COLUMN_NOTIFICATION_PACKAGE + "=? AND "
+ Impl.COLUMN_NOTIFICATION_CLASS + "=?";
/**
* Delete all the downloads for a package/class pair.
*/
public static final void removeAllDownloadsByPackage(
Context context, String notification_package, String notification_class) {
context.getContentResolver().delete(Impl.CONTENT_URI, QUERY_WHERE_CLAUSE,
new String[]{notification_package, notification_class});
}
}
@@ -1,56 +0,0 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Denotes that the class, method or field has its visibility relaxed so
* that unit tests can access it.
* <p/>
* The <code>visibility</code> argument can be used to specific what the original
* visibility should have been if it had not been made public or package-private for testing.
* The default is to consider the element private.
*/
@Retention(RetentionPolicy.SOURCE)
public @interface VisibleForTesting {
/**
* Intended visibility if the element had not been made public or package-private for
* testing.
*/
enum Visibility {
/**
* The element should be considered protected.
*/
PROTECTED,
/**
* The element should be considered package-private.
*/
PACKAGE,
/**
* The element should be considered private.
*/
PRIVATE
}
/**
* Intended visibility if the element had not been made public or package-private for testing.
* If not specified, one should assume the element originally intended to be private.
*/
Visibility visibility() default Visibility.PRIVATE;
}
@@ -1,95 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.net;
import android.app.PendingIntent;
import android.net.NetworkInfo;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
/**
* A simple container used to carry information of the ongoing legacy VPN.
* Internal use only.
*
* @hide
*/
public class LegacyVpnInfo implements Parcelable {
private static final String TAG = "LegacyVpnInfo";
public static final int STATE_DISCONNECTED = 0;
public static final int STATE_INITIALIZING = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
public static final int STATE_TIMEOUT = 4;
public static final int STATE_FAILED = 5;
public String key;
public int state = -1;
public PendingIntent intent;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(key);
out.writeInt(state);
out.writeParcelable(intent, flags);
}
public static final Parcelable.Creator<LegacyVpnInfo> CREATOR =
new Parcelable.Creator<LegacyVpnInfo>() {
@Override
public LegacyVpnInfo createFromParcel(Parcel in) {
LegacyVpnInfo info = new LegacyVpnInfo();
info.key = in.readString();
info.state = in.readInt();
info.intent = in.readParcelable(null);
return info;
}
@Override
public LegacyVpnInfo[] newArray(int size) {
return new LegacyVpnInfo[size];
}
};
/**
* Return best matching {@link com.android.internal.net.LegacyVpnInfo} state based on given
* {@link NetworkInfo}.
*/
public static int stateFromNetworkInfo(NetworkInfo info) {
switch (info.getDetailedState()) {
case CONNECTING:
return STATE_CONNECTING;
case CONNECTED:
return STATE_CONNECTED;
case DISCONNECTED:
return STATE_DISCONNECTED;
case FAILED:
return STATE_FAILED;
default:
Log.w(TAG, "Unhandled state " + info.getDetailedState()
+ " ; treating as disconnected");
return STATE_DISCONNECTED;
}
}
}
@@ -1,117 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.net;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import com.android.internal.util.Preconditions;
import java.util.List;
/**
* A simple container used to carry information in VpnBuilder, VpnDialogs,
* and com.android.server.connectivity.Vpn. Internal use only.
*
* @hide
*/
public class VpnConfig implements Parcelable {
public static final String SERVICE_INTERFACE = "android.net.VpnService";
public static final String DIALOGS_PACKAGE = "com.android.vpndialogs";
public static final String LEGACY_VPN = "[Legacy VPN]";
public static Intent getIntentForConfirmation() {
Intent intent = new Intent();
intent.setClassName(DIALOGS_PACKAGE, DIALOGS_PACKAGE + ".ConfirmDialog");
return intent;
}
public static PendingIntent getIntentForStatusPanel(Context context, VpnConfig config) {
Preconditions.checkNotNull(config);
Intent intent = new Intent();
intent.setClassName(DIALOGS_PACKAGE, DIALOGS_PACKAGE + ".ManageDialog");
intent.putExtra("config", config);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
public String user;
public String interfaze;
public String session;
public int mtu = -1;
public String addresses;
public String routes;
public List<String> dnsServers;
public List<String> searchDomains;
public PendingIntent configureIntent;
public long startTime = -1;
public boolean legacy;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(user);
out.writeString(interfaze);
out.writeString(session);
out.writeInt(mtu);
out.writeString(addresses);
out.writeString(routes);
out.writeStringList(dnsServers);
out.writeStringList(searchDomains);
out.writeParcelable(configureIntent, flags);
out.writeLong(startTime);
out.writeInt(legacy ? 1 : 0);
}
public static final Parcelable.Creator<VpnConfig> CREATOR =
new Parcelable.Creator<VpnConfig>() {
@Override
public VpnConfig createFromParcel(Parcel in) {
VpnConfig config = new VpnConfig();
config.user = in.readString();
config.interfaze = in.readString();
config.session = in.readString();
config.mtu = in.readInt();
config.addresses = in.readString();
config.routes = in.readString();
config.dnsServers = in.createStringArrayList();
config.searchDomains = in.createStringArrayList();
config.configureIntent = in.readParcelable(null);
config.startTime = in.readLong();
config.legacy = in.readInt() != 0;
return config;
}
@Override
public VpnConfig[] newArray(int size) {
return new VpnConfig[size];
}
};
}
@@ -1,203 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.net;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import java.nio.charset.Charset;
/**
* Parcel-like entity class for VPN profiles. To keep things simple, all
* fields are package private. Methods are provided for serialization, so
* storage can be implemented easily. Two rules are set for this class.
* First, all fields must be kept non-null. Second, always make a copy
* using clone() before modifying.
*
* @hide
*/
public class VpnProfile implements Cloneable, Parcelable {
private static final String TAG = "VpnProfile";
// Match these constants with R.array.vpn_types.
public static final int TYPE_PPTP = 0;
public static final int TYPE_L2TP_IPSEC_PSK = 1;
public static final int TYPE_L2TP_IPSEC_RSA = 2;
public static final int TYPE_IPSEC_XAUTH_PSK = 3;
public static final int TYPE_IPSEC_XAUTH_RSA = 4;
public static final int TYPE_IPSEC_HYBRID_RSA = 5;
public static final int TYPE_MAX = 5;
// Entity fields.
public final String key; // -1
public String name = ""; // 0
public int type = TYPE_PPTP; // 1
public String server = ""; // 2
public String username = ""; // 3
public String password = ""; // 4
public String dnsServers = ""; // 5
public String searchDomains = ""; // 6
public String routes = ""; // 7
public boolean mppe = true; // 8
public String l2tpSecret = ""; // 9
public String ipsecIdentifier = "";// 10
public String ipsecSecret = ""; // 11
public String ipsecUserCert = ""; // 12
public String ipsecCaCert = ""; // 13
public String ipsecServerCert = "";// 14
// Helper fields.
public boolean saveLogin = false;
public VpnProfile(String key) {
this.key = key;
}
public VpnProfile(Parcel in) {
key = in.readString();
name = in.readString();
type = in.readInt();
server = in.readString();
username = in.readString();
password = in.readString();
dnsServers = in.readString();
searchDomains = in.readString();
routes = in.readString();
mppe = in.readInt() != 0;
l2tpSecret = in.readString();
ipsecIdentifier = in.readString();
ipsecSecret = in.readString();
ipsecUserCert = in.readString();
ipsecCaCert = in.readString();
ipsecServerCert = in.readString();
saveLogin = in.readInt() != 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(key);
out.writeString(name);
out.writeInt(type);
out.writeString(server);
out.writeString(username);
out.writeString(password);
out.writeString(dnsServers);
out.writeString(searchDomains);
out.writeString(routes);
out.writeInt(mppe ? 1 : 0);
out.writeString(l2tpSecret);
out.writeString(ipsecIdentifier);
out.writeString(ipsecSecret);
out.writeString(ipsecUserCert);
out.writeString(ipsecCaCert);
out.writeString(ipsecServerCert);
out.writeInt(saveLogin ? 1 : 0);
}
public static VpnProfile decode(String key, byte[] value) {
try {
if (key == null) {
return null;
}
String[] values = new String(value, Charset.forName("UTF-8")).split("\0", -1);
// There can be 14 or 15 values in ICS MR1.
if (values.length < 14 || values.length > 15) {
return null;
}
VpnProfile profile = new VpnProfile(key);
profile.name = values[0];
profile.type = Integer.valueOf(values[1]);
if (profile.type < 0 || profile.type > TYPE_MAX) {
return null;
}
profile.server = values[2];
profile.username = values[3];
profile.password = values[4];
profile.dnsServers = values[5];
profile.searchDomains = values[6];
profile.routes = values[7];
profile.mppe = Boolean.valueOf(values[8]);
profile.l2tpSecret = values[9];
profile.ipsecIdentifier = values[10];
profile.ipsecSecret = values[11];
profile.ipsecUserCert = values[12];
profile.ipsecCaCert = values[13];
profile.ipsecServerCert = (values.length > 14) ? values[14] : "";
profile.saveLogin = !profile.username.isEmpty() || !profile.password.isEmpty();
return profile;
} catch (Exception e) {
// ignore
}
return null;
}
public byte[] encode() {
StringBuilder builder = new StringBuilder(name);
builder.append('\0').append(type);
builder.append('\0').append(server);
builder.append('\0').append(saveLogin ? username : "");
builder.append('\0').append(saveLogin ? password : "");
builder.append('\0').append(dnsServers);
builder.append('\0').append(searchDomains);
builder.append('\0').append(routes);
builder.append('\0').append(mppe);
builder.append('\0').append(l2tpSecret);
builder.append('\0').append(ipsecIdentifier);
builder.append('\0').append(ipsecSecret);
builder.append('\0').append(ipsecUserCert);
builder.append('\0').append(ipsecCaCert);
builder.append('\0').append(ipsecServerCert);
return builder.toString().getBytes(Charset.forName("UTF-8"));
}
/**
* Test if profile is valid for lockdown, which requires IPv4 address for
* both server and DNS. Server hostnames would require using DNS before
* connection.
*/
public boolean isValidLockdownProfile() {
try {
return true;
} catch (IllegalArgumentException e) {
Log.w(TAG, "Invalid address", e);
return false;
}
}
public static final Creator<VpnProfile> CREATOR = new Creator<VpnProfile>() {
@Override
public VpnProfile createFromParcel(Parcel in) {
return new VpnProfile(in);
}
@Override
public VpnProfile[] newArray(int size) {
return new VpnProfile[size];
}
};
@Override
public int describeContents() {
return 0;
}
}
@@ -1,36 +0,0 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
/**
* {@hide}
*/
@SuppressWarnings("serial")
public class EncodeException extends Exception {
public EncodeException() {
super();
}
public EncodeException(String s) {
super(s);
}
public EncodeException(char c) {
super("Unencodable char: '" + c + "'");
}
}
File diff suppressed because it is too large Load Diff
@@ -1,519 +0,0 @@
/*
* Copyright (C) 2006 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import java.io.UnsupportedEncodingException;
/**
* Various methods, useful for dealing with SIM data.
*/
public class IccUtils {
static final String LOG_TAG = "IccUtils";
/**
* Many fields in GSM SIM's are stored as nibble-swizzled BCD
* <p/>
* Assumes left-justified field that may be padded right with 0xf
* values.
* <p/>
* Stops on invalid BCD value, returning string so far
*/
public static String
bcdToString(byte[] data, int offset, int length) {
StringBuilder ret = new StringBuilder(length * 2);
for (int i = offset; i < offset + length; i++) {
int v;
v = data[i] & 0xf;
if (v > 9) break;
ret.append((char) ('0' + v));
v = (data[i] >> 4) & 0xf;
// Some PLMNs have 'f' as high nibble, ignore it
if (v == 0xf) continue;
if (v > 9) break;
ret.append((char) ('0' + v));
}
return ret.toString();
}
/**
* Decode cdma byte into String.
*/
public static String
cdmaBcdToString(byte[] data, int offset, int length) {
StringBuilder ret = new StringBuilder(length);
int count = 0;
for (int i = offset; count < length; i++) {
int v;
v = data[i] & 0xf;
if (v > 9) v = 0;
ret.append((char) ('0' + v));
if (++count == length) break;
v = (data[i] >> 4) & 0xf;
if (v > 9) v = 0;
ret.append((char) ('0' + v));
++count;
}
return ret.toString();
}
/**
* Decodes a GSM-style BCD byte, returning an int ranging from 0-99.
* <p/>
* In GSM land, the least significant BCD digit is stored in the most
* significant nibble.
* <p/>
* Out-of-range digits are treated as 0 for the sake of the time stamp,
* because of this:
* <p/>
* TS 23.040 section 9.2.3.11
* "if the MS receives a non-integer value in the SCTS, it shall
* assume the digit is set to 0 but shall store the entire field
* exactly as received"
*/
public static int
gsmBcdByteToInt(byte b) {
int ret = 0;
// treat out-of-range BCD values as 0
if ((b & 0xf0) <= 0x90) {
ret = (b >> 4) & 0xf;
}
if ((b & 0x0f) <= 0x09) {
ret += (b & 0xf) * 10;
}
return ret;
}
/**
* Decodes a CDMA style BCD byte like {@link gsmBcdByteToInt}, but
* opposite nibble format. The least significant BCD digit
* is in the least significant nibble and the most significant
* is in the most significant nibble.
*/
public static int
cdmaBcdByteToInt(byte b) {
int ret = 0;
// treat out-of-range BCD values as 0
if ((b & 0xf0) <= 0x90) {
ret = ((b >> 4) & 0xf) * 10;
}
if ((b & 0x0f) <= 0x09) {
ret += (b & 0xf);
}
return ret;
}
/**
* Decodes a string field that's formatted like the EF[ADN] alpha
* identifier
* <p/>
* From TS 51.011 10.5.1:
* Coding:
* this alpha tagging shall use either
* - the SMS default 7 bit coded alphabet as defined in
* TS 23.038 [12] with bit 8 set to 0. The alpha identifier
* shall be left justified. Unused bytes shall be set to 'FF'; or
* - one of the UCS2 coded options as defined in annex B.
* <p/>
* Annex B from TS 11.11 V8.13.0:
* 1) If the first octet in the alpha string is '80', then the
* remaining octets are 16 bit UCS2 characters ...
* 2) if the first octet in the alpha string is '81', then the
* second octet contains a value indicating the number of
* characters in the string, and the third octet contains an
* 8 bit number which defines bits 15 to 8 of a 16 bit
* base pointer, where bit 16 is set to zero and bits 7 to 1
* are also set to zero. These sixteen bits constitute a
* base pointer to a "half page" in the UCS2 code space, to be
* used with some or all of the remaining octets in the string.
* The fourth and subsequent octets contain codings as follows:
* If bit 8 of the octet is set to zero, the remaining 7 bits
* of the octet contain a GSM Default Alphabet character,
* whereas if bit 8 of the octet is set to one, then the
* remaining seven bits are an offset value added to the
* 16 bit base pointer defined earlier...
* 3) If the first octet of the alpha string is set to '82', then
* the second octet contains a value indicating the number of
* characters in the string, and the third and fourth octets
* contain a 16 bit number which defines the complete 16 bit
* base pointer to a "half page" in the UCS2 code space...
*/
public static String
adnStringFieldToString(byte[] data, int offset, int length) {
if (length == 0) {
return "";
}
if (length >= 1) {
if (data[offset] == (byte) 0x80) {
int ucslen = (length - 1) / 2;
String ret = null;
try {
ret = new String(data, offset + 1, ucslen * 2, "utf-16be");
} catch (UnsupportedEncodingException ex) {
Log.e(LOG_TAG, "implausible UnsupportedEncodingException",
ex);
}
if (ret != null) {
// trim off trailing FFFF characters
ucslen = ret.length();
while (ucslen > 0 && ret.charAt(ucslen - 1) == '\uFFFF')
ucslen--;
return ret.substring(0, ucslen);
}
}
}
boolean isucs2 = false;
char base = '\0';
int len = 0;
if (length >= 3 && data[offset] == (byte) 0x81) {
len = data[offset + 1] & 0xFF;
if (len > length - 3)
len = length - 3;
base = (char) ((data[offset + 2] & 0xFF) << 7);
offset += 3;
isucs2 = true;
} else if (length >= 4 && data[offset] == (byte) 0x82) {
len = data[offset + 1] & 0xFF;
if (len > length - 4)
len = length - 4;
base = (char) (((data[offset + 2] & 0xFF) << 8) |
(data[offset + 3] & 0xFF));
offset += 4;
isucs2 = true;
}
if (isucs2) {
StringBuilder ret = new StringBuilder();
while (len > 0) {
// UCS2 subset case
if (data[offset] < 0) {
ret.append((char) (base + (data[offset] & 0x7F)));
offset++;
len--;
}
// GSM character set case
int count = 0;
while (count < len && data[offset + count] >= 0)
count++;
ret.append(GsmAlphabet.gsm8BitUnpackedToString(data,
offset, count));
offset += count;
len -= count;
}
return ret.toString();
}
Resources resource = Resources.getSystem();
String defaultCharset = "";
return GsmAlphabet.gsm8BitUnpackedToString(data, offset, length, defaultCharset.trim());
}
static int
hexCharToInt(char c) {
if (c >= '0' && c <= '9') return (c - '0');
if (c >= 'A' && c <= 'F') return (c - 'A' + 10);
if (c >= 'a' && c <= 'f') return (c - 'a' + 10);
throw new RuntimeException("invalid hex char '" + c + "'");
}
/**
* Converts a hex String to a byte array.
*
* @param s A string of hexadecimal characters, must be an even number of
* chars long
* @return byte array representation
* @throws RuntimeException on invalid format
*/
public static byte[]
hexStringToBytes(String s) {
byte[] ret;
if (s == null) return null;
int sz = s.length();
ret = new byte[sz / 2];
for (int i = 0; i < sz; i += 2) {
ret[i / 2] = (byte) ((hexCharToInt(s.charAt(i)) << 4)
| hexCharToInt(s.charAt(i + 1)));
}
return ret;
}
/**
* Converts a byte array into a String of hexadecimal characters.
*
* @param bytes an array of bytes
* @return hex string representation of bytes array
*/
public static String
bytesToHexString(byte[] bytes) {
if (bytes == null) return null;
StringBuilder ret = new StringBuilder(2 * bytes.length);
for (int i = 0; i < bytes.length; i++) {
int b;
b = 0x0f & (bytes[i] >> 4);
ret.append("0123456789abcdef".charAt(b));
b = 0x0f & bytes[i];
ret.append("0123456789abcdef".charAt(b));
}
return ret.toString();
}
/**
* Convert a TS 24.008 Section 10.5.3.5a Network Name field to a string
* "offset" points to "octet 3", the coding scheme byte
* empty string returned on decode error
*/
public static String
networkNameToString(byte[] data, int offset, int length) {
String ret;
if ((data[offset] & 0x80) != 0x80 || length < 1) {
return "";
}
switch ((data[offset] >>> 4) & 0x7) {
case 0:
// SMS character set
int countSeptets;
int unusedBits = data[offset] & 7;
countSeptets = (((length - 1) * 8) - unusedBits) / 7;
ret = GsmAlphabet.gsm7BitPackedToString(data, offset + 1, countSeptets);
break;
case 1:
// UCS2
try {
ret = new String(data,
offset + 1, length - 1, "utf-16");
} catch (UnsupportedEncodingException ex) {
ret = "";
Log.e(LOG_TAG, "implausible UnsupportedEncodingException", ex);
}
break;
// unsupported encoding
default:
ret = "";
break;
}
// "Add CI"
// "The MS should add the letters for the Country's Initials and
// a separator (e.g. a space) to the text string"
if ((data[offset] & 0x40) != 0) {
// FIXME(mkf) add country initials here
}
return ret;
}
/**
* Convert a TS 131.102 image instance of code scheme '11' into Bitmap
*
* @param data The raw data
* @param length The length of image body
* @return The bitmap
*/
public static Bitmap parseToBnW(byte[] data, int length) {
int valueIndex = 0;
int width = data[valueIndex++] & 0xFF;
int height = data[valueIndex++] & 0xFF;
int numOfPixels = width * height;
int[] pixels = new int[numOfPixels];
int pixelIndex = 0;
int bitIndex = 7;
byte currentByte = 0x00;
while (pixelIndex < numOfPixels) {
// reassign data and index for every byte (8 bits).
if (pixelIndex % 8 == 0) {
currentByte = data[valueIndex++];
bitIndex = 7;
}
pixels[pixelIndex++] = bitToRGB((currentByte >> bitIndex--) & 0x01);
}
;
if (pixelIndex != numOfPixels) {
Log.e(LOG_TAG, "parse end and size error");
}
return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
}
private static int bitToRGB(int bit) {
if (bit == 1) {
return Color.WHITE;
} else {
return Color.BLACK;
}
}
/**
* a TS 131.102 image instance of code scheme '11' into color Bitmap
*
* @param data The raw data
* @param length the length of image body
* @param transparency with or without transparency
* @return The color bitmap
*/
public static Bitmap parseToRGB(byte[] data, int length,
boolean transparency) {
int valueIndex = 0;
int width = data[valueIndex++] & 0xFF;
int height = data[valueIndex++] & 0xFF;
int bits = data[valueIndex++] & 0xFF;
int colorNumber = data[valueIndex++] & 0xFF;
int clutOffset = ((data[valueIndex++] & 0xFF) << 8)
| (data[valueIndex++] & 0xFF);
int[] colorIndexArray = getCLUT(data, clutOffset, colorNumber);
if (true == transparency) {
colorIndexArray[colorNumber - 1] = Color.TRANSPARENT;
}
int[] resultArray = null;
if (0 == (8 % bits)) {
resultArray = mapTo2OrderBitColor(data, valueIndex,
(width * height), colorIndexArray, bits);
} else {
resultArray = mapToNon2OrderBitColor(data, valueIndex,
(width * height), colorIndexArray, bits);
}
return Bitmap.createBitmap(resultArray, width, height,
Bitmap.Config.RGB_565);
}
private static int[] mapTo2OrderBitColor(byte[] data, int valueIndex,
int length, int[] colorArray, int bits) {
if (0 != (8 % bits)) {
Log.e(LOG_TAG, "not event number of color");
return mapToNon2OrderBitColor(data, valueIndex, length, colorArray,
bits);
}
int mask = 0x01;
switch (bits) {
case 1:
mask = 0x01;
break;
case 2:
mask = 0x03;
break;
case 4:
mask = 0x0F;
break;
case 8:
mask = 0xFF;
break;
}
int[] resultArray = new int[length];
int resultIndex = 0;
int run = 8 / bits;
while (resultIndex < length) {
byte tempByte = data[valueIndex++];
for (int runIndex = 0; runIndex < run; ++runIndex) {
int offset = run - runIndex - 1;
resultArray[resultIndex++] = colorArray[(tempByte >> (offset * bits))
& mask];
}
}
return resultArray;
}
private static int[] mapToNon2OrderBitColor(byte[] data, int valueIndex,
int length, int[] colorArray, int bits) {
if (0 == (8 % bits)) {
Log.e(LOG_TAG, "not odd number of color");
return mapTo2OrderBitColor(data, valueIndex, length, colorArray,
bits);
}
int[] resultArray = new int[length];
// TODO fix me:
return resultArray;
}
private static int[] getCLUT(byte[] rawData, int offset, int number) {
if (null == rawData) {
return null;
}
int[] result = new int[number];
int endIndex = offset + (number * 3); // 1 color use 3 bytes
int valueIndex = offset;
int colorIndex = 0;
int alpha = 0xff << 24;
do {
result[colorIndex++] = alpha
| ((rawData[valueIndex++] & 0xFF) << 16)
| ((rawData[valueIndex++] & 0xFF) << 8)
| ((rawData[valueIndex++] & 0xFF));
} while (valueIndex < endIndex);
return result;
}
}
@@ -1,190 +0,0 @@
/*
* Copyright (C) 2012 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
/**
* @hide
*/
public class PhoneConstants {
/**
* The phone state. One of the following:<p>
* <ul>
* <li>IDLE = no phone activity</li>
* <li>RINGING = a phone call is ringing or call waiting.
* In the latter case, another call is active as well</li>
* <li>OFFHOOK = The phone is off hook. At least one call
* exists that is dialing, active or holding and no calls are
* ringing or waiting.</li>
* </ul>
*/
public enum State {
IDLE, RINGING, OFFHOOK;
};
/**
* The state of a data connection.
* <ul>
* <li>CONNECTED = IP traffic should be available</li>
* <li>CONNECTING = Currently setting up data connection</li>
* <li>DISCONNECTED = IP not available</li>
* <li>SUSPENDED = connection is created but IP traffic is
* temperately not available. i.e. voice call is in place
* in 2G network</li>
* </ul>
*/
public enum DataState {
CONNECTED, CONNECTING, DISCONNECTED, SUSPENDED;
};
public static final String STATE_KEY = "state";
// Radio Type
public static final int PHONE_TYPE_NONE = RILConstants.NO_PHONE;
public static final int PHONE_TYPE_GSM = RILConstants.GSM_PHONE;
public static final int PHONE_TYPE_CDMA = RILConstants.CDMA_PHONE;
public static final int PHONE_TYPE_SIP = RILConstants.SIP_PHONE;
public static final int PHONE_TYPE_THIRD_PARTY = RILConstants.THIRD_PARTY_PHONE;
public static final int PHONE_TYPE_IMS = RILConstants.IMS_PHONE;
// Modes for LTE_ON_CDMA
public static final int LTE_ON_CDMA_UNKNOWN = RILConstants.LTE_ON_CDMA_UNKNOWN;
public static final int LTE_ON_CDMA_FALSE = RILConstants.LTE_ON_CDMA_FALSE;
public static final int LTE_ON_CDMA_TRUE = RILConstants.LTE_ON_CDMA_TRUE;
// Number presentation type for caller id display (From internal/Connection.java)
public static final int PRESENTATION_ALLOWED = 1; // normal
public static final int PRESENTATION_RESTRICTED = 2; // block by user
public static final int PRESENTATION_UNKNOWN = 3; // no specified or unknown by network
public static final int PRESENTATION_PAYPHONE = 4; // show pay phone info
public static final String PHONE_NAME_KEY = "phoneName";
public static final String FAILURE_REASON_KEY = "reason";
public static final String STATE_CHANGE_REASON_KEY = "reason";
public static final String DATA_NETWORK_TYPE_KEY = "networkType";
public static final String DATA_FAILURE_CAUSE_KEY = "failCause";
public static final String DATA_APN_TYPE_KEY = "apnType";
public static final String DATA_APN_KEY = "apn";
public static final String DATA_LINK_PROPERTIES_KEY = "linkProperties";
public static final String DATA_NETWORK_CAPABILITIES_KEY = "networkCapabilities";
public static final String DATA_IFACE_NAME_KEY = "iface";
public static final String NETWORK_UNAVAILABLE_KEY = "networkUnvailable";
public static final String DATA_NETWORK_ROAMING_KEY = "networkRoaming";
public static final String PHONE_IN_ECM_STATE = "phoneinECMState";
public static final String REASON_LINK_PROPERTIES_CHANGED = "linkPropertiesChanged";
/**
* Return codes for supplyPinReturnResult and
* supplyPukReturnResult APIs
*/
public static final int PIN_RESULT_SUCCESS = 0;
public static final int PIN_PASSWORD_INCORRECT = 1;
public static final int PIN_GENERAL_FAILURE = 2;
/**
* Return codes for <code>enableApnType()</code>
*/
public static final int APN_ALREADY_ACTIVE = 0;
public static final int APN_REQUEST_STARTED = 1;
public static final int APN_TYPE_NOT_AVAILABLE = 2;
public static final int APN_REQUEST_FAILED = 3;
public static final int APN_ALREADY_INACTIVE = 4;
/**
* APN types for data connections. These are usage categories for an APN
* entry. One APN entry may support multiple APN types, eg, a single APN
* may service regular internet traffic ("default") as well as MMS-specific
* connections.<br/>
* APN_TYPE_ALL is a special type to indicate that this APN entry can
* service all data connections.
*/
public static final String APN_TYPE_ALL = "*";
/** APN type for default data traffic */
public static final String APN_TYPE_DEFAULT = "default";
/** APN type for MMS traffic */
public static final String APN_TYPE_MMS = "mms";
/** APN type for SUPL assisted GPS */
public static final String APN_TYPE_SUPL = "supl";
/** APN type for DUN traffic */
public static final String APN_TYPE_DUN = "dun";
/** APN type for HiPri traffic */
public static final String APN_TYPE_HIPRI = "hipri";
/** APN type for FOTA */
public static final String APN_TYPE_FOTA = "fota";
/** APN type for IMS */
public static final String APN_TYPE_IMS = "ims";
/** APN type for CBS */
public static final String APN_TYPE_CBS = "cbs";
/** APN type for IA Initial Attach APN */
public static final String APN_TYPE_IA = "ia";
/** APN type for IA Emergency PDN */
public static final String APN_TYPE_EMERGENCY = "emergency";
public static final int RIL_CARD_MAX_APPS = 8;
public static final int DEFAULT_CARD_INDEX = 0;
public static final int MAX_PHONE_COUNT_SINGLE_SIM = 1;
public static final int MAX_PHONE_COUNT_DUAL_SIM = 2;
public static final int MAX_PHONE_COUNT_TRI_SIM = 3;
public static final String PHONE_KEY = "phone";
public static final String SLOT_KEY = "slot";
// FIXME: This is used to pass a subId via intents, we need to look at its usage, which is
// FIXME: extensive, and see if this should be an array of all active subId's or ...?
public static final String SUBSCRIPTION_KEY = "subscription";
public static final String SUB_SETTING = "subSettings";
public static final int SUB1 = 0;
public static final int SUB2 = 1;
public static final int SUB3 = 2;
public static final int EVENT_SUBSCRIPTION_ACTIVATED = 500;
public static final int EVENT_SUBSCRIPTION_DEACTIVATED = 501;
// TODO: Remove these constants and use an int instead.
public static final int SIM_ID_1 = 0;
public static final int SIM_ID_2 = 1;
public static final int SIM_ID_3 = 2;
public static final int SIM_ID_4 = 3;
// ICC SIM Application Types
// TODO: Replace the IccCardApplicationStatus.AppType enums with these constants
public static final int APPTYPE_UNKNOWN = 0;
public static final int APPTYPE_SIM = 1;
public static final int APPTYPE_USIM = 2;
public static final int APPTYPE_RUIM = 3;
public static final int APPTYPE_CSIM = 4;
public static final int APPTYPE_ISIM = 5;
public enum CardUnavailableReason {
REASON_CARD_REMOVED,
REASON_RADIO_UNAVAILABLE,
REASON_SIM_REFRESH_RESET
};
// Initial MTU value.
public static final int UNSET_MTU = 0;
}
@@ -1,338 +0,0 @@
/*
* Copyright (C) 2006 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
/**
* TODO: This should probably not be an interface see
* http://www.javaworld.com/javaworld/javaqa/2001-06/01-qa-0608-constants.html and google with
* http://www.google.com/search?q=interface+constants&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a
*
* Also they should all probably be static final.
*/
/**
* {@hide}
*/
public interface RILConstants {
// From the top of ril.cpp
int RIL_ERRNO_INVALID_RESPONSE = -1;
int MAX_INT = 0x7FFFFFFF;
// from RIL_Errno
int SUCCESS = 0;
int RADIO_NOT_AVAILABLE = 1; /* If radio did not start or is resetting */
int GENERIC_FAILURE = 2;
int PASSWORD_INCORRECT = 3; /* for PIN/PIN2 methods only! */
int SIM_PIN2 = 4; /* Operation requires SIM PIN2 to be entered */
int SIM_PUK2 = 5; /* Operation requires SIM PIN2 to be entered */
int REQUEST_NOT_SUPPORTED = 6;
int REQUEST_CANCELLED = 7;
int OP_NOT_ALLOWED_DURING_VOICE_CALL = 8; /* data operation is not allowed during voice call in
class C */
int OP_NOT_ALLOWED_BEFORE_REG_NW = 9; /* request is not allowed before device registers to
network */
int SMS_SEND_FAIL_RETRY = 10; /* send sms fail and need retry */
int SIM_ABSENT = 11; /* ICC card is absent */
int SUBSCRIPTION_NOT_AVAILABLE = 12; /* fail to find CDMA subscription from specified
location */
int MODE_NOT_SUPPORTED = 13; /* HW does not support preferred network type */
int FDN_CHECK_FAILURE = 14; /* send operation barred error when FDN is enabled */
int ILLEGAL_SIM_OR_ME = 15; /* network selection failure due
to wrong SIM/ME and no
retries needed */
int MISSING_RESOURCE = 16; /* no logical channel available */
int NO_SUCH_ELEMENT = 17; /* application not found on SIM */
int SUBSCRIPTION_NOT_SUPPORTED = 26; /* Subscription not supported */
/* NETWORK_MODE_* See ril.h RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE */
int NETWORK_MODE_WCDMA_PREF = 0; /* GSM/WCDMA (WCDMA preferred) */
int NETWORK_MODE_GSM_ONLY = 1; /* GSM only */
int NETWORK_MODE_WCDMA_ONLY = 2; /* WCDMA only */
int NETWORK_MODE_GSM_UMTS = 3; /* GSM/WCDMA (auto mode, according to PRL)
AVAILABLE Application Settings menu*/
int NETWORK_MODE_CDMA = 4; /* CDMA and EvDo (auto mode, according to PRL)
AVAILABLE Application Settings menu*/
int NETWORK_MODE_CDMA_NO_EVDO = 5; /* CDMA only */
int NETWORK_MODE_EVDO_NO_CDMA = 6; /* EvDo only */
int NETWORK_MODE_GLOBAL = 7; /* GSM/WCDMA, CDMA, and EvDo (auto mode, according to PRL)
AVAILABLE Application Settings menu*/
int NETWORK_MODE_LTE_CDMA_EVDO = 8; /* LTE, CDMA and EvDo */
int NETWORK_MODE_LTE_GSM_WCDMA = 9; /* LTE, GSM/WCDMA */
int NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA = 10; /* LTE, CDMA, EvDo, GSM/WCDMA */
int NETWORK_MODE_LTE_ONLY = 11; /* LTE Only mode. */
int NETWORK_MODE_LTE_WCDMA = 12; /* LTE/WCDMA */
int PREFERRED_NETWORK_MODE = NETWORK_MODE_WCDMA_PREF;
int CDMA_CELL_BROADCAST_SMS_DISABLED = 1;
int CDMA_CELL_BROADCAST_SMS_ENABLED = 0;
int NO_PHONE = 0;
int GSM_PHONE = 1;
int CDMA_PHONE = 2;
int SIP_PHONE = 3;
int THIRD_PARTY_PHONE = 4;
int IMS_PHONE = 5;
int LTE_ON_CDMA_UNKNOWN = -1;
int LTE_ON_CDMA_FALSE = 0;
int LTE_ON_CDMA_TRUE = 1;
int CDM_TTY_MODE_DISABLED = 0;
int CDM_TTY_MODE_ENABLED = 1;
int CDM_TTY_FULL_MODE = 1;
int CDM_TTY_HCO_MODE = 2;
int CDM_TTY_VCO_MODE = 3;
/* Setup a packet data connection. See ril.h RIL_REQUEST_SETUP_DATA_CALL */
int SETUP_DATA_TECH_CDMA = 0;
int SETUP_DATA_TECH_GSM = 1;
int SETUP_DATA_AUTH_NONE = 0;
int SETUP_DATA_AUTH_PAP = 1;
int SETUP_DATA_AUTH_CHAP = 2;
int SETUP_DATA_AUTH_PAP_CHAP = 3;
String SETUP_DATA_PROTOCOL_IP = "IP";
String SETUP_DATA_PROTOCOL_IPV6 = "IPV6";
String SETUP_DATA_PROTOCOL_IPV4V6 = "IPV4V6";
/* Deactivate data call reasons */
int DEACTIVATE_REASON_NONE = 0;
int DEACTIVATE_REASON_RADIO_OFF = 1;
int DEACTIVATE_REASON_PDP_RESET = 2;
/* NV config radio reset types. */
int NV_CONFIG_RELOAD_RESET = 1;
int NV_CONFIG_ERASE_RESET = 2;
int NV_CONFIG_FACTORY_RESET = 3;
/*
cat include/telephony/ril.h | \
egrep '^#define' | \
sed -re 's/^#define +([^ ]+)* +([^ ]+)/ int \1 = \2;/' \
>>java/android/com.android.internal.telephony/gsm/RILConstants.java
*/
/**
* No restriction at all including voice/SMS/USSD/SS/AV64
* and packet data.
*/
int RIL_RESTRICTED_STATE_NONE = 0x00;
/**
* Block emergency call due to restriction.
* But allow all normal voice/SMS/USSD/SS/AV64.
*/
int RIL_RESTRICTED_STATE_CS_EMERGENCY = 0x01;
/**
* Block all normal voice/SMS/USSD/SS/AV64 due to restriction.
* Only Emergency call allowed.
*/
int RIL_RESTRICTED_STATE_CS_NORMAL = 0x02;
/**
* Block all voice/SMS/USSD/SS/AV64
* including emergency call due to restriction.
*/
int RIL_RESTRICTED_STATE_CS_ALL = 0x04;
/**
* Block packet data access due to restriction.
*/
int RIL_RESTRICTED_STATE_PS_ALL = 0x10;
/** Data profile for RIL_REQUEST_SETUP_DATA_CALL */
public static final int DATA_PROFILE_DEFAULT = 0;
public static final int DATA_PROFILE_TETHERED = 1;
public static final int DATA_PROFILE_IMS = 2;
public static final int DATA_PROFILE_FOTA = 3;
public static final int DATA_PROFILE_CBS = 4;
public static final int DATA_PROFILE_OEM_BASE = 1000;
int RIL_REQUEST_GET_SIM_STATUS = 1;
int RIL_REQUEST_ENTER_SIM_PIN = 2;
int RIL_REQUEST_ENTER_SIM_PUK = 3;
int RIL_REQUEST_ENTER_SIM_PIN2 = 4;
int RIL_REQUEST_ENTER_SIM_PUK2 = 5;
int RIL_REQUEST_CHANGE_SIM_PIN = 6;
int RIL_REQUEST_CHANGE_SIM_PIN2 = 7;
int RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION = 8;
int RIL_REQUEST_GET_CURRENT_CALLS = 9;
int RIL_REQUEST_DIAL = 10;
int RIL_REQUEST_GET_IMSI = 11;
int RIL_REQUEST_HANGUP = 12;
int RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND = 13;
int RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND = 14;
int RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE = 15;
int RIL_REQUEST_CONFERENCE = 16;
int RIL_REQUEST_UDUB = 17;
int RIL_REQUEST_LAST_CALL_FAIL_CAUSE = 18;
int RIL_REQUEST_SIGNAL_STRENGTH = 19;
int RIL_REQUEST_VOICE_REGISTRATION_STATE = 20;
int RIL_REQUEST_DATA_REGISTRATION_STATE = 21;
int RIL_REQUEST_OPERATOR = 22;
int RIL_REQUEST_RADIO_POWER = 23;
int RIL_REQUEST_DTMF = 24;
int RIL_REQUEST_SEND_SMS = 25;
int RIL_REQUEST_SEND_SMS_EXPECT_MORE = 26;
int RIL_REQUEST_SETUP_DATA_CALL = 27;
int RIL_REQUEST_SIM_IO = 28;
int RIL_REQUEST_SEND_USSD = 29;
int RIL_REQUEST_CANCEL_USSD = 30;
int RIL_REQUEST_GET_CLIR = 31;
int RIL_REQUEST_SET_CLIR = 32;
int RIL_REQUEST_QUERY_CALL_FORWARD_STATUS = 33;
int RIL_REQUEST_SET_CALL_FORWARD = 34;
int RIL_REQUEST_QUERY_CALL_WAITING = 35;
int RIL_REQUEST_SET_CALL_WAITING = 36;
int RIL_REQUEST_SMS_ACKNOWLEDGE = 37;
int RIL_REQUEST_GET_IMEI = 38;
int RIL_REQUEST_GET_IMEISV = 39;
int RIL_REQUEST_ANSWER = 40;
int RIL_REQUEST_DEACTIVATE_DATA_CALL = 41;
int RIL_REQUEST_QUERY_FACILITY_LOCK = 42;
int RIL_REQUEST_SET_FACILITY_LOCK = 43;
int RIL_REQUEST_CHANGE_BARRING_PASSWORD = 44;
int RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE = 45;
int RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC = 46;
int RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL = 47;
int RIL_REQUEST_QUERY_AVAILABLE_NETWORKS = 48;
int RIL_REQUEST_DTMF_START = 49;
int RIL_REQUEST_DTMF_STOP = 50;
int RIL_REQUEST_BASEBAND_VERSION = 51;
int RIL_REQUEST_SEPARATE_CONNECTION = 52;
int RIL_REQUEST_SET_MUTE = 53;
int RIL_REQUEST_GET_MUTE = 54;
int RIL_REQUEST_QUERY_CLIP = 55;
int RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE = 56;
int RIL_REQUEST_DATA_CALL_LIST = 57;
int RIL_REQUEST_RESET_RADIO = 58;
int RIL_REQUEST_OEM_HOOK_RAW = 59;
int RIL_REQUEST_OEM_HOOK_STRINGS = 60;
int RIL_REQUEST_SCREEN_STATE = 61;
int RIL_REQUEST_SET_SUPP_SVC_NOTIFICATION = 62;
int RIL_REQUEST_WRITE_SMS_TO_SIM = 63;
int RIL_REQUEST_DELETE_SMS_ON_SIM = 64;
int RIL_REQUEST_SET_BAND_MODE = 65;
int RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE = 66;
int RIL_REQUEST_STK_GET_PROFILE = 67;
int RIL_REQUEST_STK_SET_PROFILE = 68;
int RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND = 69;
int RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE = 70;
int RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM = 71;
int RIL_REQUEST_EXPLICIT_CALL_TRANSFER = 72;
int RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE = 73;
int RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE = 74;
int RIL_REQUEST_GET_NEIGHBORING_CELL_IDS = 75;
int RIL_REQUEST_SET_LOCATION_UPDATES = 76;
int RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE = 77;
int RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE = 78;
int RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE = 79;
int RIL_REQUEST_SET_TTY_MODE = 80;
int RIL_REQUEST_QUERY_TTY_MODE = 81;
int RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE = 82;
int RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE = 83;
int RIL_REQUEST_CDMA_FLASH = 84;
int RIL_REQUEST_CDMA_BURST_DTMF = 85;
int RIL_REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY = 86;
int RIL_REQUEST_CDMA_SEND_SMS = 87;
int RIL_REQUEST_CDMA_SMS_ACKNOWLEDGE = 88;
int RIL_REQUEST_GSM_GET_BROADCAST_CONFIG = 89;
int RIL_REQUEST_GSM_SET_BROADCAST_CONFIG = 90;
int RIL_REQUEST_GSM_BROADCAST_ACTIVATION = 91;
int RIL_REQUEST_CDMA_GET_BROADCAST_CONFIG = 92;
int RIL_REQUEST_CDMA_SET_BROADCAST_CONFIG = 93;
int RIL_REQUEST_CDMA_BROADCAST_ACTIVATION = 94;
int RIL_REQUEST_CDMA_SUBSCRIPTION = 95;
int RIL_REQUEST_CDMA_WRITE_SMS_TO_RUIM = 96;
int RIL_REQUEST_CDMA_DELETE_SMS_ON_RUIM = 97;
int RIL_REQUEST_DEVICE_IDENTITY = 98;
int RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE = 99;
int RIL_REQUEST_GET_SMSC_ADDRESS = 100;
int RIL_REQUEST_SET_SMSC_ADDRESS = 101;
int RIL_REQUEST_REPORT_SMS_MEMORY_STATUS = 102;
int RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING = 103;
int RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE = 104;
int RIL_REQUEST_ISIM_AUTHENTICATION = 105;
int RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU = 106;
int RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS = 107;
int RIL_REQUEST_VOICE_RADIO_TECH = 108;
int RIL_REQUEST_GET_CELL_INFO_LIST = 109;
int RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE = 110;
int RIL_REQUEST_SET_INITIAL_ATTACH_APN = 111;
int RIL_REQUEST_IMS_REGISTRATION_STATE = 112;
int RIL_REQUEST_IMS_SEND_SMS = 113;
int RIL_REQUEST_SIM_TRANSMIT_APDU_BASIC = 114;
int RIL_REQUEST_SIM_OPEN_CHANNEL = 115;
int RIL_REQUEST_SIM_CLOSE_CHANNEL = 116;
int RIL_REQUEST_SIM_TRANSMIT_APDU_CHANNEL = 117;
int RIL_REQUEST_NV_READ_ITEM = 118;
int RIL_REQUEST_NV_WRITE_ITEM = 119;
int RIL_REQUEST_NV_WRITE_CDMA_PRL = 120;
int RIL_REQUEST_NV_RESET_CONFIG = 121;
int RIL_REQUEST_SET_UICC_SUBSCRIPTION = 122;
int RIL_REQUEST_ALLOW_DATA = 123;
int RIL_REQUEST_GET_HARDWARE_CONFIG = 124;
int RIL_REQUEST_SIM_AUTHENTICATION = 125;
int RIL_REQUEST_GET_DC_RT_INFO = 126;
int RIL_REQUEST_SET_DC_RT_INFO_RATE = 127;
int RIL_REQUEST_SET_DATA_PROFILE = 128;
int RIL_REQUEST_SHUTDOWN = 129;
int RIL_UNSOL_RESPONSE_BASE = 1000;
int RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED = 1000;
int RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED = 1001;
int RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED = 1002;
int RIL_UNSOL_RESPONSE_NEW_SMS = 1003;
int RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT = 1004;
int RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM = 1005;
int RIL_UNSOL_ON_USSD = 1006;
int RIL_UNSOL_ON_USSD_REQUEST = 1007;
int RIL_UNSOL_NITZ_TIME_RECEIVED = 1008;
int RIL_UNSOL_SIGNAL_STRENGTH = 1009;
int RIL_UNSOL_DATA_CALL_LIST_CHANGED = 1010;
int RIL_UNSOL_SUPP_SVC_NOTIFICATION = 1011;
int RIL_UNSOL_STK_SESSION_END = 1012;
int RIL_UNSOL_STK_PROACTIVE_COMMAND = 1013;
int RIL_UNSOL_STK_EVENT_NOTIFY = 1014;
int RIL_UNSOL_STK_CALL_SETUP = 1015;
int RIL_UNSOL_SIM_SMS_STORAGE_FULL = 1016;
int RIL_UNSOL_SIM_REFRESH = 1017;
int RIL_UNSOL_CALL_RING = 1018;
int RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED = 1019;
int RIL_UNSOL_RESPONSE_CDMA_NEW_SMS = 1020;
int RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS = 1021;
int RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL = 1022;
int RIL_UNSOL_RESTRICTED_STATE_CHANGED = 1023;
int RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE = 1024;
int RIL_UNSOL_CDMA_CALL_WAITING = 1025;
int RIL_UNSOL_CDMA_OTA_PROVISION_STATUS = 1026;
int RIL_UNSOL_CDMA_INFO_REC = 1027;
int RIL_UNSOL_OEM_HOOK_RAW = 1028;
int RIL_UNSOL_RINGBACK_TONE = 1029;
int RIL_UNSOL_RESEND_INCALL_MUTE = 1030;
int RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED = 1031;
int RIL_UNSOl_CDMA_PRL_CHANGED = 1032;
int RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE = 1033;
int RIL_UNSOL_RIL_CONNECTED = 1034;
int RIL_UNSOL_VOICE_RADIO_TECH_CHANGED = 1035;
int RIL_UNSOL_CELL_INFO_LIST = 1036;
int RIL_UNSOL_RESPONSE_IMS_NETWORK_STATE_CHANGED = 1037;
int RIL_UNSOL_UICC_SUBSCRIPTION_STATUS_CHANGED = 1038;
int RIL_UNSOL_SRVCC_STATE_NOTIFY = 1039;
int RIL_UNSOL_HARDWARE_CONFIG_CHANGED = 1040;
}
@@ -1,83 +0,0 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
/**
* SMS Constants and must be the same as the corresponding
* deprecated version in SmsMessage.
*
* @hide
*/
public class SmsConstants {
/**
* User data text encoding code unit size
*/
public static final int ENCODING_UNKNOWN = 0;
public static final int ENCODING_7BIT = 1;
public static final int ENCODING_8BIT = 2;
public static final int ENCODING_16BIT = 3;
/**
* The maximum number of payload septets per message
*/
public static final int MAX_USER_DATA_SEPTETS = 160;
/**
* The maximum number of payload septets per message if a user data header
* is present. This assumes the header only contains the
* CONCATENATED_8_BIT_REFERENCE element.
*/
public static final int MAX_USER_DATA_SEPTETS_WITH_HEADER = 153;
/**
* This value is not defined in global standard. Only in Korea, this is used.
*/
public static final int ENCODING_KSC5601 = 4;
/**
* The maximum number of payload bytes per message
*/
public static final int MAX_USER_DATA_BYTES = 140;
/**
* The maximum number of payload bytes per message if a user data header
* is present. This assumes the header only contains the
* CONCATENATED_8_BIT_REFERENCE element.
*/
public static final int MAX_USER_DATA_BYTES_WITH_HEADER = 134;
/**
* SMS Class enumeration.
* See TS 23.038.
*/
public enum MessageClass {
UNKNOWN, CLASS_0, CLASS_1, CLASS_2, CLASS_3;
}
/**
* Indicates a 3GPP format SMS message.
*
* @hide pending API council approval
*/
public static final String FORMAT_3GPP = "3gpp";
/**
* Indicates a 3GPP2 format SMS message.
*
* @hide pending API council approval
*/
public static final String FORMAT_3GPP2 = "3gpp2";
}
@@ -1,207 +0,0 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
/**
* Contains a list of string constants used to get or set telephone properties
* in the system. You can use {@link android.os.SystemProperties os.SystemProperties}
* to get and set these values.
*
* @hide
*/
public interface TelephonyProperties {
//****** Baseband and Radio Interface version
//TODO T: property strings do not have to be gsm specific
// change gsm.*operator.*" properties to "operator.*" properties
/**
* Baseband version
* Availability: property is available any time radio is on
*/
static final String PROPERTY_BASEBAND_VERSION = "gsm.version.baseband";
/**
* Radio Interface Layer (RIL) library implementation.
*/
static final String PROPERTY_RIL_IMPL = "gsm.version.ril-impl";
//****** Current Network
/**
* Alpha name of current registered operator.<p>
* Availability: when registered to a network. Result may be unreliable on
* CDMA networks.
*/
static final String PROPERTY_OPERATOR_ALPHA = "gsm.operator.alpha";
//TODO: most of these properties are generic, substitute gsm. with phone. bug 1856959
/**
* Numeric name (MCC+MNC) of current registered operator.<p>
* Availability: when registered to a network. Result may be unreliable on
* CDMA networks.
*/
static final String PROPERTY_OPERATOR_NUMERIC = "gsm.operator.numeric";
/**
* 'true' if the device is on a manually selected network
* <p/>
* Availability: when registered to a network
*/
static final String PROPERTY_OPERATOR_ISMANUAL = "operator.ismanual";
/**
* 'true' if the device is considered roaming on this network for GSM
* purposes.
* Availability: when registered to a network
*/
static final String PROPERTY_OPERATOR_ISROAMING = "gsm.operator.isroaming";
/**
* The ISO country code equivalent of the current registered operator's
* MCC (Mobile Country Code)<p>
* Availability: when registered to a network. Result may be unreliable on
* CDMA networks.
*/
static final String PROPERTY_OPERATOR_ISO_COUNTRY = "gsm.operator.iso-country";
/**
* The contents of this property is the value of the kernel command line
* product_type variable that corresponds to a product that supports LTE on CDMA.
* {@see BaseCommands#getLteOnCdmaMode()}
*/
static final String PROPERTY_LTE_ON_CDMA_PRODUCT_TYPE = "telephony.lteOnCdmaProductType";
/**
* The contents of this property is the one of {@link Phone#LTE_ON_CDMA_TRUE} or
* {@link Phone#LTE_ON_CDMA_FALSE}. If absent the value will assumed to be false
* and the {@see #PROPERTY_LTE_ON_CDMA_PRODUCT_TYPE} will be used to determine its
* final value which could also be {@link Phone#LTE_ON_CDMA_FALSE}.
* {@see BaseCommands#getLteOnCdmaMode()}
*/
static final String PROPERTY_LTE_ON_CDMA_DEVICE = "telephony.lteOnCdmaDevice";
static final String CURRENT_ACTIVE_PHONE = "gsm.current.phone-type";
//****** SIM Card
/**
* One of <code>"UNKNOWN"</code> <code>"ABSENT"</code> <code>"PIN_REQUIRED"</code>
* <code>"PUK_REQUIRED"</code> <code>"NETWORK_LOCKED"</code> or <code>"READY"</code>
*/
static String PROPERTY_SIM_STATE = "gsm.sim.state";
/**
* The MCC+MNC (mobile country code+mobile network code) of the
* provider of the SIM. 5 or 6 decimal digits.
* Availability: SIM state must be "READY"
*/
static String PROPERTY_ICC_OPERATOR_NUMERIC = "gsm.sim.operator.numeric";
/**
* PROPERTY_ICC_OPERATOR_ALPHA is also known as the SPN, or Service Provider Name.
* Availability: SIM state must be "READY"
*/
static String PROPERTY_ICC_OPERATOR_ALPHA = "gsm.sim.operator.alpha";
/**
* ISO country code equivalent for the SIM provider's country code
*/
static String PROPERTY_ICC_OPERATOR_ISO_COUNTRY = "gsm.sim.operator.iso-country";
/**
* Indicates the available radio technology. Values include: <code>"unknown"</code>,
* <code>"GPRS"</code>, <code>"EDGE"</code> and <code>"UMTS"</code>.
*/
static String PROPERTY_DATA_NETWORK_TYPE = "gsm.network.type";
/**
* Indicate if phone is in emergency callback mode
*/
static final String PROPERTY_INECM_MODE = "ril.cdma.inecmmode";
/**
* Indicate the timer value for exiting emergency callback mode
*/
static final String PROPERTY_ECM_EXIT_TIMER = "ro.cdma.ecmexittimer";
/**
* The international dialing prefix conversion string
*/
static final String PROPERTY_IDP_STRING = "ro.cdma.idpstring";
/**
* Defines the schema for the carrier specified OTASP number
*/
static final String PROPERTY_OTASP_NUM_SCHEMA = "ro.cdma.otaspnumschema";
/**
* Disable all calls including Emergency call when it set to true.
*/
static final String PROPERTY_DISABLE_CALL = "ro.telephony.disable-call";
/**
* Set to true for vendor RIL's that send multiple UNSOL_CALL_RING notifications.
*/
static final String PROPERTY_RIL_SENDS_MULTIPLE_CALL_RING =
"ro.telephony.call_ring.multiple";
/**
* The number of milliseconds between CALL_RING notifications.
*/
static final String PROPERTY_CALL_RING_DELAY = "ro.telephony.call_ring.delay";
/**
* Track CDMA SMS message id numbers to ensure they increment
* monotonically, regardless of reboots.
*/
static final String PROPERTY_CDMA_MSG_ID = "persist.radio.cdma.msgid";
/**
* Property to override DEFAULT_WAKE_LOCK_TIMEOUT
*/
static final String PROPERTY_WAKE_LOCK_TIMEOUT = "ro.ril.wake_lock_timeout";
/**
* Set to true to indicate that the modem needs to be reset
* when there is a radio technology change.
*/
static final String PROPERTY_RESET_ON_RADIO_TECH_CHANGE = "persist.radio.reset_on_switch";
/**
* Set to false to disable SMS receiving, default is
* the value of config_sms_capable
*/
static final String PROPERTY_SMS_RECEIVE = "telephony.sms.receive";
/**
* Set to false to disable SMS sending, default is
* the value of config_sms_capable
*/
static final String PROPERTY_SMS_SEND = "telephony.sms.send";
/**
* Set to true to indicate a test CSIM card is used in the device.
* This property is for testing purpose only. This should not be defined
* in commercial configuration.
*/
static final String PROPERTY_TEST_CSIM = "persist.radio.test-csim";
/**
* Ignore RIL_UNSOL_NITZ_TIME_RECEIVED completely, used for debugging/testing.
*/
static final String PROPERTY_IGNORE_NITZ = "telephony.test.ignore.nitz";
}
@@ -1,243 +0,0 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.util;
import java.lang.reflect.Array;
// XXX these should be changed to reflect the actual memory allocator we use.
// it looks like right now objects want to be powers of 2 minus 8
// and the array size eats another 4 bytes
/**
* ArrayUtils contains some methods that you can call to find out
* the most efficient increments by which to grow arrays.
*/
public class ArrayUtils {
private static Object[] EMPTY = new Object[0];
private static final int CACHE_SIZE = 73;
private static Object[] sCache = new Object[CACHE_SIZE];
private ArrayUtils() { /* cannot be instantiated */ }
public static int idealByteArraySize(int need) {
for (int i = 4; i < 32; i++)
if (need <= (1 << i) - 12)
return (1 << i) - 12;
return need;
}
public static int idealBooleanArraySize(int need) {
return idealByteArraySize(need);
}
public static int idealShortArraySize(int need) {
return idealByteArraySize(need * 2) / 2;
}
public static int idealCharArraySize(int need) {
return idealByteArraySize(need * 2) / 2;
}
public static int idealIntArraySize(int need) {
return idealByteArraySize(need * 4) / 4;
}
public static int idealFloatArraySize(int need) {
return idealByteArraySize(need * 4) / 4;
}
public static int idealObjectArraySize(int need) {
return idealByteArraySize(need * 4) / 4;
}
public static int idealLongArraySize(int need) {
return idealByteArraySize(need * 8) / 8;
}
/**
* Checks if the beginnings of two byte arrays are equal.
*
* @param array1 the first byte array
* @param array2 the second byte array
* @param length the number of bytes to check
* @return true if they're equal, false otherwise
*/
public static boolean equals(byte[] array1, byte[] array2, int length) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length < length || array2.length < length) {
return false;
}
for (int i = 0; i < length; i++) {
if (array1[i] != array2[i]) {
return false;
}
}
return true;
}
/**
* Returns an empty array of the specified type. The intent is that
* it will return the same empty array every time to avoid reallocation,
* although this is not guaranteed.
*/
@SuppressWarnings("unchecked")
public static <T> T[] emptyArray(Class<T> kind) {
if (kind == Object.class) {
return (T[]) EMPTY;
}
int bucket = ((System.identityHashCode(kind) / 8) & 0x7FFFFFFF) % CACHE_SIZE;
Object cache = sCache[bucket];
if (cache == null || cache.getClass().getComponentType() != kind) {
cache = Array.newInstance(kind, 0);
sCache[bucket] = cache;
// Log.e("cache", "new empty " + kind.getName() + " at " + bucket);
}
return (T[]) cache;
}
/**
* Checks that value is present as at least one of the elements of the array.
*
* @param array the array to check in
* @param value the value to check for
* @return true if the value is present in the array
*/
public static <T> boolean contains(T[] array, T value) {
for (T element : array) {
if (element == null) {
if (value == null) return true;
} else {
if (value != null && element.equals(value)) return true;
}
}
return false;
}
public static boolean contains(int[] array, int value) {
for (int element : array) {
if (element == value) {
return true;
}
}
return false;
}
public static long total(long[] array) {
long total = 0;
for (long value : array) {
total += value;
}
return total;
}
/**
* Appends an element to a copy of the array and returns the copy.
*
* @param array The original array, or null to represent an empty array.
* @param element The element to add.
* @return A new array that contains all of the elements of the original array
* with the specified element added at the end.
*/
@SuppressWarnings("unchecked")
public static <T> T[] appendElement(Class<T> kind, T[] array, T element) {
final T[] result;
final int end;
if (array != null) {
end = array.length;
result = (T[]) Array.newInstance(kind, end + 1);
System.arraycopy(array, 0, result, 0, end);
} else {
end = 0;
result = (T[]) Array.newInstance(kind, 1);
}
result[end] = element;
return result;
}
/**
* Removes an element from a copy of the array and returns the copy.
* If the element is not present, then the original array is returned unmodified.
*
* @param array The original array, or null to represent an empty array.
* @param element The element to remove.
* @return A new array that contains all of the elements of the original array
* except the first copy of the specified element removed. If the specified element
* was not present, then returns the original array. Returns null if the result
* would be an empty array.
*/
@SuppressWarnings("unchecked")
public static <T> T[] removeElement(Class<T> kind, T[] array, T element) {
if (array != null) {
final int length = array.length;
for (int i = 0; i < length; i++) {
if (array[i] == element) {
if (length == 1) {
return null;
}
T[] result = (T[]) Array.newInstance(kind, length - 1);
System.arraycopy(array, 0, result, 0, i);
System.arraycopy(array, i + 1, result, i, length - i - 1);
return result;
}
}
}
return array;
}
public static int[] appendInt(int[] cur, int val) {
if (cur == null) {
return new int[]{val};
}
final int N = cur.length;
for (int i = 0; i < N; i++) {
if (cur[i] == val) {
return cur;
}
}
int[] ret = new int[N + 1];
System.arraycopy(cur, 0, ret, 0, N);
ret[N] = val;
return ret;
}
public static int[] removeInt(int[] cur, int val) {
if (cur == null) {
return null;
}
final int N = cur.length;
for (int i = 0; i < N; i++) {
if (cur[i] == val) {
int[] ret = new int[N - 1];
if (i > 0) {
System.arraycopy(cur, 0, ret, 0, i);
}
if (i < (N - 1)) {
System.arraycopy(cur, i + 1, ret, i, N - i - 1);
}
return ret;
}
}
return cur;
}
}
@@ -1,62 +0,0 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.util;
import java.util.Arrays;
/**
* Object utility methods.
*/
public class Objects {
/**
* Determines whether two possibly-null objects are equal. Returns:
* <p/>
* <ul>
* <li>{@code true} if {@code a} and {@code b} are both null.
* <li>{@code true} if {@code a} and {@code b} are both non-null and they are
* equal according to {@link Object#equals(Object)}.
* <li>{@code false} in all other situations.
* </ul>
* <p/>
* <p>This assumes that any non-null objects passed to this function conform
* to the {@code equals()} contract.
*/
public static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
/**
* Generates a hash code for multiple values. The hash code is generated by
* calling {@link java.util.Arrays#hashCode(Object[])}.
* <p/>
* <p>This is useful for implementing {@link Object#hashCode()}. For example,
* in an object that has three properties, {@code x}, {@code y}, and
* {@code z}, one could write:
* <pre>
* public int hashCode() {
* return Objects.hashCode(getX(), getY(), getZ());
* }</pre>
*
* <b>Warning</b>: When a single object is supplied, the returned hash code
* does not equal the hash code of that object.
*/
public static int hashCode(Object... objects) {
return Arrays.hashCode(objects);
}
}
@@ -1,69 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.util;
/**
* Simple static methods to be called at the start of your own methods to verify
* correct arguments and state.
*/
public class Preconditions {
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
}
@@ -1,108 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.TypeInfo;
public class AttrImpl extends NodeImpl implements Attr {
private String mName;
private String mValue;
/*
* Internal methods
*/
protected AttrImpl(DocumentImpl owner, String name) {
super(owner);
mName = name;
}
/*
* Attr Interface Methods
*/
public String getName() {
return mName;
}
public Element getOwnerElement() {
// TODO Auto-generated method stub
return null;
}
public boolean getSpecified() {
return mValue != null;
}
public String getValue() {
return mValue;
}
// Instead of setting a <code>Text></code> with the content of the
// String value as defined in the specs, we directly set here the
// internal mValue member.
public void setValue(String value) throws DOMException {
mValue = value;
}
/*
* Node Interface Methods
*/
@Override
public String getNodeName() {
return mName;
}
@Override
public short getNodeType() {
return Node.ATTRIBUTE_NODE;
}
@Override
public Node getParentNode() {
return null;
}
@Override
public Node getPreviousSibling() {
return null;
}
@Override
public Node getNextSibling() {
return null;
}
@Override
public void setNodeValue(String nodeValue) throws DOMException {
setValue(nodeValue);
}
public TypeInfo getSchemaTypeInfo() {
return null;
}
public boolean isId() {
return false;
}
}
@@ -1,194 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
public abstract class DocumentImpl extends NodeImpl implements Document {
/*
* Internal methods
*/
public DocumentImpl() {
super(null);
}
/*
* Document Interface Methods
*/
public Attr createAttribute(String name) throws DOMException {
return new AttrImpl(this, name);
}
public Attr createAttributeNS(String namespaceURI, String qualifiedName)
throws DOMException {
// TODO Auto-generated method stub
return null;
}
public CDATASection createCDATASection(String data) throws DOMException {
// TODO Auto-generated method stub
return null;
}
public Comment createComment(String data) {
// TODO Auto-generated method stub
return null;
}
public DocumentFragment createDocumentFragment() {
// TODO Auto-generated method stub
return null;
}
public abstract Element createElement(String tagName) throws DOMException;
public Element createElementNS(String namespaceURI, String qualifiedName)
throws DOMException {
// TODO Auto-generated method stub
return null;
}
public EntityReference createEntityReference(String name) throws DOMException {
// TODO Auto-generated method stub
return null;
}
public ProcessingInstruction createProcessingInstruction(String target, String data)
throws DOMException {
// TODO Auto-generated method stub
return null;
}
public Text createTextNode(String data) {
// TODO Auto-generated method stub
return null;
}
public DocumentType getDoctype() {
// TODO Auto-generated method stub
return null;
}
public abstract Element getDocumentElement();
public Element getElementById(String elementId) {
// TODO Auto-generated method stub
return null;
}
public NodeList getElementsByTagName(String tagname) {
// TODO Auto-generated method stub
return null;
}
public NodeList getElementsByTagNameNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return null;
}
public DOMImplementation getImplementation() {
// TODO Auto-generated method stub
return null;
}
public Node importNode(Node importedNode, boolean deep) throws DOMException {
// TODO Auto-generated method stub
return null;
}
/*
* Node Interface methods
*/
@Override
public short getNodeType() {
return Node.DOCUMENT_NODE;
}
@Override
public String getNodeName() {
// The value of nodeName is "#document" when Node is a Document
return "#document";
}
public String getInputEncoding() {
return null;
}
public String getXmlEncoding() {
return null;
}
public boolean getXmlStandalone() {
return false;
}
public void setXmlStandalone(boolean xmlStandalone) throws DOMException {}
public String getXmlVersion() {
return null;
}
public void setXmlVersion(String xmlVersion) throws DOMException {}
public boolean getStrictErrorChecking() {
return true;
}
public void setStrictErrorChecking(boolean strictErrorChecking) {}
public String getDocumentURI() {
return null;
}
public void setDocumentURI(String documentURI) {}
public Node adoptNode(Node source) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public DOMConfiguration getDomConfig() {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public void normalizeDocument() {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public Node renameNode(Node n, String namespaceURI, String qualifiedName)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
}
@@ -1,172 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.w3c.dom.TypeInfo;
public class ElementImpl extends NodeImpl implements Element {
private String mTagName;
private NamedNodeMap mAttributes = new NamedNodeMapImpl();
/*
* Internal methods
*/
protected ElementImpl(DocumentImpl owner, String tagName) {
super(owner);
mTagName = tagName;
}
/*
* Element Interface methods
*/
public String getAttribute(String name) {
Attr attrNode = getAttributeNode(name);
String attrValue = "";
if (attrNode != null) {
attrValue = attrNode.getValue();
}
return attrValue;
}
public String getAttributeNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return null;
}
public Attr getAttributeNode(String name) {
return (Attr)mAttributes.getNamedItem(name);
}
public Attr getAttributeNodeNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return null;
}
public NodeList getElementsByTagName(String name) {
return new NodeListImpl(this, name, true);
}
public NodeList getElementsByTagNameNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return null;
}
public String getTagName() {
return mTagName;
}
public boolean hasAttribute(String name) {
return (getAttributeNode(name) != null);
}
public boolean hasAttributeNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return false;
}
public void removeAttribute(String name) throws DOMException {
// TODO Auto-generated method stub
}
public void removeAttributeNS(String namespaceURI, String localName)
throws DOMException {
// TODO Auto-generated method stub
}
public Attr removeAttributeNode(Attr oldAttr) throws DOMException {
// TODO Auto-generated method stub
return null;
}
public void setAttribute(String name, String value) throws DOMException {
Attr attribute = getAttributeNode(name);
if (attribute == null) {
attribute = mOwnerDocument.createAttribute(name);
}
attribute.setNodeValue(value);
mAttributes.setNamedItem(attribute);
}
public void setAttributeNS(String namespaceURI, String qualifiedName,
String value) throws DOMException {
// TODO Auto-generated method stub
}
public Attr setAttributeNode(Attr newAttr) throws DOMException {
// TODO Auto-generated method stub
return null;
}
public Attr setAttributeNodeNS(Attr newAttr) throws DOMException {
// TODO Auto-generated method stub
return null;
}
/*
* Node Interface methods
*/
@Override
public short getNodeType() {
return ELEMENT_NODE;
}
@Override
public String getNodeName() {
// The value of nodeName is tagName when Node is an Element
return mTagName;
}
@Override
public NamedNodeMap getAttributes() {
return mAttributes;
}
@Override
public boolean hasAttributes() {
return (mAttributes.getLength() > 0);
}
public TypeInfo getSchemaTypeInfo() {
return null;
}
public void setIdAttribute(String name, boolean isId) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public void setIdAttributeNS(String namespaceURI, String localName,
boolean isId) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public void setIdAttributeNode(Attr idAttr, boolean isId)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
}
@@ -1,88 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import java.util.Vector;
public class NamedNodeMapImpl implements NamedNodeMap {
private Vector<Node> mNodes = new Vector<Node>();
public int getLength() {
return mNodes.size();
}
public Node getNamedItem(String name) {
Node node = null;
for (int i = 0; i < mNodes.size(); i++) {
if (name.equals(mNodes.elementAt(i).getNodeName())) {
node = mNodes.elementAt(i);
break;
}
}
return node;
}
public Node getNamedItemNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return null;
}
public Node item(int index) {
if (index < mNodes.size()) {
return mNodes.elementAt(index);
}
return null;
}
public Node removeNamedItem(String name) throws DOMException {
Node node = getNamedItem(name);
if (node == null) {
throw new DOMException(DOMException.NOT_FOUND_ERR, "Not found");
} else {
mNodes.remove(node);
}
return node;
}
public Node removeNamedItemNS(String namespaceURI, String localName)
throws DOMException {
// TODO Auto-generated method stub
return null;
}
public Node setNamedItem(Node arg) throws DOMException {
Node existing = getNamedItem(arg.getNodeName());
if (existing != null) {
mNodes.remove(existing);
}
mNodes.add(arg);
return existing;
}
public Node setNamedItemNS(Node arg) throws DOMException {
// TODO Auto-generated method stub
return null;
}
}
@@ -1,274 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom;
import com.android.mms.dom.events.EventTargetImpl;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.UserDataHandler;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventException;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import java.util.NoSuchElementException;
import java.util.Vector;
public abstract class NodeImpl implements Node, EventTarget {
private Node mParentNode;
private final Vector<Node> mChildNodes = new Vector<Node>();
DocumentImpl mOwnerDocument;
private final EventTarget mEventTarget = new EventTargetImpl(this);
/*
* Internal methods
*/
protected NodeImpl(DocumentImpl owner) {
mOwnerDocument = owner;
}
/*
* Node Interface Methods
*/
public Node appendChild(Node newChild) throws DOMException {
((NodeImpl)newChild).setParentNode(this);
mChildNodes.remove(newChild);
mChildNodes.add(newChild);
return newChild;
}
public Node cloneNode(boolean deep) {
// TODO Auto-generated method stub
return null;
}
public NamedNodeMap getAttributes() {
// Default. Override in Element.
return null;
}
public NodeList getChildNodes() {
return new NodeListImpl(this, null, false);
}
public Node getFirstChild() {
Node firstChild = null;
try {
firstChild = mChildNodes.firstElement();
}
catch (NoSuchElementException e) {
// Ignore and return null
}
return firstChild;
}
public Node getLastChild() {
Node lastChild = null;
try {
lastChild = mChildNodes.lastElement();
}
catch (NoSuchElementException e) {
// Ignore and return null
}
return lastChild;
}
public String getLocalName() {
// TODO Auto-generated method stub
return null;
}
public String getNamespaceURI() {
// TODO Auto-generated method stub
return null;
}
public Node getNextSibling() {
if ((mParentNode != null) && (this != mParentNode.getLastChild())) {
Vector<Node> siblings = ((NodeImpl)mParentNode).mChildNodes;
int indexOfThis = siblings.indexOf(this);
return siblings.elementAt(indexOfThis + 1);
}
return null;
}
public abstract String getNodeName();
public abstract short getNodeType();
public String getNodeValue() throws DOMException {
// Default behaviour. Override if required.
return null;
}
public Document getOwnerDocument() {
return mOwnerDocument;
}
public Node getParentNode() {
return mParentNode;
}
public String getPrefix() {
// TODO Auto-generated method stub
return null;
}
public Node getPreviousSibling() {
if ((mParentNode != null) && (this != mParentNode.getFirstChild())) {
Vector<Node> siblings = ((NodeImpl)mParentNode).mChildNodes;
int indexOfThis = siblings.indexOf(this);
return siblings.elementAt(indexOfThis - 1);
}
return null;
}
public boolean hasAttributes() {
// Default. Override in Element.
return false;
}
public boolean hasChildNodes() {
return !(mChildNodes.isEmpty());
}
public Node insertBefore(Node newChild, Node refChild) throws DOMException {
// TODO Auto-generated method stub
return null;
}
public boolean isSupported(String feature, String version) {
// TODO Auto-generated method stub
return false;
}
public void normalize() {
// TODO Auto-generated method stub
}
public Node removeChild(Node oldChild) throws DOMException {
if (mChildNodes.contains(oldChild)) {
mChildNodes.remove(oldChild);
((NodeImpl)oldChild).setParentNode(null);
} else {
throw new DOMException(DOMException.NOT_FOUND_ERR, "Child does not exist");
}
return null;
}
public Node replaceChild(Node newChild, Node oldChild) throws DOMException {
if (mChildNodes.contains(oldChild)) {
// Try to remove the new child if available
try {
mChildNodes.remove(newChild);
} catch (DOMException e) {
// Ignore exception
}
mChildNodes.setElementAt(newChild, mChildNodes.indexOf(oldChild));
((NodeImpl)newChild).setParentNode(this);
((NodeImpl)oldChild).setParentNode(null);
} else {
throw new DOMException(DOMException.NOT_FOUND_ERR, "Old child does not exist");
}
return oldChild;
}
public void setNodeValue(String nodeValue) throws DOMException {
// Default behaviour. Override if required.
}
public void setPrefix(String prefix) throws DOMException {
// TODO Auto-generated method stub
}
private void setParentNode(Node parentNode) {
mParentNode = parentNode;
}
/*
* EventTarget Interface
*/
public void addEventListener(String type, EventListener listener, boolean useCapture) {
mEventTarget.addEventListener(type, listener, useCapture);
}
public void removeEventListener(String type, EventListener listener, boolean useCapture) {
mEventTarget.removeEventListener(type, listener, useCapture);
}
public boolean dispatchEvent(Event evt) throws EventException {
return mEventTarget.dispatchEvent(evt);
}
public String getBaseURI() {
return null;
}
public short compareDocumentPosition(Node other) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public String getTextContent() throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public void setTextContent(String textContent) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public boolean isSameNode(Node other) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public String lookupPrefix(String namespaceURI) {
return null;
}
public boolean isDefaultNamespace(String namespaceURI) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public String lookupNamespaceURI(String prefix) {
return null;
}
public boolean isEqualNode(Node arg) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public Object getFeature(String feature, String version) {
return null;
}
public Object setUserData(String key, Object data,
UserDataHandler handler) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public Object getUserData(String key) {
return null;
}
}
@@ -1,129 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
public class NodeListImpl implements NodeList {
private ArrayList<Node> mSearchNodes;
private ArrayList<Node> mStaticNodes;
private Node mRootNode;
private String mTagName;
private boolean mDeepSearch;
/*
* Internal Interface
*/
/**
* Constructs a NodeList by searching for all descendants or the direct
* children of a root node with a given tag name.
* @param rootNode The root <code>Node</code> of the search.
* @param tagName The tag name to be searched for. If null, all descendants
* will be returned.
* @param deep Limit the search to the direct children of rootNode if false,
* to all descendants otherwise.
*/
public NodeListImpl(Node rootNode, String tagName, boolean deepSearch) {
mRootNode = rootNode;
mTagName = tagName;
mDeepSearch = deepSearch;
}
/**
* Constructs a NodeList for a given static node list.
* @param nodes The static node list.
*/
public NodeListImpl(ArrayList<Node> nodes) {
mStaticNodes = nodes;
}
/*
* NodeListImpl Interface
*/
public int getLength() {
if (mStaticNodes == null) {
fillList(mRootNode);
return mSearchNodes.size();
} else {
return mStaticNodes.size();
}
}
public Node item(int index) {
Node node = null;
if (mStaticNodes == null) {
fillList(mRootNode);
try {
node = mSearchNodes.get(index);
} catch (IndexOutOfBoundsException e) {
// Do nothing and return null
}
} else {
try {
node = mStaticNodes.get(index);
} catch (IndexOutOfBoundsException e) {
// Do nothing and return null
}
}
return node;
}
/**
* A preorder traversal is done in the following order:
* <ul>
* <li> Visit root.
* <li> Traverse children from left to right in preorder.
* </ul>
* This method fills the live node list.
* @param The root of preorder traversal
* @return The next match
*/
private void fillList(Node node) {
// (Re)-initialize the container if this is the start of the search.
// Visit the root of this iteration otherwise.
if (node == mRootNode) {
mSearchNodes = new ArrayList<Node>();
} else {
if ((mTagName == null) || node.getNodeName().equals(mTagName)) {
mSearchNodes.add(node);
}
}
// Descend one generation...
node = node.getFirstChild();
// ...and visit in preorder the children if we are in deep search
// or directly add the children to the list otherwise.
while (node != null) {
if (mDeepSearch) {
fillList(node);
} else {
if ((mTagName == null) || node.getNodeName().equals(mTagName)) {
mSearchNodes.add(node);
}
}
node = node.getNextSibling();
}
}
}
@@ -1,127 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.events;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventTarget;
public class EventImpl implements Event {
// Event type informations
private String mEventType;
private boolean mCanBubble;
private boolean mCancelable;
// Flags whether the event type information was set
// FIXME: Can we use mEventType for this purpose?
private boolean mInitialized;
// Target of this event
private EventTarget mTarget;
// Event status variables
private short mEventPhase;
private boolean mStopPropagation;
private boolean mPreventDefault;
private EventTarget mCurrentTarget;
private int mSeekTo;
private final long mTimeStamp = System.currentTimeMillis();
public boolean getBubbles() {
return mCanBubble;
}
public boolean getCancelable() {
return mCancelable;
}
public EventTarget getCurrentTarget() {
return mCurrentTarget;
}
public short getEventPhase() {
return mEventPhase;
}
public EventTarget getTarget() {
return mTarget;
}
public long getTimeStamp() {
return mTimeStamp;
}
public String getType() {
return mEventType;
}
public void initEvent(String eventTypeArg, boolean canBubbleArg,
boolean cancelableArg) {
mEventType = eventTypeArg;
mCanBubble = canBubbleArg;
mCancelable = cancelableArg;
mInitialized = true;
}
public void initEvent(String eventTypeArg, boolean canBubbleArg, boolean cancelableArg,
int seekTo) {
mSeekTo = seekTo;
initEvent(eventTypeArg, canBubbleArg, cancelableArg);
}
public void preventDefault() {
mPreventDefault = true;
}
public void stopPropagation() {
mStopPropagation = true;
}
/*
* Internal Interface
*/
boolean isInitialized() {
return mInitialized;
}
boolean isPreventDefault() {
return mPreventDefault;
}
boolean isPropogationStopped() {
return mStopPropagation;
}
void setTarget(EventTarget target) {
mTarget = target;
}
void setEventPhase(short eventPhase) {
mEventPhase = eventPhase;
}
void setCurrentTarget(EventTarget currentTarget) {
mCurrentTarget = currentTarget;
}
public int getSeekTo() {
return mSeekTo;
}
}
@@ -1,132 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.events;
import android.util.Log;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventException;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import java.util.ArrayList;
public class EventTargetImpl implements EventTarget {
private static final String TAG = "EventTargetImpl";
private ArrayList<EventListenerEntry> mListenerEntries;
private EventTarget mNodeTarget;
static class EventListenerEntry
{
final String mType;
final EventListener mListener;
final boolean mUseCapture;
EventListenerEntry(String type, EventListener listener, boolean useCapture)
{
mType = type;
mListener = listener;
mUseCapture = useCapture;
}
}
public EventTargetImpl(EventTarget target) {
mNodeTarget = target;
}
public void addEventListener(String type, EventListener listener, boolean useCapture) {
if ((type == null) || type.equals("") || (listener == null)) {
return;
}
// Make sure we have only one entry
removeEventListener(type, listener, useCapture);
if (mListenerEntries == null) {
mListenerEntries = new ArrayList<EventListenerEntry>();
}
mListenerEntries.add(new EventListenerEntry(type, listener, useCapture));
}
public boolean dispatchEvent(Event evt) throws EventException {
// We need to use the internal APIs to modify and access the event status
EventImpl eventImpl = (EventImpl)evt;
if (!eventImpl.isInitialized()) {
throw new EventException(EventException.UNSPECIFIED_EVENT_TYPE_ERR,
"Event not initialized");
} else if ((eventImpl.getType() == null) || eventImpl.getType().equals("")) {
throw new EventException(EventException.UNSPECIFIED_EVENT_TYPE_ERR,
"Unspecified even type");
}
// Initialize event status
eventImpl.setTarget(mNodeTarget);
// TODO: At this point, to support event capturing and bubbling, we should
// establish the chain of EventTargets from the top of the tree to this
// event's target.
// TODO: CAPTURING_PHASE skipped
// Handle AT_TARGET
// Invoke handleEvent of non-capturing listeners on this EventTarget.
eventImpl.setEventPhase(Event.AT_TARGET);
eventImpl.setCurrentTarget(mNodeTarget);
if (!eventImpl.isPropogationStopped() && (mListenerEntries != null)) {
for (int i = 0; i < mListenerEntries.size(); i++) {
EventListenerEntry listenerEntry = mListenerEntries.get(i);
if (!listenerEntry.mUseCapture
&& listenerEntry.mType.equals(eventImpl.getType())) {
try {
listenerEntry.mListener.handleEvent(eventImpl);
}
catch (Exception e) {
// Any exceptions thrown inside an EventListener will
// not stop propagation of the event
Log.w(TAG, "Catched EventListener exception", e);
}
}
}
}
if (eventImpl.getBubbles()) {
// TODO: BUBBLING_PHASE skipped
}
return eventImpl.isPreventDefault();
}
public void removeEventListener(String type, EventListener listener,
boolean useCapture) {
if (null == mListenerEntries) {
return;
}
for (int i = 0; i < mListenerEntries.size(); i ++) {
EventListenerEntry listenerEntry = mListenerEntries.get(i);
if ((listenerEntry.mUseCapture == useCapture)
&& (listenerEntry.mListener == listener)
&& listenerEntry.mType.equals(type)) {
mListenerEntries.remove(i);
break;
}
}
}
}
@@ -1,156 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import com.android.mms.dom.NodeListImpl;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.ElementParallelTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
public abstract class ElementParallelTimeContainerImpl extends ElementTimeContainerImpl
implements ElementParallelTimeContainer {
private final static String ENDSYNC_ATTRIBUTE_NAME = "endsync";
private final static String ENDSYNC_FIRST = "first";
private final static String ENDSYNC_LAST = "last";
private final static String ENDSYNC_ALL = "all";
private final static String ENDSYNC_MEDIA = "media";
/*
* Internal Interface
*/
ElementParallelTimeContainerImpl(SMILElement element) {
super(element);
}
public String getEndSync() {
String endsync = mSmilElement.getAttribute(ENDSYNC_ATTRIBUTE_NAME);
if ((endsync == null) || (endsync.length() == 0)) {
setEndSync(ENDSYNC_LAST);
return ENDSYNC_LAST;
}
if (ENDSYNC_FIRST.equals(endsync) || ENDSYNC_LAST.equals(endsync) ||
ENDSYNC_ALL.equals(endsync) || ENDSYNC_MEDIA.equals(endsync)) {
return endsync;
}
// FIXME add the checking for ID-Value and smil1.0-Id-value.
setEndSync(ENDSYNC_LAST);
return ENDSYNC_LAST;
}
public void setEndSync(String endSync) throws DOMException {
if (ENDSYNC_FIRST.equals(endSync) || ENDSYNC_LAST.equals(endSync) ||
ENDSYNC_ALL.equals(endSync) || ENDSYNC_MEDIA.equals(endSync)) {
mSmilElement.setAttribute(ENDSYNC_ATTRIBUTE_NAME, endSync);
} else { // FIXME add the support for ID-Value and smil1.0-Id-value.
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Unsupported endsync value" + endSync);
}
}
@Override
public float getDur() {
float dur = super.getDur();
if (dur == 0) {
dur = getImplicitDuration();
}
return dur;
}
public float getImplicitDuration() {
float dur = -1.0F;
if (ENDSYNC_LAST.equals(getEndSync())) {
NodeList children = getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
TimeList endTimeList = child.getEnd();
for (int j = 0; j < endTimeList.getLength(); ++j) {
Time endTime = endTimeList.item(j);
if (endTime.getTimeType() == Time.SMIL_TIME_INDEFINITE) {
// Return "indefinite" here.
return -1.0F;
}
if (endTime.getResolved()) {
float end = (float)endTime.getResolvedOffset();
dur = (end > dur) ? end : dur;
}
}
}
} // Other endsync types are not supported now.
return dur;
}
public NodeList getActiveChildrenAt(float instant) {
/*
* Find the closest Time of ElementTime before instant.
* Add ElementTime to list of active elements if the Time belongs to the begin-list,
* do not add it otherwise.
*/
ArrayList<Node> activeChildren = new ArrayList<Node>();
NodeList children = getTimeChildren();
int childrenLen = children.getLength();
for (int i = 0; i < childrenLen; ++i) {
double maxOffset = 0.0;
boolean active = false;
ElementTime child = (ElementTime) children.item(i);
TimeList beginList = child.getBegin();
int len = beginList.getLength();
for (int j = 0; j < len; ++j) {
Time begin = beginList.item(j);
if (begin.getResolved()) {
double resolvedOffset = begin.getResolvedOffset() * 1000.0;
if ((resolvedOffset <= instant) && (resolvedOffset >= maxOffset)) {
maxOffset = resolvedOffset;
active = true;
}
}
}
TimeList endList = child.getEnd();
len = endList.getLength();
for (int j = 0; j < len; ++j) {
Time end = endList.item(j);
if (end.getResolved()) {
double resolvedOffset = end.getResolvedOffset() * 1000.0;
if ((resolvedOffset <= instant) && (resolvedOffset >= maxOffset)) {
maxOffset = resolvedOffset;
active = false;
}
}
}
if (active) {
activeChildren.add((Node) child);
}
}
return new NodeListImpl(activeChildren);
}
}
@@ -1,74 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import com.android.mms.dom.NodeListImpl;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.ElementSequentialTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILElement;
import java.util.ArrayList;
public abstract class ElementSequentialTimeContainerImpl extends
ElementTimeContainerImpl implements ElementSequentialTimeContainer {
/*
* Internal Interface
*/
ElementSequentialTimeContainerImpl(SMILElement element) {
super(element);
}
/*
* ElementSequentialTimeContainer Interface
*/
public NodeList getActiveChildrenAt(float instant) {
NodeList allChildren = this.getTimeChildren();
ArrayList<Node> nodes = new ArrayList<Node>();
for (int i = 0; i < allChildren.getLength(); i++) {
instant -= ((ElementTime) allChildren.item(i)).getDur();
if (instant < 0) {
nodes.add(allChildren.item(i));
return new NodeListImpl(nodes);
}
}
return new NodeListImpl(nodes);
}
public float getDur() {
float dur = super.getDur();
if (dur == 0) {
NodeList children = getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
if (child.getDur() < 0) {
// Return "indefinite" since containing a child whose duration is indefinite.
return -1.0F;
}
dur += child.getDur();
}
}
return dur;
}
}
@@ -1,33 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import org.w3c.dom.smil.ElementTimeContainer;
import org.w3c.dom.smil.SMILElement;
public abstract class ElementTimeContainerImpl extends ElementTimeImpl implements
ElementTimeContainer {
/*
* Internal Interface
*/
ElementTimeContainerImpl(SMILElement element) {
super(element);
}
}
@@ -1,349 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import android.util.Log;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
public abstract class ElementTimeImpl implements ElementTime {
private static final String TAG = "ElementTimeImpl";
private static final String FILL_REMOVE_ATTRIBUTE = "remove";
private static final String FILL_FREEZE_ATTRIBUTE = "freeze";
private static final String FILL_HOLD_ATTRIBUTE = "hold";
private static final String FILL_TRANSITION_ATTRIBUTE = "transition";
private static final String FILL_AUTO_ATTRIBUTE = "auto";
private static final String FILL_ATTRIBUTE_NAME = "fill";
private static final String FILLDEFAULT_ATTRIBUTE_NAME = "fillDefault";
final SMILElement mSmilElement;
/*
* Internal Interface
*/
ElementTimeImpl(SMILElement element) {
mSmilElement = element;
}
// Default implementation. Override if required.
int getBeginConstraints() {
return TimeImpl.ALLOW_ALL;
}
// Default implementation. Override if required
int getEndConstraints() {
return TimeImpl.ALLOW_ALL;
}
/**
* To get the parent node on the ElementTime tree. It is in opposition to getTimeChildren.
* @return the parent ElementTime. Returns <code>null</code> if there is no parent.
*/
abstract ElementTime getParentElementTime();
/*
* ElementTime Interface
*/
public TimeList getBegin() {
String[] beginTimeStringList = mSmilElement.getAttribute("begin").split(";");
// TODO: Check other constraints on parsed values, e.g., "single, non-negative offset values
ArrayList<Time> beginTimeList = new ArrayList<>();
// Initialize Time instances and add them to Vector
for (String aBeginTimeStringList : beginTimeStringList) {
try {
beginTimeList.add(new TimeImpl(aBeginTimeStringList, getBeginConstraints()));
} catch (IllegalArgumentException e) {
// Ignore badly formatted times
}
}
if (beginTimeList.isEmpty()) {
/*
* What is the right default value?
*
* In MMS SMIL, this method may be called either on an instance of:
*
* 1 - ElementSequentialTimeContainer (The SMILDocument)
* 2 - ElementParallelTimeContainer (A Time-Child of the SMILDocument, which is a seq)
* 3 - ElementTime (A SMILMediaElement).
*
* 1 - In the first case, the default start time is obviously 0.
* 2 - In the second case, the specifications mentions that
* "For children of a sequence, the only legal value for begin is
* a (single) non-negative offset value. The default begin value is 0."
* 3 - In the third case, the specification mentions that
* "The default value of begin for children of a par is 0."
*
* In short, if no value is specified, the default is always 0.
*/
beginTimeList.add(new TimeImpl("0", TimeImpl.ALLOW_ALL));
}
return new TimeListImpl(beginTimeList);
}
public float getDur() {
float dur = 0;
try {
String durString = mSmilElement.getAttribute("dur");
if (durString != null) {
dur = TimeImpl.parseClockValue(durString) / 1000f;
}
} catch (IllegalArgumentException e) {
// Do nothing and return the minimum value
}
return dur;
}
public TimeList getEnd() {
ArrayList<Time> endTimeList = new ArrayList<>();
String[] endTimeStringList = mSmilElement.getAttribute("end").split(";");
int len = endTimeStringList.length;
if (!((len == 1) && (endTimeStringList[0].length() == 0))) { // Ensure the end field is set.
// Initialize Time instances and add them to Vector
for (String anEndTimeStringList : endTimeStringList) {
try {
endTimeList.add(new TimeImpl(anEndTimeStringList,
getEndConstraints()));
} catch (IllegalArgumentException e) {
// Ignore badly formatted times
Log.e(TAG, "Malformed time value.", e);
}
}
}
// "end" time is not specified
if (endTimeList.isEmpty()) {
// Get duration
float duration = getDur();
if (duration < 0) {
endTimeList.add(new TimeImpl("indefinite", getEndConstraints()));
} else {
// Get begin
TimeList begin = getBegin();
for (int i = 0; i < begin.getLength(); i++) {
endTimeList.add(new TimeImpl(
// end = begin + dur
begin.item(i).getResolvedOffset() + duration + "s",
getEndConstraints()));
}
}
}
return new TimeListImpl(endTimeList);
}
private boolean beginAndEndAreZero() {
TimeList begin = getBegin();
TimeList end = getEnd();
if (begin.getLength() == 1 && end.getLength() == 1) {
Time beginTime = begin.item(0);
Time endTime = end.item(0);
return beginTime.getOffset() == 0. && endTime.getOffset() == 0.;
}
return false;
}
public short getFill() {
String fill = mSmilElement.getAttribute(FILL_ATTRIBUTE_NAME);
if (fill.equalsIgnoreCase(FILL_FREEZE_ATTRIBUTE)) {
return FILL_FREEZE;
} else if (fill.equalsIgnoreCase(FILL_REMOVE_ATTRIBUTE)) {
return FILL_REMOVE;
} else if (fill.equalsIgnoreCase(FILL_HOLD_ATTRIBUTE)) {
// FIXME handle it as freeze for now
return FILL_FREEZE;
} else if (fill.equalsIgnoreCase(FILL_TRANSITION_ATTRIBUTE)) {
// FIXME handle it as freeze for now
return FILL_FREEZE;
} else if (!fill.equalsIgnoreCase(FILL_AUTO_ATTRIBUTE)) {
/*
* fill = default
* The fill behavior for the element is determined by the value of the fillDefault
* attribute. This is the default value.
*/
short fillDefault = getFillDefault();
if (fillDefault != FILL_AUTO) {
return fillDefault;
}
}
/*
* fill = auto
* The fill behavior for this element depends on whether the element specifies any of
* the attributes that define the simple or active duration:
* - If none of the attributes dur, end, repeatCount or repeatDur are specified on
* the element, then the element will have a fill behavior identical to that if it were
* specified as "freeze".
* - Otherwise, the element will have a fill behavior identical to that if it were
* specified as "remove".
*/
if (((mSmilElement.getAttribute("dur").length() == 0) &&
(mSmilElement.getAttribute("end").length() == 0) &&
(mSmilElement.getAttribute("repeatCount").length() == 0) &&
(mSmilElement.getAttribute("repeatDur").length() == 0)) ||
beginAndEndAreZero()) {
return FILL_FREEZE;
} else {
return FILL_REMOVE;
}
}
public short getFillDefault() {
String fillDefault = mSmilElement.getAttribute(FILLDEFAULT_ATTRIBUTE_NAME);
if (fillDefault.equalsIgnoreCase(FILL_REMOVE_ATTRIBUTE)) {
return FILL_REMOVE;
} else if (fillDefault.equalsIgnoreCase(FILL_FREEZE_ATTRIBUTE)) {
return FILL_FREEZE;
} else if (fillDefault.equalsIgnoreCase(FILL_AUTO_ATTRIBUTE)) {
return FILL_AUTO;
} else if (fillDefault.equalsIgnoreCase(FILL_HOLD_ATTRIBUTE)) {
// FIXME handle it as freeze for now
return FILL_FREEZE;
} else if (fillDefault.equalsIgnoreCase(FILL_TRANSITION_ATTRIBUTE)) {
// FIXME handle it as freeze for now
return FILL_FREEZE;
} else {
/*
* fillDefault = inherit
* Specifies that the value of this attribute (and of the fill behavior) are
* inherited from the fillDefault value of the parent element.
* This is the default value.
*/
ElementTime parent = getParentElementTime();
if (parent == null) {
/*
* fillDefault = auto
* If there is no parent element, the value is "auto".
*/
return FILL_AUTO;
} else {
return parent.getFillDefault();
}
}
}
public float getRepeatCount() {
String repeatCount = mSmilElement.getAttribute("repeatCount");
try {
float value = Float.parseFloat(repeatCount);
if (value > 0) {
return value;
} else {
return 0; // default
}
} catch (NumberFormatException e) {
return 0; // default
}
}
public float getRepeatDur() {
try {
float repeatDur =
TimeImpl.parseClockValue(mSmilElement.getAttribute("repeatDur"));
if (repeatDur > 0) {
return repeatDur;
} else {
return 0; // default
}
} catch (IllegalArgumentException e) {
return 0; // default
}
}
public short getRestart() {
String restart = mSmilElement.getAttribute("restart");
if (restart.equalsIgnoreCase("never")) {
return RESTART_NEVER;
} else if (restart.equalsIgnoreCase("whenNotActive")) {
return RESTART_WHEN_NOT_ACTIVE;
} else {
return RESTART_ALWAYS; // default
}
}
public void setBegin(TimeList begin) throws DOMException {
// TODO Implement this
mSmilElement.setAttribute("begin", "indefinite");
}
public void setDur(float dur) throws DOMException {
// In SMIL 3.0, the dur could be a timecount-value which may contain fractions.
// However, in MMS 1.3, the dur SHALL be expressed in integer milliseconds.
mSmilElement.setAttribute("dur", Integer.toString((int)(dur * 1000)) + "ms");
}
public void setEnd(TimeList end) throws DOMException {
// TODO Implement this
mSmilElement.setAttribute("end", "indefinite");
}
public void setFill(short fill) throws DOMException {
if (fill == FILL_FREEZE) {
mSmilElement.setAttribute(FILL_ATTRIBUTE_NAME, FILL_FREEZE_ATTRIBUTE);
} else {
mSmilElement.setAttribute(FILL_ATTRIBUTE_NAME, FILL_REMOVE_ATTRIBUTE); // default
}
}
public void setFillDefault(short fillDefault) throws DOMException {
if (fillDefault == FILL_FREEZE) {
mSmilElement.setAttribute(FILLDEFAULT_ATTRIBUTE_NAME, FILL_FREEZE_ATTRIBUTE);
} else {
mSmilElement.setAttribute(FILLDEFAULT_ATTRIBUTE_NAME, FILL_REMOVE_ATTRIBUTE);
}
}
public void setRepeatCount(float repeatCount) throws DOMException {
String repeatCountString = "indefinite";
if (repeatCount > 0) {
repeatCountString = Float.toString(repeatCount);
}
mSmilElement.setAttribute("repeatCount", repeatCountString);
}
public void setRepeatDur(float repeatDur) throws DOMException {
String repeatDurString = "indefinite";
if (repeatDur > 0) {
repeatDurString = Float.toString(repeatDur) + "ms";
}
mSmilElement.setAttribute("repeatDur", repeatDurString);
}
public void setRestart(short restart) throws DOMException {
if (restart == RESTART_NEVER) {
mSmilElement.setAttribute("restart", "never");
} else if (restart == RESTART_WHEN_NOT_ACTIVE) {
mSmilElement.setAttribute("restart", "whenNotActive");
} else {
mSmilElement.setAttribute("restart", "always");
}
}
}
@@ -1,295 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import com.android.mms.dom.DocumentImpl;
import com.android.mms.dom.events.EventImpl;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
import org.w3c.dom.smil.ElementSequentialTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.SMILLayoutElement;
import org.w3c.dom.smil.TimeList;
public class SmilDocumentImpl extends DocumentImpl implements SMILDocument, DocumentEvent {
/*
* The sequential time container cannot be initialized here because the real container
* is body, which hasn't been created yet. It will be initialized when the body has
* already been created. Please see getBody().
*/
ElementSequentialTimeContainer mSeqTimeContainer;
public final static String SMIL_DOCUMENT_START_EVENT = "SmilDocumentStart";
public final static String SMIL_DOCUMENT_END_EVENT = "SimlDocumentEnd";
/*
* Internal methods
*/
public SmilDocumentImpl() {
super();
}
/*
* ElementSequentialTimeContainer stuff
*/
public NodeList getActiveChildrenAt(float instant) {
return mSeqTimeContainer.getActiveChildrenAt(instant);
}
public NodeList getTimeChildren() {
return mSeqTimeContainer.getTimeChildren();
}
public boolean beginElement() {
return mSeqTimeContainer.beginElement();
}
public boolean endElement() {
return mSeqTimeContainer.endElement();
}
public TimeList getBegin() {
return mSeqTimeContainer.getBegin();
}
public float getDur() {
return mSeqTimeContainer.getDur();
}
public TimeList getEnd() {
return mSeqTimeContainer.getEnd();
}
public short getFill() {
return mSeqTimeContainer.getFill();
}
public short getFillDefault() {
return mSeqTimeContainer.getFillDefault();
}
public float getRepeatCount() {
return mSeqTimeContainer.getRepeatCount();
}
public float getRepeatDur() {
return mSeqTimeContainer.getRepeatDur();
}
public short getRestart() {
return mSeqTimeContainer.getRestart();
}
public void pauseElement() {
mSeqTimeContainer.pauseElement();
}
public void resumeElement() {
mSeqTimeContainer.resumeElement();
}
public void seekElement(float seekTo) {
mSeqTimeContainer.seekElement(seekTo);
}
public void setBegin(TimeList begin) throws DOMException {
mSeqTimeContainer.setBegin(begin);
}
public void setDur(float dur) throws DOMException {
mSeqTimeContainer.setDur(dur);
}
public void setEnd(TimeList end) throws DOMException {
mSeqTimeContainer.setEnd(end);
}
public void setFill(short fill) throws DOMException {
mSeqTimeContainer.setFill(fill);
}
public void setFillDefault(short fillDefault) throws DOMException {
mSeqTimeContainer.setFillDefault(fillDefault);
}
public void setRepeatCount(float repeatCount) throws DOMException {
mSeqTimeContainer.setRepeatCount(repeatCount);
}
public void setRepeatDur(float repeatDur) throws DOMException {
mSeqTimeContainer.setRepeatDur(repeatDur);
}
public void setRestart(short restart) throws DOMException {
mSeqTimeContainer.setRestart(restart);
}
/*
* Document Interface
*/
@Override
public Element createElement(String tagName) throws DOMException {
// Find the appropriate class for this element
tagName = tagName.toLowerCase();
switch (tagName) {
case "text":
case "img":
case "video":
return new SmilRegionMediaElementImpl(this, tagName);
case "audio":
return new SmilMediaElementImpl(this, tagName);
case "layout":
return new SmilLayoutElementImpl(this, tagName);
case "root-layout":
return new SmilRootLayoutElementImpl(this, tagName);
case "region":
return new SmilRegionElementImpl(this, tagName);
case "ref":
return new SmilRefElementImpl(this, tagName);
case "par":
return new SmilParElementImpl(this, tagName);
case "vcard":
return new SmilRegionMediaElementImpl(this, tagName);
default:
// This includes also the structural nodes SMIL,
// HEAD, BODY, for which no specific types are defined.
return new SmilElementImpl(this, tagName);
}
}
@Override
public SMILElement getDocumentElement() {
Node rootElement = getFirstChild();
if (rootElement == null || !(rootElement instanceof SMILElement)) {
// The root doesn't exist. Create a new one.
rootElement = createElement("smil");
appendChild(rootElement);
}
return (SMILElement) rootElement;
}
/*
* SMILElement Interface
*/
public SMILElement getHead() {
Node rootElement = getDocumentElement();
Node headElement = rootElement.getFirstChild();
if (headElement == null || !(headElement instanceof SMILElement)) {
// The head doesn't exist. Create a new one.
headElement = createElement("head");
rootElement.appendChild(headElement);
}
return (SMILElement) headElement;
}
public SMILElement getBody() {
Node rootElement = getDocumentElement();
Node headElement = getHead();
Node bodyElement = headElement.getNextSibling();
if (bodyElement == null || !(bodyElement instanceof SMILElement)) {
// The body doesn't exist. Create a new one.
bodyElement = createElement("body");
rootElement.appendChild(bodyElement);
}
// Initialize the real sequential time container, which is body.
mSeqTimeContainer = new ElementSequentialTimeContainerImpl((SMILElement) bodyElement) {
public NodeList getTimeChildren() {
return getBody().getElementsByTagName("par");
}
public boolean beginElement() {
Event startEvent = createEvent("Event");
startEvent.initEvent(SMIL_DOCUMENT_START_EVENT, false, false);
dispatchEvent(startEvent);
return true;
}
public boolean endElement() {
Event endEvent = createEvent("Event");
endEvent.initEvent(SMIL_DOCUMENT_END_EVENT, false, false);
dispatchEvent(endEvent);
return true;
}
public void pauseElement() {
// TODO Auto-generated method stub
}
public void resumeElement() {
// TODO Auto-generated method stub
}
public void seekElement(float seekTo) {
// TODO Auto-generated method stub
}
ElementTime getParentElementTime() {
return null;
}
};
return (SMILElement) bodyElement;
}
public SMILLayoutElement getLayout() {
Node headElement = getHead();
Node layoutElement = null;
// Find the layout element under <code>HEAD</code>
layoutElement = headElement.getFirstChild();
while ((layoutElement != null) && !(layoutElement instanceof SMILLayoutElement)) {
layoutElement = layoutElement.getNextSibling();
}
if (layoutElement == null) {
// The layout doesn't exist. Create a default one.
layoutElement = new SmilLayoutElementImpl(this, "layout");
headElement.appendChild(layoutElement);
}
return (SMILLayoutElement) layoutElement;
}
/*
* DocumentEvent Interface
*/
public Event createEvent(String eventType) throws DOMException {
if ("Event".equals(eventType)) {
return new EventImpl();
} else {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Not supported interface");
}
}
}
@@ -1,48 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import com.android.mms.dom.ElementImpl;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILElement;
public class SmilElementImpl extends ElementImpl implements SMILElement {
/**
* This constructor is used by the factory methods of the SmilDocument.
*
* @param owner The SMIL document to which this element belongs to
* @param tagName The tag name of the element
*/
SmilElementImpl(SmilDocumentImpl owner, String tagName)
{
super(owner, tagName.toLowerCase());
}
public String getId() {
// TODO Auto-generated method stub
return null;
}
public void setId(String id) throws DOMException {
// TODO Auto-generated method stub
}
}
@@ -1,60 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.SMILLayoutElement;
import org.w3c.dom.smil.SMILRootLayoutElement;
public class SmilLayoutElementImpl extends SmilElementImpl implements
SMILLayoutElement {
SmilLayoutElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
public boolean getResolved() {
// TODO Auto-generated method stub
return false;
}
public String getType() {
return this.getAttribute("type");
}
public NodeList getRegions() {
return this.getElementsByTagName("region");
}
public SMILRootLayoutElement getRootLayout() {
NodeList childNodes = this.getChildNodes();
SMILRootLayoutElement rootLayoutNode = null;
int childrenCount = childNodes.getLength();
for (int i = 0; i < childrenCount; i++) {
if (childNodes.item(i).getNodeName().equals("root-layout")) {
rootLayoutNode = (SMILRootLayoutElement)childNodes.item(i);
}
}
if (null == rootLayoutNode) {
// root-layout node is not set. Create a default one.
rootLayoutNode = (SMILRootLayoutElement) getOwnerDocument().createElement("root-layout");
appendChild(rootLayoutNode);
}
return rootLayoutNode;
}
}
@@ -1,340 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import android.util.Log;
import com.android.mms.dom.events.EventImpl;
import org.w3c.dom.DOMException;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILMediaElement;
import org.w3c.dom.smil.TimeList;
public class SmilMediaElementImpl extends SmilElementImpl implements
SMILMediaElement {
public final static String SMIL_MEDIA_START_EVENT = "SmilMediaStart";
public final static String SMIL_MEDIA_END_EVENT = "SmilMediaEnd";
public final static String SMIL_MEDIA_PAUSE_EVENT = "SmilMediaPause";
public final static String SMIL_MEDIA_SEEK_EVENT = "SmilMediaSeek";
private final static String TAG = "Mms:smil";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
ElementTime mElementTime = new ElementTimeImpl(this) {
private Event createEvent(String eventType) {
DocumentEvent doc =
(DocumentEvent)SmilMediaElementImpl.this.getOwnerDocument();
Event event = doc.createEvent("Event");
event.initEvent(eventType, false, false);
if (LOCAL_LOGV) Log.v(TAG, "Dispatching 'begin' event to "
+ SmilMediaElementImpl.this.getTagName() + " "
+ SmilMediaElementImpl.this.getSrc() + " at "
+ System.currentTimeMillis());
return event;
}
private Event createEvent(String eventType, int seekTo) {
DocumentEvent doc =
(DocumentEvent)SmilMediaElementImpl.this.getOwnerDocument();
EventImpl event = (EventImpl) doc.createEvent("Event");
event.initEvent(eventType, false, false, seekTo);
if (LOCAL_LOGV) Log.v(TAG, "Dispatching 'begin' event to "
+ SmilMediaElementImpl.this.getTagName() + " "
+ SmilMediaElementImpl.this.getSrc() + " at "
+ System.currentTimeMillis());
return event;
}
public boolean beginElement() {
Event startEvent = createEvent(SMIL_MEDIA_START_EVENT);
dispatchEvent(startEvent);
return true;
}
public boolean endElement() {
Event endEvent = createEvent(SMIL_MEDIA_END_EVENT);
dispatchEvent(endEvent);
return true;
}
public void resumeElement() {
Event resumeEvent = createEvent(SMIL_MEDIA_START_EVENT);
dispatchEvent(resumeEvent);
}
public void pauseElement() {
Event pauseEvent = createEvent(SMIL_MEDIA_PAUSE_EVENT);
dispatchEvent(pauseEvent);
}
public void seekElement(float seekTo) {
Event seekEvent = createEvent(SMIL_MEDIA_SEEK_EVENT, (int) seekTo);
dispatchEvent(seekEvent);
}
@Override
public float getDur() {
float dur = super.getDur();
if (dur == 0) {
// Duration is not specified, So get the implicit duration.
String tag = getTagName();
if (tag.equals("video") || tag.equals("audio")) {
// Continuous media
// FIXME Should get the duration of the media. "indefinite" instead here.
dur = -1.0F;
} else if (tag.equals("text") || tag.equals("img")) {
// Discrete media
dur = 0;
} else {
Log.w(TAG, "Unknown media type");
}
}
return dur;
}
@Override
ElementTime getParentElementTime() {
return ((SmilParElementImpl) mSmilElement.getParentNode()).mParTimeContainer;
}
};
/*
* Internal Interface
*/
SmilMediaElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
/*
* SMILMediaElement Interface
*/
public String getAbstractAttr() {
return this.getAttribute("abstract");
}
public String getAlt() {
return this.getAttribute("alt");
}
public String getAuthor() {
return this.getAttribute("author");
}
public String getClipBegin() {
return this.getAttribute("clipBegin");
}
public String getClipEnd() {
return this.getAttribute("clipEnd");
}
public String getCopyright() {
return this.getAttribute("copyright");
}
public String getLongdesc() {
return this.getAttribute("longdesc");
}
public String getPort() {
return this.getAttribute("port");
}
public String getReadIndex() {
return this.getAttribute("readIndex");
}
public String getRtpformat() {
return this.getAttribute("rtpformat");
}
public String getSrc() {
return this.getAttribute("src");
}
public String getStripRepeat() {
return this.getAttribute("stripRepeat");
}
public String getTitle() {
return this.getAttribute("title");
}
public String getTransport() {
return this.getAttribute("transport");
}
public String getType() {
return this.getAttribute("type");
}
public void setAbstractAttr(String abstractAttr) throws DOMException {
this.setAttribute("abstract", abstractAttr);
}
public void setAlt(String alt) throws DOMException {
this.setAttribute("alt", alt);
}
public void setAuthor(String author) throws DOMException {
this.setAttribute("author", author);
}
public void setClipBegin(String clipBegin) throws DOMException {
this.setAttribute("clipBegin", clipBegin);
}
public void setClipEnd(String clipEnd) throws DOMException {
this.setAttribute("clipEnd", clipEnd);
}
public void setCopyright(String copyright) throws DOMException {
this.setAttribute("copyright", copyright);
}
public void setLongdesc(String longdesc) throws DOMException {
this.setAttribute("longdesc", longdesc);
}
public void setPort(String port) throws DOMException {
this.setAttribute("port", port);
}
public void setReadIndex(String readIndex) throws DOMException {
this.setAttribute("readIndex", readIndex);
}
public void setRtpformat(String rtpformat) throws DOMException {
this.setAttribute("rtpformat", rtpformat);
}
public void setSrc(String src) throws DOMException {
this.setAttribute("src", src);
}
public void setStripRepeat(String stripRepeat) throws DOMException {
this.setAttribute("stripRepeat", stripRepeat);
}
public void setTitle(String title) throws DOMException {
this.setAttribute("title", title);
}
public void setTransport(String transport) throws DOMException {
this.setAttribute("transport", transport);
}
public void setType(String type) throws DOMException {
this.setAttribute("type", type);
}
/*
* TimeElement Interface
*/
public boolean beginElement() {
return mElementTime.beginElement();
}
public boolean endElement() {
return mElementTime.endElement();
}
public TimeList getBegin() {
return mElementTime.getBegin();
}
public float getDur() {
return mElementTime.getDur();
}
public TimeList getEnd() {
return mElementTime.getEnd();
}
public short getFill() {
return mElementTime.getFill();
}
public short getFillDefault() {
return mElementTime.getFillDefault();
}
public float getRepeatCount() {
return mElementTime.getRepeatCount();
}
public float getRepeatDur() {
return mElementTime.getRepeatDur();
}
public short getRestart() {
return mElementTime.getRestart();
}
public void pauseElement() {
mElementTime.pauseElement();
}
public void resumeElement() {
mElementTime.resumeElement();
}
public void seekElement(float seekTo) {
mElementTime.seekElement(seekTo);
}
public void setBegin(TimeList begin) throws DOMException {
mElementTime.setBegin(begin);
}
public void setDur(float dur) throws DOMException {
mElementTime.setDur(dur);
}
public void setEnd(TimeList end) throws DOMException {
mElementTime.setEnd(end);
}
public void setFill(short fill) throws DOMException {
mElementTime.setFill(fill);
}
public void setFillDefault(short fillDefault) throws DOMException {
mElementTime.setFillDefault(fillDefault);
}
public void setRepeatCount(float repeatCount) throws DOMException {
mElementTime.setRepeatCount(repeatCount);
}
public void setRepeatDur(float repeatDur) throws DOMException {
mElementTime.setRepeatDur(repeatDur);
}
public void setRestart(short restart) throws DOMException {
mElementTime.setRestart(restart);
}
}
@@ -1,218 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import org.w3c.dom.DOMException;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
import org.w3c.dom.smil.ElementParallelTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILParElement;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
public class SmilParElementImpl extends SmilElementImpl implements SMILParElement {
public final static String SMIL_SLIDE_START_EVENT = "SmilSlideStart";
public final static String SMIL_SLIDE_END_EVENT = "SmilSlideEnd";
ElementParallelTimeContainer mParTimeContainer =
new ElementParallelTimeContainerImpl(this) {
@Override
public TimeList getBegin() {
/*
* For children of a sequence, the only legal value for begin is
* a (single) non-negative offset value.
*/
TimeList beginTimeList = super.getBegin();
if (beginTimeList.getLength() > 1) {
ArrayList<Time> singleTimeContainer = new ArrayList<>();
singleTimeContainer.add(beginTimeList.item(0));
beginTimeList = new TimeListImpl(singleTimeContainer);
}
return beginTimeList;
}
public NodeList getTimeChildren() {
return getChildNodes();
}
public boolean beginElement() {
DocumentEvent doc = (DocumentEvent) SmilParElementImpl.this.getOwnerDocument();
Event startEvent = doc.createEvent("Event");
startEvent.initEvent(SMIL_SLIDE_START_EVENT, false, false);
dispatchEvent(startEvent);
return true;
}
public boolean endElement() {
DocumentEvent doc = (DocumentEvent) SmilParElementImpl.this.getOwnerDocument();
Event endEvent = doc.createEvent("Event");
endEvent.initEvent(SMIL_SLIDE_END_EVENT, false, false);
dispatchEvent(endEvent);
return true;
}
public void pauseElement() {
// TODO Auto-generated method stub
}
public void resumeElement() {
// TODO Auto-generated method stub
}
public void seekElement(float seekTo) {
// TODO Auto-generated method stub
}
ElementTime getParentElementTime() {
return ((SmilDocumentImpl) mSmilElement.getOwnerDocument()).mSeqTimeContainer;
}
};
/*
* Internal Interface
*/
SmilParElementImpl(SmilDocumentImpl owner, String tagName)
{
super(owner, tagName.toUpperCase());
}
int getBeginConstraints() {
/*
* For children of a sequence, the only legal value for begin is
* a (single) non-negative offset value.
*/
return (TimeImpl.ALLOW_OFFSET_VALUE); // Do not set ALLOW_NEGATIVE_VALUE
}
/*
* ElementParallelTimeContainer
*/
public String getEndSync() {
return mParTimeContainer.getEndSync();
}
public float getImplicitDuration() {
return mParTimeContainer.getImplicitDuration();
}
public void setEndSync(String endSync) throws DOMException {
mParTimeContainer.setEndSync(endSync);
}
public NodeList getActiveChildrenAt(float instant) {
return mParTimeContainer.getActiveChildrenAt(instant);
}
public NodeList getTimeChildren() {
return mParTimeContainer.getTimeChildren();
}
public boolean beginElement() {
return mParTimeContainer.beginElement();
}
public boolean endElement() {
return mParTimeContainer.endElement();
}
public TimeList getBegin() {
return mParTimeContainer.getBegin();
}
public float getDur() {
return mParTimeContainer.getDur();
}
public TimeList getEnd() {
return mParTimeContainer.getEnd();
}
public short getFill() {
return mParTimeContainer.getFill();
}
public short getFillDefault() {
return mParTimeContainer.getFillDefault();
}
public float getRepeatCount() {
return mParTimeContainer.getRepeatCount();
}
public float getRepeatDur() {
return mParTimeContainer.getRepeatDur();
}
public short getRestart() {
return mParTimeContainer.getRestart();
}
public void pauseElement() {
mParTimeContainer.pauseElement();
}
public void resumeElement() {
mParTimeContainer.resumeElement();
}
public void seekElement(float seekTo) {
mParTimeContainer.seekElement(seekTo);
}
public void setBegin(TimeList begin) throws DOMException {
mParTimeContainer.setBegin(begin);
}
public void setDur(float dur) throws DOMException {
mParTimeContainer.setDur(dur);
}
public void setEnd(TimeList end) throws DOMException {
mParTimeContainer.setEnd(end);
}
public void setFill(short fill) throws DOMException {
mParTimeContainer.setFill(fill);
}
public void setFillDefault(short fillDefault) throws DOMException {
mParTimeContainer.setFillDefault(fillDefault);
}
public void setRepeatCount(float repeatCount) throws DOMException {
mParTimeContainer.setRepeatCount(repeatCount);
}
public void setRepeatDur(float repeatDur) throws DOMException {
mParTimeContainer.setRepeatDur(repeatDur);
}
public void setRestart(short restart) throws DOMException {
mParTimeContainer.setRestart(restart);
}
}
@@ -1,744 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import android.util.Log;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.smil.ElementParallelTimeContainer;
import org.w3c.dom.smil.ElementSequentialTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
/**
* The SmilPlayer is responsible for playing, stopping, pausing and resuming a SMIL tree.
* <li>It creates a whole timeline before playing.</li>
* <li>The player runs in a different thread which intends not to block the main thread.</li>
*/
public class SmilPlayer implements Runnable {
private static final String TAG = "Mms/smil";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private static final int TIMESLICE = 200;
private enum SmilPlayerState {
INITIALIZED,
PLAYING,
PLAYED,
PAUSED,
STOPPED,
}
private enum SmilPlayerAction {
NO_ACTIVE_ACTION,
RELOAD,
STOP,
PAUSE,
START,
NEXT,
PREV
}
public static final String MEDIA_TIME_UPDATED_EVENT = "mediaTimeUpdated";
private static final Comparator<TimelineEntry> sTimelineEntryComparator =
new Comparator<TimelineEntry>() {
public int compare(TimelineEntry o1, TimelineEntry o2) {
return Double.compare(o1.getOffsetTime(), o2.getOffsetTime());
}
};
private static SmilPlayer sPlayer;
private long mCurrentTime;
private int mCurrentElement;
private int mCurrentSlide;
private ArrayList<TimelineEntry> mAllEntries;
private ElementTime mRoot;
private Thread mPlayerThread;
private SmilPlayerState mState = SmilPlayerState.INITIALIZED;
private SmilPlayerAction mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
private ArrayList<ElementTime> mActiveElements;
private Event mMediaTimeUpdatedEvent;
private static ArrayList<TimelineEntry> getParTimeline(
ElementParallelTimeContainer par, double offset, double maxOffset) {
ArrayList<TimelineEntry> timeline = new ArrayList<>();
// Set my begin at first
TimeList myBeginList = par.getBegin();
/*
* Begin list only contain 1 begin time which has been resolved.
* @see com.android.mms.dom.smil.ElementParallelTimeContainerImpl#getBegin()
*/
Time begin = myBeginList.item(0);
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset > maxOffset) {
// This element can't be started.
return timeline;
}
TimelineEntry myBegin = new TimelineEntry(beginOffset, par, TimelineEntry.ACTION_BEGIN);
timeline.add(myBegin);
TimeList myEndList = par.getEnd();
/*
* End list only contain 1 end time which has been resolved.
* @see com.android.mms.dom.smil.ElementParallelTimeContainerImpl#getEnd()
*/
Time end = myEndList.item(0);
double endOffset = end.getResolvedOffset() + offset;
if (endOffset > maxOffset) {
endOffset = maxOffset;
}
TimelineEntry myEnd = new TimelineEntry(endOffset, par, TimelineEntry.ACTION_END);
maxOffset = endOffset;
NodeList children = par.getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
ArrayList<TimelineEntry> childTimeline = getTimeline(child, offset, maxOffset);
timeline.addAll(childTimeline);
}
Collections.sort(timeline, sTimelineEntryComparator);
// Add end-event to timeline for all active children
NodeList activeChildrenAtEnd = par.getActiveChildrenAt(
(float) (endOffset - offset) * 1000);
for (int i = 0; i < activeChildrenAtEnd.getLength(); ++i) {
timeline.add(new TimelineEntry(endOffset,
(ElementTime) activeChildrenAtEnd.item(i),
TimelineEntry.ACTION_END));
}
// Set my end at last
timeline.add(myEnd);
return timeline;
}
private static ArrayList<TimelineEntry> getSeqTimeline(
ElementSequentialTimeContainer seq, double offset, double maxOffset) {
ArrayList<TimelineEntry> timeline = new ArrayList<>();
double orgOffset = offset;
// Set my begin at first
TimeList myBeginList = seq.getBegin();
/*
* Begin list only contain 1 begin time which has been resolved.
* @see com.android.mms.dom.smil.ElementSequentialTimeContainerImpl#getBegin()
*/
Time begin = myBeginList.item(0);
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset > maxOffset) {
// This element can't be started.
return timeline;
}
TimelineEntry myBegin = new TimelineEntry(beginOffset, seq, TimelineEntry.ACTION_BEGIN);
timeline.add(myBegin);
TimeList myEndList = seq.getEnd();
/*
* End list only contain 1 end time which has been resolved.
* @see com.android.mms.dom.smil.ElementSequentialTimeContainerImpl#getEnd()
*/
Time end = myEndList.item(0);
double endOffset = end.getResolvedOffset() + offset;
if (endOffset > maxOffset) {
endOffset = maxOffset;
}
TimelineEntry myEnd = new TimelineEntry(endOffset, seq, TimelineEntry.ACTION_END);
maxOffset = endOffset;
// Get children's timelines
NodeList children = seq.getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
ArrayList<TimelineEntry> childTimeline = getTimeline(child, offset, maxOffset);
timeline.addAll(childTimeline);
// Since the child timeline has been sorted, the offset of the last one is the biggest.
offset = childTimeline.get(childTimeline.size() - 1).getOffsetTime();
}
// Add end-event to timeline for all active children
NodeList activeChildrenAtEnd = seq.getActiveChildrenAt(
(float) (endOffset - orgOffset));
for (int i = 0; i < activeChildrenAtEnd.getLength(); ++i) {
timeline.add(new TimelineEntry(endOffset,
(ElementTime) activeChildrenAtEnd.item(i),
TimelineEntry.ACTION_END));
}
// Set my end at last
timeline.add(myEnd);
return timeline;
}
private static ArrayList<TimelineEntry> getTimeline(ElementTime element,
double offset, double maxOffset) {
if (element instanceof ElementParallelTimeContainer) {
return getParTimeline((ElementParallelTimeContainer) element, offset, maxOffset);
} else if (element instanceof ElementSequentialTimeContainer) {
return getSeqTimeline((ElementSequentialTimeContainer) element, offset, maxOffset);
} else {
// Not ElementTimeContainer here
ArrayList<TimelineEntry> timeline = new ArrayList<>();
TimeList beginList = element.getBegin();
for (int i = 0; i < beginList.getLength(); ++i) {
Time begin = beginList.item(i);
if (begin.getResolved()) {
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset <= maxOffset) {
TimelineEntry entry = new TimelineEntry(beginOffset,
element, TimelineEntry.ACTION_BEGIN);
timeline.add(entry);
}
}
}
TimeList endList = element.getEnd();
for (int i = 0; i < endList.getLength(); ++i) {
Time end = endList.item(i);
if (end.getResolved()) {
double endOffset = end.getResolvedOffset() + offset;
if (endOffset <= maxOffset) {
TimelineEntry entry = new TimelineEntry(endOffset,
element, TimelineEntry.ACTION_END);
timeline.add(entry);
}
}
}
Collections.sort(timeline, sTimelineEntryComparator);
return timeline;
}
}
private SmilPlayer() {
// Private constructor
}
public static SmilPlayer getPlayer() {
if (sPlayer == null) {
sPlayer = new SmilPlayer();
}
return sPlayer;
}
public synchronized boolean isPlayingState() {
return mState == SmilPlayerState.PLAYING;
}
public synchronized boolean isPlayedState() {
return mState == SmilPlayerState.PLAYED;
}
public synchronized boolean isPausedState() {
return mState == SmilPlayerState.PAUSED;
}
public synchronized boolean isStoppedState() {
return mState == SmilPlayerState.STOPPED;
}
private synchronized boolean isPauseAction() {
return mAction == SmilPlayerAction.PAUSE;
}
private synchronized boolean isStartAction() {
return mAction == SmilPlayerAction.START;
}
private synchronized boolean isStopAction() {
return mAction == SmilPlayerAction.STOP;
}
private synchronized boolean isReloadAction() {
return mAction == SmilPlayerAction.RELOAD;
}
private synchronized boolean isNextAction() {
return mAction == SmilPlayerAction.NEXT;
}
private synchronized boolean isPrevAction() {
return mAction == SmilPlayerAction.PREV;
}
public synchronized void init(ElementTime root) {
mRoot = root;
mAllEntries = getTimeline(mRoot, 0, Long.MAX_VALUE);
mMediaTimeUpdatedEvent = ((DocumentEvent) mRoot).createEvent("Event");
mMediaTimeUpdatedEvent.initEvent(MEDIA_TIME_UPDATED_EVENT, false, false);
mActiveElements = new ArrayList<>();
}
public synchronized void play() {
if (!isPlayingState()) {
mCurrentTime = 0;
mCurrentElement = 0;
mCurrentSlide = 0;
mPlayerThread = new Thread(this, "SmilPlayer thread");
mState = SmilPlayerState.PLAYING;
mPlayerThread.start();
} else {
Log.w(TAG, "Error State: Playback is playing!");
}
}
public synchronized void pause() {
if (isPlayingState()) {
mAction = SmilPlayerAction.PAUSE;
notifyAll();
} else {
Log.w(TAG, "Error State: Playback is not playing!");
}
}
public synchronized void start() {
if (isPausedState()) {
resumeActiveElements();
mAction = SmilPlayerAction.START;
notifyAll();
} else if (isPlayedState()) {
play();
} else {
Log.w(TAG, "Error State: Playback can not be started!");
}
}
public synchronized void stop() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.STOP;
notifyAll();
} else if (isPlayedState()) {
actionStop();
}
}
public synchronized void stopWhenReload() {
endActiveElements();
}
public synchronized void reload() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.RELOAD;
notifyAll();
} else if (isPlayedState()) {
actionReload();
}
}
public synchronized void next() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.NEXT;
notifyAll();
}
}
public synchronized void prev() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.PREV;
notifyAll();
}
}
private synchronized boolean isBeginOfSlide(TimelineEntry entry) {
return (TimelineEntry.ACTION_BEGIN == entry.getAction())
&& (entry.getElement() instanceof SmilParElementImpl);
}
private synchronized void reloadActiveSlide() {
mActiveElements.clear();
beginSmilDocument();
for (int i = mCurrentSlide; i < mCurrentElement; i++) {
TimelineEntry entry = mAllEntries.get(i);
actionEntry(entry);
}
seekActiveMedia();
}
private synchronized void beginSmilDocument() {
TimelineEntry entry = mAllEntries.get(0);
actionEntry(entry);
}
private synchronized double getOffsetTime(ElementTime element) {
for (int i = mCurrentSlide; i < mCurrentElement; i++) {
TimelineEntry entry = mAllEntries.get(i);
if (element.equals(entry.getElement())) {
return entry.getOffsetTime() * 1000; // in ms
}
}
return -1;
}
private synchronized void seekActiveMedia() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (element instanceof SmilParElementImpl) {
return;
}
double offset = getOffsetTime(element);
if ((offset >= 0) && (offset <= mCurrentTime)) {
if (LOCAL_LOGV) Log.v(TAG, "[SEEK] " + " at " + mCurrentTime
+ " " + element);
element.seekElement( (float) (mCurrentTime - offset) );
}
}
}
private synchronized void waitForEntry(long interval)
throws InterruptedException {
if (LOCAL_LOGV) Log.v(TAG, "Waiting for " + interval + "ms.");
long overhead = 0;
while (interval > 0) {
long startAt = System.currentTimeMillis();
long sleep = Math.min(interval, TIMESLICE);
if (overhead < sleep) {
wait(sleep - overhead);
mCurrentTime += sleep;
} else {
sleep = 0;
mCurrentTime += overhead;
}
if (isStopAction() || isReloadAction() || isPauseAction() || isNextAction() ||
isPrevAction()) {
return;
}
((EventTarget) mRoot).dispatchEvent(mMediaTimeUpdatedEvent);
interval -= TIMESLICE;
overhead = System.currentTimeMillis() - startAt - sleep;
}
}
public synchronized int getDuration() {
if ((mAllEntries != null) && !mAllEntries.isEmpty()) {
return (int) mAllEntries.get(mAllEntries.size() - 1).mOffsetTime * 1000;
}
return 0;
}
public synchronized int getCurrentPosition() {
return (int) mCurrentTime;
}
private synchronized void endActiveElements() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) Log.v(TAG, "[STOP] " + " at " + mCurrentTime + " " + element);
element.endElement();
}
}
private synchronized void pauseActiveElements() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) Log.v(TAG, "[PAUSE] " + " at " + mCurrentTime + " " + element);
element.pauseElement();
}
}
private synchronized void resumeActiveElements() {
int size = mActiveElements.size();
for (int i = 0; i < size; i++) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) Log.v(TAG, "[RESUME] " + " at " + mCurrentTime + " " + element);
element.resumeElement();
}
}
private synchronized void waitForWakeUp() {
try {
while ( !(isStartAction() || isStopAction() || isReloadAction() ||
isNextAction() || isPrevAction()) ) {
wait(TIMESLICE);
}
if (isStartAction()) {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
mState = SmilPlayerState.PLAYING;
}
} catch (InterruptedException e) {
Log.e(TAG, "Unexpected InterruptedException.", e);
}
}
private synchronized void actionEntry(TimelineEntry entry) {
switch (entry.getAction()) {
case TimelineEntry.ACTION_BEGIN:
if (LOCAL_LOGV) Log.v(TAG, "[START] " + " at " + mCurrentTime + " "
+ entry.getElement());
entry.getElement().beginElement();
mActiveElements.add(entry.getElement());
break;
case TimelineEntry.ACTION_END:
if (LOCAL_LOGV) Log.v(TAG, "[STOP] " + " at " + mCurrentTime + " "
+ entry.getElement());
entry.getElement().endElement();
mActiveElements.remove(entry.getElement());
break;
default:
break;
}
}
private synchronized TimelineEntry reloadCurrentEntry() {
// Check if the position is less than size of all entries
if (mCurrentElement < mAllEntries.size()) {
return mAllEntries.get(mCurrentElement);
} else {
return null;
}
}
private void stopCurrentSlide() {
HashSet<TimelineEntry> skippedEntries = new HashSet<>();
int totalEntries = mAllEntries.size();
for (int i = mCurrentElement; i < totalEntries; i++) {
// Stop any started entries, and skip the not started entries until
// meeting the end of slide
TimelineEntry entry = mAllEntries.get(i);
int action = entry.getAction();
if (entry.getElement() instanceof SmilParElementImpl &&
action == TimelineEntry.ACTION_END) {
actionEntry(entry);
mCurrentElement = i;
break;
} else if (action == TimelineEntry.ACTION_END && !skippedEntries.contains(entry)) {
actionEntry(entry);
} else if (action == TimelineEntry.ACTION_BEGIN) {
skippedEntries.add(entry);
}
}
}
private TimelineEntry loadNextSlide() {
TimelineEntry entry;
int totalEntries = mAllEntries.size();
for (int i = mCurrentElement; i < totalEntries; i++) {
entry = mAllEntries.get(i);
if (isBeginOfSlide(entry)) {
mCurrentElement = i;
mCurrentSlide = i;
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
return entry;
}
}
// No slide, finish play back
mCurrentElement++;
entry = null;
if (mCurrentElement < totalEntries) {
entry = mAllEntries.get(mCurrentElement);
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
}
return entry;
}
private TimelineEntry loadPrevSlide() {
int skippedSlides = 1;
int latestBeginEntryIndex = -1;
for (int i = mCurrentSlide; i >= 0; i--) {
TimelineEntry entry = mAllEntries.get(i);
if (isBeginOfSlide(entry)) {
latestBeginEntryIndex = i;
if (0 == skippedSlides-- ) {
mCurrentElement = i;
mCurrentSlide = i;
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
return entry;
}
}
}
if (latestBeginEntryIndex != -1) {
mCurrentElement = latestBeginEntryIndex;
mCurrentSlide = latestBeginEntryIndex;
return mAllEntries.get(mCurrentElement);
}
return null;
}
private synchronized TimelineEntry actionNext() {
stopCurrentSlide();
return loadNextSlide();
}
private synchronized TimelineEntry actionPrev() {
stopCurrentSlide();
return loadPrevSlide();
}
private synchronized void actionPause() {
pauseActiveElements();
mState = SmilPlayerState.PAUSED;
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
private synchronized void actionStop() {
endActiveElements();
mCurrentTime = 0;
mCurrentElement = 0;
mCurrentSlide = 0;
mState = SmilPlayerState.STOPPED;
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
private synchronized void actionReload() {
reloadActiveSlide();
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
public void run() {
if (isStoppedState()) {
return;
}
if (LOCAL_LOGV) {
dumpAllEntries();
}
// Play the Element by following the timeline
int size = mAllEntries.size();
for (mCurrentElement = 0; mCurrentElement < size; mCurrentElement++) {
TimelineEntry entry = mAllEntries.get(mCurrentElement);
if (isBeginOfSlide(entry)) {
mCurrentSlide = mCurrentElement;
}
long offset = (long) (entry.getOffsetTime() * 1000); // in ms.
while (offset > mCurrentTime) {
try {
waitForEntry(offset - mCurrentTime);
} catch (InterruptedException e) {
Log.e(TAG, "Unexpected InterruptedException.", e);
}
while (isPauseAction() || isStopAction() || isReloadAction() || isNextAction() ||
isPrevAction()) {
if (isPauseAction()) {
actionPause();
waitForWakeUp();
}
if (isStopAction()) {
actionStop();
return;
}
if (isReloadAction()) {
actionReload();
entry = reloadCurrentEntry();
if (entry == null)
return;
if (isPausedState()) {
mAction = SmilPlayerAction.PAUSE;
}
}
if (isNextAction()) {
TimelineEntry nextEntry = actionNext();
if (nextEntry != null) {
entry = nextEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
if (isPrevAction()) {
TimelineEntry prevEntry = actionPrev();
if (prevEntry != null) {
entry = prevEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
}
}
mCurrentTime = offset;
actionEntry(entry);
}
mState = SmilPlayerState.PLAYED;
}
private static final class TimelineEntry {
final static int ACTION_BEGIN = 0;
final static int ACTION_END = 1;
private final double mOffsetTime;
private final ElementTime mElement;
private final int mAction;
public TimelineEntry(double offsetTime, ElementTime element, int action) {
mOffsetTime = offsetTime;
mElement = element;
mAction = action;
}
public double getOffsetTime() {
return mOffsetTime;
}
public ElementTime getElement() {
return mElement;
}
public int getAction() {
return mAction;
}
public String toString() {
return "Type = " + mElement + " offset = " + getOffsetTime() + " action = " + getAction();
}
}
private void dumpAllEntries() {
for (TimelineEntry entry : mAllEntries) {
if (LOCAL_LOGV) Log.v(TAG, "[Entry] "+ entry);
else break;
}
}
}
@@ -1,29 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import org.w3c.dom.smil.SMILRefElement;
public class SmilRefElementImpl extends SmilRegionMediaElementImpl implements
SMILRefElement {
SmilRefElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
}
@@ -1,264 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import android.util.Log;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILRegionElement;
public class SmilRegionElementImpl extends SmilElementImpl implements
SMILRegionElement {
/*
* Internal Interface
*/
private static final String HIDDEN_ATTRIBUTE = "hidden";
private static final String SLICE_ATTRIBUTE = "slice";
private static final String SCROLL_ATTRIBUTE = "scroll";
private static final String MEET_ATTRIBUTE = "meet";
private static final String FILL_ATTRIBUTE = "fill";
private static final String ID_ATTRIBUTE_NAME = "id";
private static final String WIDTH_ATTRIBUTE_NAME = "width";
private static final String TITLE_ATTRIBUTE_NAME = "title";
private static final String HEIGHT_ATTRIBUTE_NAME = "height";
private static final String BACKGROUND_COLOR_ATTRIBUTE_NAME = "backgroundColor";
private static final String Z_INDEX_ATTRIBUTE_NAME = "z-index";
private static final String TOP_ATTRIBUTE_NAME = "top";
private static final String LEFT_ATTRIBUTE_NAME = "left";
private static final String RIGHT_ATTRIBUTE_NAME = "right";
private static final String BOTTOM_ATTRIBUTE_NAME = "bottom";
private static final String FIT_ATTRIBUTE_NAME = "fit";
private static final String TAG = "SmilRegionElementImpl";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
SmilRegionElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
/*
* SMILRegionElement Interface
*/
public String getFit() {
String fit = getAttribute(FIT_ATTRIBUTE_NAME);
if (FILL_ATTRIBUTE.equalsIgnoreCase(fit)) {
return FILL_ATTRIBUTE;
} else if (MEET_ATTRIBUTE.equalsIgnoreCase(fit)) {
return MEET_ATTRIBUTE;
} else if (SCROLL_ATTRIBUTE.equalsIgnoreCase(fit)) {
return SCROLL_ATTRIBUTE;
} else if (SLICE_ATTRIBUTE.equalsIgnoreCase(fit)) {
return SLICE_ATTRIBUTE;
} else {
return HIDDEN_ATTRIBUTE;
}
}
public int getLeft() {
try {
return parseRegionLength(getAttribute(LEFT_ATTRIBUTE_NAME), true);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) Log.v(TAG, "Left attribute is not set or incorrect.");
}
try {
int bbw = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth();
int right = parseRegionLength(getAttribute(RIGHT_ATTRIBUTE_NAME), true);
int width = parseRegionLength(getAttribute(WIDTH_ATTRIBUTE_NAME), true);
return bbw - right - width;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) Log.v(TAG, "Right or width attribute is not set or incorrect.");
}
return 0;
}
public int getTop() {
try {
return parseRegionLength(getAttribute(TOP_ATTRIBUTE_NAME), false);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) Log.v(TAG, "Top attribute is not set or incorrect.");
}
try {
int bbh = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight();
int bottom = parseRegionLength(getAttribute(BOTTOM_ATTRIBUTE_NAME), false);
int height = parseRegionLength(getAttribute(HEIGHT_ATTRIBUTE_NAME), false);
return bbh - bottom - height;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) Log.v(TAG, "Bottom or height attribute is not set or incorrect.");
}
return 0;
}
public int getZIndex() {
try {
return Integer.parseInt(this.getAttribute(Z_INDEX_ATTRIBUTE_NAME));
} catch (NumberFormatException _) {
return 0;
}
}
public void setFit(String fit) throws DOMException {
if (fit.equalsIgnoreCase(FILL_ATTRIBUTE)
|| fit.equalsIgnoreCase(MEET_ATTRIBUTE)
|| fit.equalsIgnoreCase(SCROLL_ATTRIBUTE)
|| fit.equalsIgnoreCase(SLICE_ATTRIBUTE)) {
this.setAttribute(FIT_ATTRIBUTE_NAME, fit.toLowerCase());
} else {
this.setAttribute(FIT_ATTRIBUTE_NAME, HIDDEN_ATTRIBUTE);
}
}
public void setLeft(int left) throws DOMException {
this.setAttribute(LEFT_ATTRIBUTE_NAME, String.valueOf(left));
}
public void setTop(int top) throws DOMException {
this.setAttribute(TOP_ATTRIBUTE_NAME, String.valueOf(top));
}
public void setZIndex(int zIndex) throws DOMException {
if (zIndex > 0) {
this.setAttribute(Z_INDEX_ATTRIBUTE_NAME, Integer.toString(zIndex));
} else {
this.setAttribute(Z_INDEX_ATTRIBUTE_NAME, Integer.toString(0));
}
}
public String getBackgroundColor() {
return this.getAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME);
}
public int getHeight() {
try {
final int height = parseRegionLength(getAttribute(HEIGHT_ATTRIBUTE_NAME), false);
return height == 0 ?
((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight() :
height;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) Log.v(TAG, "Height attribute is not set or incorrect.");
}
int bbh = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight();
try {
bbh -= parseRegionLength(getAttribute(TOP_ATTRIBUTE_NAME), false);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) Log.v(TAG, "Top attribute is not set or incorrect.");
}
try {
bbh -= parseRegionLength(getAttribute(BOTTOM_ATTRIBUTE_NAME), false);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) Log.v(TAG, "Bottom attribute is not set or incorrect.");
}
return bbh;
}
public String getTitle() {
return this.getAttribute(TITLE_ATTRIBUTE_NAME);
}
public int getWidth() {
try {
final int width = parseRegionLength(getAttribute(WIDTH_ATTRIBUTE_NAME), true);
return width == 0 ?
((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth() :
width;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) Log.v(TAG, "Width attribute is not set or incorrect.");
}
int bbw = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth();
try {
bbw -= parseRegionLength(getAttribute(LEFT_ATTRIBUTE_NAME), true);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) Log.v(TAG, "Left attribute is not set or incorrect.");
}
try {
bbw -= parseRegionLength(getAttribute(RIGHT_ATTRIBUTE_NAME), true);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) Log.v(TAG, "Right attribute is not set or incorrect.");
}
return bbw;
}
public void setBackgroundColor(String backgroundColor) throws DOMException {
this.setAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME, backgroundColor);
}
public void setHeight(int height) throws DOMException {
this.setAttribute(HEIGHT_ATTRIBUTE_NAME, String.valueOf(height) + "px");
}
public void setTitle(String title) throws DOMException {
this.setAttribute(TITLE_ATTRIBUTE_NAME, title);
}
public void setWidth(int width) throws DOMException {
this.setAttribute(WIDTH_ATTRIBUTE_NAME, String.valueOf(width) + "px");
}
/*
* SMILElement Interface
*/
@Override
public String getId() {
return this.getAttribute(ID_ATTRIBUTE_NAME);
}
@Override
public void setId(String id) throws DOMException {
this.setAttribute(ID_ATTRIBUTE_NAME, id);
}
/*
* Internal Interface
*/
private int parseRegionLength(String length, boolean horizontal) {
if (length.endsWith("px")) {
length = length.substring(0, length.indexOf("px"));
return Integer.parseInt(length);
} else if (length.endsWith("%")) {
double value = 0.01*Integer.parseInt(length.substring(0, length.length() - 1));
if (horizontal) {
value *= ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth();
} else {
value *= ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight();
}
return (int) Math.round(value);
} else {
return Integer.parseInt(length);
}
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return super.toString()
+ ": id=" + getId()
+ ", width=" + getWidth()
+ ", height=" + getHeight()
+ ", left=" + getLeft()
+ ", top=" + getTop();
}
}
@@ -1,53 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILRegionElement;
import org.w3c.dom.smil.SMILRegionMediaElement;
public class SmilRegionMediaElementImpl extends SmilMediaElementImpl implements
SMILRegionMediaElement {
private SMILRegionElement mRegion;
SmilRegionMediaElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
public SMILRegionElement getRegion() {
if (mRegion == null) {
SMILDocument doc = (SMILDocument)this.getOwnerDocument();
NodeList regions = doc.getLayout().getElementsByTagName("region");
SMILRegionElement region = null;
for (int i = 0; i < regions.getLength(); i++) {
region = (SMILRegionElement)regions.item(i);
if (region.getId().equals(this.getAttribute("region"))) {
mRegion = region;
}
}
}
return mRegion;
}
public void setRegion(SMILRegionElement region) {
this.setAttribute("region", region.getId());
mRegion = region;
}
}
@@ -1,84 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILRootLayoutElement;
public class SmilRootLayoutElementImpl extends SmilElementImpl implements
SMILRootLayoutElement {
private static final String WIDTH_ATTRIBUTE_NAME = "width";
private static final String HEIGHT_ATTRIBUTE_NAME = "height";
private static final String BACKGROUND_COLOR_ATTRIBUTE_NAME = "backgroundColor";
private static final String TITLE_ATTRIBUTE_NAME = "title";
SmilRootLayoutElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
public String getBackgroundColor() {
return this.getAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME);
}
public int getHeight() {
String heightString = this.getAttribute(HEIGHT_ATTRIBUTE_NAME);
return parseAbsoluteLength(heightString);
}
public String getTitle() {
return this.getAttribute(TITLE_ATTRIBUTE_NAME);
}
public int getWidth() {
String widthString = this.getAttribute(WIDTH_ATTRIBUTE_NAME);
return parseAbsoluteLength(widthString);
}
public void setBackgroundColor(String backgroundColor) throws DOMException {
this.setAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME, backgroundColor);
}
public void setHeight(int height) throws DOMException {
this.setAttribute(HEIGHT_ATTRIBUTE_NAME, String.valueOf(height) + "px");
}
public void setTitle(String title) throws DOMException {
this.setAttribute(TITLE_ATTRIBUTE_NAME, title);
}
public void setWidth(int width) throws DOMException {
this.setAttribute(WIDTH_ATTRIBUTE_NAME, String.valueOf(width) + "px");
}
/*
* Internal Interface
*/
private int parseAbsoluteLength(String length) {
if (length.endsWith("px")) {
length = length.substring(0, length.indexOf("px"));
}
try {
return Integer.parseInt(length);
} catch (NumberFormatException e) {
return 0;
}
}
}
@@ -1,295 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.smil.Time;
public class TimeImpl implements Time {
static final int ALLOW_INDEFINITE_VALUE = (1 << 0);
static final int ALLOW_OFFSET_VALUE = (1 << 1);
static final int ALLOW_SYNCBASE_VALUE = (1 << 2);
static final int ALLOW_SYNCTOPREV_VALUE = (1 << 3);
static final int ALLOW_EVENT_VALUE = (1 << 4);
static final int ALLOW_MARKER_VALUE = (1 << 5);
static final int ALLOW_WALLCLOCK_VALUE = (1 << 6);
static final int ALLOW_NEGATIVE_VALUE = (1 << 7);
static final int ALLOW_ALL = 0xFF;
short mTimeType;
boolean mResolved;
double mResolvedOffset;
/**
* Creates a TimeImpl representation of a time-value represented as a String.
* Time-values have the following syntax:
* <p>
* <pre>
* Time-val ::= ( smil-1.0-syncbase-value
* | "indefinite"
* | offset-value
* | syncbase-value
* | syncToPrev-value
* | event-value
* | media-marker-value
* | wallclock-sync-value )
* Smil-1.0-syncbase-value ::=
* "id(" id-ref ")" ( "(" ( "begin" | "end" | clock-value ) ")" )?
* Offset-value ::= ( "+" | "-" )? clock-value
* Syncbase-value ::= ( id-ref "." ( "begin" | "end" ) ) ( ( "+" | "-" ) clock-value )?
* SyncToPrev-value ::= ( "prev.begin" | "prev.end" ) ( ( "+" | "-" ) clock-value )?
* Event-value ::= ( id-ref "." )? ( event-ref ) ( ( "+" | "-" ) clock-value )?
* Media-marker-value ::= id-ref ".marker(" marker-name ")"
* Wallclock-sync-value ::= "wallclock(" wallclock-value ")"
* </pre>
*
* @param timeValue A String in the representation specified above
* @param constraints Any combination of the #ALLOW_* flags
* @return A TimeImpl instance representing
* @exception IllegalArgumentException if the timeValue input
* parameter does not comply with the defined syntax
* @exception NullPointerException if the timekValue string is
* <code>null</code>
*/
TimeImpl(String timeValue, int constraints) {
/*
* We do not support yet:
* - smil-1.0-syncbase-value
* - syncbase-value
* - syncToPrev-value
* - event-value
* - Media-marker-value
* - Wallclock-sync-value
*/
// Will throw NullPointerException if timeValue is null
if (timeValue.equals("indefinite")
&& ((constraints & ALLOW_INDEFINITE_VALUE) != 0) ) {
mTimeType = SMIL_TIME_INDEFINITE;
} else if ((constraints & ALLOW_OFFSET_VALUE) != 0) {
int sign = 1;
if (timeValue.startsWith("+")) {
timeValue = timeValue.substring(1);
} else if (timeValue.startsWith("-")) {
timeValue = timeValue.substring(1);
sign = -1;
}
mResolvedOffset = sign*parseClockValue(timeValue)/1000.0;
mResolved = true;
mTimeType = SMIL_TIME_OFFSET;
} else {
throw new IllegalArgumentException("Unsupported time value");
}
}
/**
* Converts a String representation of a clock value into the float
* representation used in this API.
* <p>
* Clock values have the following syntax:
* </p>
* <p>
* <pre>
* Clock-val ::= ( Full-clock-val | Partial-clock-val | Timecount-val )
* Full-clock-val ::= Hours ":" Minutes ":" Seconds ("." Fraction)?
* Partial-clock-val ::= Minutes ":" Seconds ("." Fraction)?
* Timecount-val ::= Timecount ("." Fraction)? (Metric)?
* Metric ::= "h" | "min" | "s" | "ms"
* Hours ::= DIGIT+; any positive number
* Minutes ::= 2DIGIT; range from 00 to 59
* Seconds ::= 2DIGIT; range from 00 to 59
* Fraction ::= DIGIT+
* Timecount ::= DIGIT+
* 2DIGIT ::= DIGIT DIGIT
* DIGIT ::= [0-9]
* </pre>
*
* @param clockValue A String in the representation specified above
* @return A float value in milliseconds that matches the string
* representation given as the parameter
* @exception IllegalArgumentException if the clockValue input
* parameter does not comply with the defined syntax
* @exception NullPointerException if the clockValue string is
* <code>null</code>
*/
public static float parseClockValue(String clockValue) {
try {
float result = 0;
// Will throw NullPointerException if clockValue is null
clockValue = clockValue.trim();
// Handle first 'Timecount-val' cases with metric
if (clockValue.endsWith("ms")) {
result = parseFloat(clockValue, 2, true);
} else if (clockValue.endsWith("s")) {
result = 1000*parseFloat(clockValue, 1, true);
} else if (clockValue.endsWith("min")) {
result = 60000*parseFloat(clockValue, 3, true);
} else if (clockValue.endsWith("h")) {
result = 3600000*parseFloat(clockValue, 1, true);
} else {
// Handle Timecount-val without metric
try {
return parseFloat(clockValue, 0, true) * 1000;
} catch (NumberFormatException _) {
// Ignore
}
// Split in {[Hours], Minutes, Seconds}
String[] timeValues = clockValue.split(":");
// Read Hours if present and remember location of Minutes
int indexOfMinutes;
if (timeValues.length == 2) {
indexOfMinutes = 0;
} else if (timeValues.length == 3) {
result = 3600000*(int)parseFloat(timeValues[0], 0, false);
indexOfMinutes = 1;
} else {
throw new IllegalArgumentException();
}
// Read Minutes
int minutes = (int)parseFloat(timeValues[indexOfMinutes], 0, false);
if ((minutes >= 00) && (minutes <= 59)) {
result += 60000*minutes;
} else {
throw new IllegalArgumentException();
}
// Read Seconds
float seconds = parseFloat(timeValues[indexOfMinutes + 1], 0, true);
if ((seconds >= 00) && (seconds < 60)) {
result += 60000*seconds;
} else {
throw new IllegalArgumentException();
}
}
return result;
} catch (NumberFormatException e) {
throw new IllegalArgumentException();
}
}
/**
* Parse a value formatted as follows:
* <p>
* <pre>
* Value ::= Number ("." Decimal)? (Text)?
* Number ::= DIGIT+; any positive number
* Decimal ::= DIGIT+; any positive number
* Text ::= CHAR*; any sequence of chars
* DIGIT ::= [0-9]
* </pre>
* @param value The Value to parse
* @param ignoreLast The size of Text to ignore
* @param parseDecimal Whether Decimal is expected
* @return The float value without Text, rounded to 3 digits after '.'
* @throws IllegalArgumentException if Decimal was not expected but encountered
*/
private static float parseFloat(String value, int ignoreLast, boolean parseDecimal) {
// Ignore last characters
value = value.substring(0, value.length() - ignoreLast);
float result;
int indexOfComma = value.indexOf('.');
if (indexOfComma != -1) {
if (!parseDecimal) {
throw new IllegalArgumentException("int value contains decimal");
}
// Ensure that there are at least 3 decimals
value = value + "000";
// Read value up to 3 decimals and cut the rest
result = Float.parseFloat(value.substring(0, indexOfComma));
result += Float.parseFloat(
value.substring(indexOfComma + 1, indexOfComma + 4))/1000;
} else {
result = Integer.parseInt(value);
}
return result;
}
/*
* Time Interface
*/
public boolean getBaseBegin() {
// TODO Auto-generated method stub
return false;
}
public Element getBaseElement() {
// TODO Auto-generated method stub
return null;
}
public String getEvent() {
// TODO Auto-generated method stub
return null;
}
public String getMarker() {
// TODO Auto-generated method stub
return null;
}
public double getOffset() {
// TODO Auto-generated method stub
return 0;
}
public boolean getResolved() {
return mResolved;
}
public double getResolvedOffset() {
return mResolvedOffset;
}
public short getTimeType() {
return mTimeType;
}
public void setBaseBegin(boolean baseBegin) throws DOMException {
// TODO Auto-generated method stub
}
public void setBaseElement(Element baseElement) throws DOMException {
// TODO Auto-generated method stub
}
public void setEvent(String event) throws DOMException {
// TODO Auto-generated method stub
}
public void setMarker(String marker) throws DOMException {
// TODO Auto-generated method stub
}
public void setOffset(double offset) throws DOMException {
// TODO Auto-generated method stub
}
}
@@ -1,54 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
public class TimeListImpl implements TimeList {
private final ArrayList<Time> mTimes;
/*
* Internal Interface
*/
TimeListImpl(ArrayList<Time> times) {
mTimes = times;
}
/*
* TimeList Interface
*/
public int getLength() {
return mTimes.size();
}
public Time item(int index) {
Time time = null;
try {
time = mTimes.get(index);
} catch (IndexOutOfBoundsException e) {
// Do nothing and return null
}
return time;
}
}
@@ -1,85 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil.parser;
import android.util.Log;
import com.android.mms.dom.smil.SmilDocumentImpl;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.smil.SMILDocument;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
public class SmilContentHandler extends DefaultHandler {
private static final String TAG = "SmilContentHandler";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private SMILDocument mSmilDocument;
private Node mCurrentNode;
/**
* Resets this handler.
*
*/
public void reset() {
mSmilDocument = new SmilDocumentImpl();
mCurrentNode = mSmilDocument;
}
/**
* Returns the SMILDocument.
* @return The SMILDocument instance
*/
public SMILDocument getSmilDocument() {
return mSmilDocument;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if (LOCAL_LOGV) Log.v(TAG, "SmilContentHandler.startElement. Creating element " + localName);
Element element = mSmilDocument.createElement(localName);
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
if (LOCAL_LOGV) Log.v(TAG, "Attribute " + i +
" lname = " + attributes.getLocalName(i) +
" value = " + attributes.getValue(i));
element.setAttribute(attributes.getLocalName(i),
attributes.getValue(i));
}
}
if (LOCAL_LOGV) Log.v(TAG, "Appending " + localName + " to " + mCurrentNode.getNodeName());
mCurrentNode.appendChild(element);
mCurrentNode = element;
}
@Override
public void endElement(String uri, String localName, String qName) {
if (LOCAL_LOGV) Log.v(TAG, "SmilContentHandler.endElement. localName " + localName);
mCurrentNode = mCurrentNode.getParentNode();
}
@Override
public void characters(char[] ch, int start, int length) {
if (LOCAL_LOGV) Log.v(TAG, "SmilContentHandler.characters. ch = " + new String(ch, start, length));
}
}
@@ -1,76 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil.parser;
import com.google.android.mms.MmsException;
import org.w3c.dom.smil.SMILDocument;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import java.io.IOException;
import java.io.InputStream;
public class SmilXmlParser {
private XMLReader mXmlReader;
private SmilContentHandler mContentHandler;
public SmilXmlParser() throws MmsException {
//FIXME: Now we don't have the SAXParser wrapped inside,
// use the Driver class temporarily.
System.setProperty("org.xml.sax.driver", "org.xmlpull.v1.sax2.Driver");
try {
mXmlReader = XMLReaderFactory.createXMLReader();
mContentHandler = new SmilContentHandler();
mXmlReader.setContentHandler(mContentHandler);
} catch (SAXException e) {
throw new MmsException(e);
}
}
public SMILDocument parse(InputStream in) throws IOException, SAXException {
mContentHandler.reset();
mXmlReader.parse(new InputSource(in));
SMILDocument doc = mContentHandler.getSmilDocument();
validateDocument(doc);
return doc;
}
private void validateDocument(SMILDocument doc) {
/*
* Calling getBody() will create "smil", "head", and "body" elements if they
* are not present. It will also initialize the SequentialTimeElementContainer
* member of SMILDocument, which could not be set on creation of the document.
* @see com.android.mms.dom.smil.SmilDocumentImpl#getBody()
*/
doc.getBody();
/*
* Calling getLayout() will create "layout" element if it is not present.
* @see com.android.mms.dom.smil.SmilDocumentImpl#getLayout()
*/
doc.getLayout();
}
}
@@ -1,85 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil.parser;
import android.util.Log;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILElement;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
public class SmilXmlSerializer {
private static final String TAG = "SmilXmlSerializer";
public static void serialize(SMILDocument smilDoc, OutputStream out) {
try {
Writer writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"), 2048);
writeElement(writer, smilDoc.getDocumentElement());
writer.flush();
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "exception thrown", e);
} catch (IOException e) {
Log.e(TAG, "exception thrown", e);
}
}
private static void writeElement(Writer writer, Element element)
throws IOException {
writer.write('<');
writer.write(element.getTagName());
if (element.hasAttributes()) {
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attribute = (Attr)attributes.item(i);
writer.write(" " + attribute.getName());
writer.write("=\"" + attribute.getValue() + "\"");
}
}
// FIXME: Might throw ClassCastException
SMILElement childElement = (SMILElement) element.getFirstChild();
if (childElement != null) {
writer.write('>');
do {
writeElement(writer, childElement);
childElement = (SMILElement) childElement.getNextSibling();
} while (childElement != null);
writer.write("</");
writer.write(element.getTagName());
writer.write('>');
} else {
writer.write("/>");
}
}
}
@@ -1,32 +0,0 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
public abstract class AbstractRetryScheme {
public static final int OUTGOING = 1;
public static final int INCOMING = 2;
protected int mRetriedTimes;
public AbstractRetryScheme(int retriedTimes) {
mRetriedTimes = retriedTimes;
}
abstract public int getRetryLimit();
abstract public long getWaitingInterval();
}
@@ -1,56 +0,0 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.content.Context;
import android.util.Config;
import android.util.Log;
/**
* Default retry scheme, based on specs.
*/
public class DefaultRetryScheme extends AbstractRetryScheme {
private static final String TAG = "DefaultRetryScheme";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
private static final int[] sDefaultRetryScheme = {
0, 1 * 60 * 1000, 5 * 60 * 1000, 10 * 60 * 1000, 30 * 60 * 1000};
public DefaultRetryScheme(Context context, int retriedTimes) {
super(retriedTimes);
mRetriedTimes = mRetriedTimes < 0 ? 0 : mRetriedTimes;
mRetriedTimes = mRetriedTimes >= sDefaultRetryScheme.length
? sDefaultRetryScheme.length - 1 : mRetriedTimes;
// TODO Get retry scheme from preference.
}
@Override
public int getRetryLimit() {
return sDefaultRetryScheme.length;
}
@Override
public long getWaitingInterval() {
if (LOCAL_LOGV) Log.v(TAG, "Next int: " + sDefaultRetryScheme[mRetriedTimes]);
return sDefaultRetryScheme[mRetriedTimes];
}
}
@@ -1,362 +0,0 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
* Copyirght (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import com.moez.QKSMS.MmsConfig;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
public class HttpUtils {
private static final String TAG = "HttpUtils";
private static final boolean LOCAL_LOGV = false;
public static final int HTTP_POST_METHOD = 1;
public static final int HTTP_GET_METHOD = 2;
private static final int MMS_READ_BUFFER = 4096;
// This is the value to use for the "Accept-Language" header.
// Once it becomes possible for the user to change the locale
// setting, this should no longer be static. We should call
// getHttpAcceptLanguage instead.
private static final String HDR_VALUE_ACCEPT_LANGUAGE;
static {
HDR_VALUE_ACCEPT_LANGUAGE = getCurrentAcceptLanguage(Locale.getDefault());
}
// Definition for necessary HTTP headers.
private static final String HDR_KEY_ACCEPT = "Accept";
private static final String HDR_KEY_ACCEPT_LANGUAGE = "Accept-Language";
private static final String HDR_VALUE_ACCEPT =
"*/*, application/vnd.wap.mms-message, application/vnd.wap.sic";
private HttpUtils() {
// To forbidden instantiate this class.
}
/**
* A helper method to send or retrieve data through HTTP protocol.
*
* @param token The token to identify the sending progress.
* @param url The URL used in a GET request. Null when the method is
* HTTP_POST_METHOD.
* @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
* @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(&gt;=400) returned from the server.
*/
public static byte[] httpConnection(Context context, long token,
String url, byte[] pdu, int method, boolean isProxySet,
String proxyHost, int proxyPort) throws IOException {
if (url == null) {
throw new IllegalArgumentException("URL must not be null.");
}
if (LOCAL_LOGV) Log.v(TAG, "httpConnection: params list" +
"\n\ttoken\t\t= " + token +
"\n\turl\t\t= " + url +
"\n\tmethod\t\t="
+ ((method == HTTP_POST_METHOD) ? "POST"
: ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")) +
"\n\tisProxySet\t= " + isProxySet +
"\n\tproxyHost\t= " + proxyHost +
"\n\tproxyPort\t= " + proxyPort);
// TODO Print out binary data more readable.
//"\tpdu\t\t= " + Arrays.toString(pdu));
AndroidHttpClient client = null;
try {
// Make sure to use a proxy which supports CONNECT.
URI hostUrl = new URI(url);
HttpHost target = new HttpHost(
hostUrl.getHost(), hostUrl.getPort(),
HttpHost.DEFAULT_SCHEME_NAME);
client = createHttpClient(context);
HttpRequest req = null;
switch(method) {
case HTTP_POST_METHOD:
ProgressCallbackEntity entity = new ProgressCallbackEntity(
context, token, pdu);
// Set request content type.
entity.setContentType("application/vnd.wap.mms-message");
HttpPost post = new HttpPost(url);
post.setEntity(entity);
req = post;
break;
case HTTP_GET_METHOD:
req = new HttpGet(url);
break;
default:
Log.e(TAG, "Unknown HTTP method: " + method
+ ". Must be one of POST[" + HTTP_POST_METHOD
+ "] or GET[" + HTTP_GET_METHOD + "].");
return null;
}
// Set route parameters for the request.
HttpParams params = client.getParams();
if (isProxySet) {
ConnRouteParams.setDefaultProxy(
params, new HttpHost(proxyHost, proxyPort));
}
req.setParams(params);
// Set necessary HTTP headers for MMS transmission.
req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
{
String xWapProfileTagName = MmsConfig.getUaProfTagName();
String xWapProfileUrl = MmsConfig.getUaProfUrl();
if (xWapProfileUrl != null) {
if (LOCAL_LOGV) Log.v(TAG, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
req.addHeader(xWapProfileTagName, xWapProfileUrl);
}
}
// Extra http parameters. Split by '|' to get a list of value pairs.
// Separate each pair by the first occurrence of ':' to obtain a name and
// value. Replace the occurrence of the string returned by
// MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
// the value.
String extraHttpParams = MmsConfig.getHttpParams();
if (extraHttpParams != null) {
String line1Number = ((TelephonyManager)context
.getSystemService(Context.TELEPHONY_SERVICE))
.getLine1Number();
String line1Key = MmsConfig.getHttpParamsLine1Key();
String paramList[] = extraHttpParams.split("\\|");
for (String paramPair : paramList) {
String splitPair[] = paramPair.split(":", 2);
if (splitPair.length == 2) {
String name = splitPair[0].trim();
String value = splitPair[1].trim();
if (line1Key != null) {
value = value.replace(line1Key, line1Number);
}
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
req.addHeader(name, value);
}
}
}
}
req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);
HttpResponse response = client.execute(target, req);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) { // HTTP 200 is success.
throw new IOException("HTTP error: " + status.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
byte[] body = null;
if (entity != null) {
try {
if (entity.getContentLength() > 0) {
body = new byte[(int) entity.getContentLength()];
DataInputStream dis = new DataInputStream(entity.getContent());
try {
dis.readFully(body);
} finally {
try {
dis.close();
} catch (IOException e) {
Log.e(TAG, "Error closing input stream: " + e.getMessage());
}
}
}
if (entity.isChunked()) {
if (LOCAL_LOGV) Log.v(TAG, "httpConnection: transfer encoding is chunked");
int bytesTobeRead = MmsConfig.getMaxMessageSize();
byte[] tempBody = new byte[bytesTobeRead];
DataInputStream dis = new DataInputStream(entity.getContent());
try {
int bytesRead = 0;
int offset = 0;
boolean readError = false;
do {
try {
bytesRead = dis.read(tempBody, offset, bytesTobeRead);
} catch (IOException e) {
readError = true;
Log.e(TAG, "httpConnection: error reading input stream"
+ e.getMessage());
break;
}
if (bytesRead > 0) {
bytesTobeRead -= bytesRead;
offset += bytesRead;
}
} while (bytesRead >= 0 && bytesTobeRead > 0);
if (bytesRead == -1 && offset > 0 && !readError) {
// offset is same as total number of bytes read
// bytesRead will be -1 if the data was read till the eof
body = new byte[offset];
System.arraycopy(tempBody, 0, body, 0, offset);
if (LOCAL_LOGV) Log.v(TAG, "httpConnection: Chunked response "
+ "length [" + Integer.toString(offset) + "]");
} else {
Log.e(TAG, "httpConnection: Response entity too large or empty");
}
} finally {
try {
dis.close();
} catch (IOException e) {
Log.e(TAG, "Error closing input stream: " + e.getMessage());
}
}
}
} finally {
if (entity != null) {
entity.consumeContent();
}
}
}
return body;
} catch (URISyntaxException e) {
handleHttpConnectionException(e, url);
} catch (IllegalStateException e) {
handleHttpConnectionException(e, url);
} catch (IllegalArgumentException e) {
handleHttpConnectionException(e, url);
} catch (SocketException e) {
handleHttpConnectionException(e, url);
} catch (Exception e) {
handleHttpConnectionException(e, url);
}
finally {
if (client != null) {
client.close();
}
}
return null;
}
private static void handleHttpConnectionException(Exception exception, String url)
throws IOException {
// Inner exception should be logged to make life easier.
Log.e(TAG, "Url: " + url + "\n" + exception.getMessage());
IOException e = new IOException(exception.getMessage());
e.initCause(exception);
throw e;
}
private static AndroidHttpClient createHttpClient(Context context) {
String userAgent = MmsConfig.getUserAgent();
AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent, context);
HttpParams params = client.getParams();
HttpProtocolParams.setContentCharset(params, "UTF-8");
// set the socket timeout
int soTimeout = MmsConfig.getHttpSocketTimeout();
if (LOCAL_LOGV) Log.d(TAG, "[HttpUtils] createHttpClient w/ socket timeout " + soTimeout
+ " ms, " + ", UA=" + userAgent);
HttpConnectionParams.setSoTimeout(params, soTimeout);
return client;
}
private static final String ACCEPT_LANG_FOR_US_LOCALE = "en-US";
/**
* Return the Accept-Language header. Use the current locale plus
* US if we are in a different locale than US.
* This code copied from the browser's WebSettings.java
* @return Current AcceptLanguage String.
*/
public static String getCurrentAcceptLanguage(Locale locale) {
StringBuilder buffer = new StringBuilder();
addLocaleToHttpAcceptLanguage(buffer, locale);
if (!Locale.US.equals(locale)) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append(ACCEPT_LANG_FOR_US_LOCALE);
}
return buffer.toString();
}
/**
* Convert obsolete language codes, including Hebrew/Indonesian/Yiddish,
* to new standard.
*/
private static String convertObsoleteLanguageCodeToNew(String langCode) {
if (langCode == null) {
return null;
}
if ("iw".equals(langCode)) {
// Hebrew
return "he";
} else if ("in".equals(langCode)) {
// Indonesian
return "id";
} else if ("ji".equals(langCode)) {
// Yiddish
return "yi";
}
return langCode;
}
private static void addLocaleToHttpAcceptLanguage(StringBuilder builder,
Locale locale) {
String language = convertObsoleteLanguageCodeToNew(locale.getLanguage());
if (language != null) {
builder.append(language);
String country = locale.getCountry();
if (country != null) {
builder.append("-");
builder.append(country);
}
}
}
}
@@ -1,34 +0,0 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import com.google.android.mms.MmsException;
public interface MessageSender {
public static final String RECIPIENTS_SEPARATOR = ";";
/**
* Send the message through MMS or SMS protocol.
* @param token The token to identify the sending progress.
*
* @return True if the message was sent through MMS or false if it was
* sent through SMS.
* @throws MmsException Error occurred while sending the message.
*/
boolean sendMessage(long token) throws Throwable;
}
@@ -1,35 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MessageStatusReceiver extends BroadcastReceiver {
public static final String MESSAGE_STATUS_RECEIVED_ACTION =
"com.android.mms.transaction.MessageStatusReceiver.MESSAGE_STATUS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
if (MESSAGE_STATUS_RECEIVED_ACTION.equals(intent.getAction())) {
intent.setClass(context, MessageStatusService.class);
context.startService(intent);
}
}
}
@@ -1,102 +0,0 @@
/*
* Copyright (C) 2012 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.app.IntentService;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.telephony.SmsMessage;
import android.util.Log;
/**
* Service that gets started by the MessageStatusReceiver when a message status report is
* received.
*/
public class MessageStatusService extends IntentService {
private static final String[] ID_PROJECTION = new String[] { "_id" };
private static final String LOG_TAG = "MessageStatusReceiver";
private static final Uri STATUS_URI = Uri.parse("content://sms/status");
public MessageStatusService() {
// Class name will be the thread name.
super(MessageStatusService.class.getName());
// Intent should be redelivered if the process gets killed before completing the job.
setIntentRedelivery(true);
}
@Override
protected void onHandleIntent(Intent intent) {
// This method is called on a worker thread.
Uri messageUri = intent.getData();
byte[] pdu = intent.getByteArrayExtra("pdu");
String format = intent.getStringExtra("format");
updateMessageStatus(this, messageUri, pdu, format);
}
private SmsMessage updateMessageStatus(Context context, Uri messageUri, byte[] pdu,
String format) {
SmsMessage message = SmsMessage.createFromPdu(pdu);
if (message == null) {
return null;
}
// Create a "status/#" URL and use it to update the
// message's status in the database.
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
messageUri, ID_PROJECTION, null, null, null);
try {
if (cursor.moveToFirst()) {
int messageId = cursor.getInt(0);
Uri updateUri = ContentUris.withAppendedId(STATUS_URI, messageId);
int status = message.getStatus();
boolean isStatusReport = message.isStatusReportMessage();
ContentValues contentValues = new ContentValues(2);
log("updateMessageStatus: msgUrl=" + messageUri + ", status=" + status +
", isStatusReport=" + isStatusReport);
contentValues.put("status", status);
contentValues.put("date_sent", System.currentTimeMillis());
SqliteWrapper.update(context, context.getContentResolver(),
updateUri, contentValues, null, null);
} else {
error("Can't find message for status update: " + messageUri);
}
} finally {
cursor.close();
}
return message;
}
private void error(String message) {
Log.e(LOG_TAG, "[MessageStatusReceiver] " + message);
}
private void log(String message) {
Log.d(LOG_TAG, "[MessageStatusReceiver] " + message);
}
}
@@ -1,195 +0,0 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import android.util.Log;
import com.android.mms.util.SendingProgressTokenManager;
import com.google.android.mms.InvalidHeaderValueException;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.ReadRecInd;
import com.google.android.mms.pdu_alt.SendReq;
import com.google.android.mms.util_alt.SqliteWrapper;
public class MmsMessageSender implements MessageSender {
private static final String TAG = "MmsMessageSender";
private final Context mContext;
private final Uri mMessageUri;
private final long mMessageSize;
// Default preference values
private static final boolean DEFAULT_DELIVERY_REPORT_MODE = false;
private static final boolean DEFAULT_READ_REPORT_MODE = false;
private static final long DEFAULT_EXPIRY_TIME = 7 * 24 * 60 * 60;
private static final int DEFAULT_PRIORITY = PduHeaders.PRIORITY_NORMAL;
private static final String DEFAULT_MESSAGE_CLASS = PduHeaders.MESSAGE_CLASS_PERSONAL_STR;
private static final String DELIVERY_REPORT_PREFERENCE = "delivery_reports";
private static final String READ_REPORT_PREFERENCE = "read_reports";
public MmsMessageSender(Context context, Uri location, long messageSize) {
mContext = context;
mMessageUri = location;
mMessageSize = messageSize;
if (mMessageUri == null) {
throw new IllegalArgumentException("Null message URI.");
}
}
public boolean sendMessage(long token) throws Throwable {
// Load the MMS from the message uri
PduPersister p = PduPersister.getPduPersister(mContext);
GenericPdu pdu = p.load(mMessageUri);
if (pdu.getMessageType() != PduHeaders.MESSAGE_TYPE_SEND_REQ) {
throw new MmsException("Invalid message: " + pdu.getMessageType());
}
SendReq sendReq = (SendReq) pdu;
// Update headers.
updatePreferencesHeaders(sendReq);
// MessageClass.
sendReq.setMessageClass(DEFAULT_MESSAGE_CLASS.getBytes());
// Update the 'date' field of the message before sending it.
sendReq.setDate(System.currentTimeMillis() / 1000L);
sendReq.setMessageSize(mMessageSize);
p.updateHeaders(mMessageUri, sendReq);
long messageId = ContentUris.parseId(mMessageUri);
// Move the message into MMS Outbox.
if (!mMessageUri.toString().startsWith(Uri.parse("content://mms/drafts").toString())) {
try {
// If the message is already in the outbox (most likely because we created a "primed"
// message in the outbox when the user hit send), then we have to manually put an
// entry in the pending_msgs table which is where TransacationService looks for
// messages to send. Normally, the entry in pending_msgs is created by the trigger:
// insert_mms_pending_on_update, when a message is moved from drafts to the outbox.
ContentValues values = new ContentValues(7);
values.put(Telephony.MmsSms.PendingMessages.PROTO_TYPE, 1);
values.put(Telephony.MmsSms.PendingMessages.MSG_ID, messageId);
values.put(Telephony.MmsSms.PendingMessages.MSG_TYPE, pdu.getMessageType());
values.put(Telephony.MmsSms.PendingMessages.ERROR_TYPE, 0);
values.put(Telephony.MmsSms.PendingMessages.ERROR_CODE, 0);
values.put(Telephony.MmsSms.PendingMessages.RETRY_INDEX, 0);
values.put(Telephony.MmsSms.PendingMessages.DUE_TIME, 0);
SqliteWrapper.insert(mContext, mContext.getContentResolver(),
Telephony.MmsSms.PendingMessages.CONTENT_URI, values);
} catch (Throwable e) {
p.move(mMessageUri, Telephony.Mms.Outbox.CONTENT_URI);
}
} else {
p.move(mMessageUri, Telephony.Mms.Outbox.CONTENT_URI);
}
// Start MMS transaction service
try {
SendingProgressTokenManager.put(messageId, token);
Intent service = new Intent(
TransactionService.HANDLE_PENDING_TRANSACTIONS_ACTION, null, mContext,
TransactionService.class
);
mContext.startService(service);
} catch (Exception e) {
throw new Exception("transaction service not registered in manifest");
}
return true;
}
// Update the headers which are stored in SharedPreferences.
private void updatePreferencesHeaders(SendReq sendReq) throws MmsException {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
// Expiry.
sendReq.setExpiry(DEFAULT_EXPIRY_TIME);
// Priority.
sendReq.setPriority(DEFAULT_PRIORITY);
// Delivery report.
boolean dr = prefs.getBoolean(DELIVERY_REPORT_PREFERENCE,
DEFAULT_DELIVERY_REPORT_MODE);
sendReq.setDeliveryReport(dr?PduHeaders.VALUE_YES:PduHeaders.VALUE_NO);
// Read report.
boolean rr = prefs.getBoolean(READ_REPORT_PREFERENCE,
// default to delivery report value if read report not available
prefs.getBoolean(DELIVERY_REPORT_PREFERENCE,
DEFAULT_READ_REPORT_MODE));
sendReq.setReadReport(rr?PduHeaders.VALUE_YES:PduHeaders.VALUE_NO);
}
public static void sendReadRec(Context context, String to, String messageId, int status) {
EncodedStringValue[] sender = new EncodedStringValue[1];
sender[0] = new EncodedStringValue(to);
try {
final ReadRecInd readRec = new ReadRecInd(
new EncodedStringValue(PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.getBytes()),
messageId.getBytes(),
PduHeaders.CURRENT_MMS_VERSION,
status,
sender);
readRec.setDate(System.currentTimeMillis() / 1000);
boolean group;
try {
group = com.moez.QKSMS.mmssms.Transaction.settings.getGroup();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("pref_key_compose_group", true);
}
PduPersister.getPduPersister(context).persist(readRec, Uri.parse("content://mms/outbox"), true,
group, null);
Intent service = new Intent(
TransactionService.HANDLE_PENDING_TRANSACTIONS_ACTION, null, context,
TransactionService.class
);
context.startService(service);
} catch (InvalidHeaderValueException e) {
Log.e(TAG, "Invalide header value", e);
} catch (MmsException e) {
Log.e(TAG, "Persist message failed", e);
}
}
}
@@ -1,46 +0,0 @@
/*
* Copyright (C) 2013 Samsung System LSI
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* MmsPushOutboxMessages listens for MMS_SEND_OUTBOX_MSG intent .
* {@link android.intent.action.MMS_SEND_OUTBOX_MSG},
* and wakes up the mms service when it receives it.
* This will tricker the mms service to send any messages stored
* in the outbox.
*/
public class MmsPushOutboxMessages extends BroadcastReceiver {
private static final String INTENT_MMS_SEND_OUTBOX_MSG = "android.intent.action.MMS_SEND_OUTBOX_MSG";
private static final String TAG = "MmsPushOutboxMessages";
private static final boolean LOCAL_LOGV = false;
@Override
public void onReceive(Context context, Intent intent) {
if (LOCAL_LOGV) Log.v(TAG, "Received the MMS_SEND_OUTBOX_MSG intent: " + intent);
String action = intent.getAction();
if(action.equalsIgnoreCase(INTENT_MMS_SEND_OUTBOX_MSG)){
if (LOCAL_LOGV) Log.v(TAG, "Now waking up the MMS service");
}
}
}
@@ -1,97 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;
import com.moez.QKSMS.mmssms.Utils;
/**
* MmsSystemEventReceiver receives the
* {@link android.content.intent.ACTION_BOOT_COMPLETED},
* {@link com.android.internal.telephony.TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED}
* and performs a series of operations which may include:
* <ul>
* <li>Show/hide the icon in notification area which is used to indicate
* whether there is new incoming message.</li>
* <li>Resend the MM's in the outbox.</li>
* </ul>
*/
public class MmsSystemEventReceiver extends BroadcastReceiver {
private static final String TAG = "MmsSystemEventReceiver";
private static ConnectivityManager mConnMgr = null;
private static final boolean LOCAL_LOGV = false;
public static void wakeUpService(Context context) {
if (LOCAL_LOGV) Log.v(TAG, "wakeUpService: start transaction service ...");
Intent service = new Intent(
TransactionService.HANDLE_PENDING_TRANSACTIONS_ACTION, null, context,
TransactionService.class
);
context.startService(service);
}
@Override
public void onReceive(Context context, Intent intent) {
if (LOCAL_LOGV) Log.v(TAG, "Intent received: " + intent);
String action = intent.getAction();
if (action.equals("android.intent.action.CONTENT_CHANGED")) {
intent.getParcelableExtra("deleted_contents");
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (mConnMgr == null) {
mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
boolean mobileDataEnabled = Utils.isMobileDataEnabled(context);
if (!mobileDataEnabled) {
if (LOCAL_LOGV) Log.v(TAG, "mobile data turned off, bailing");
return;
}
NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected();
if (LOCAL_LOGV) Log.v(TAG, "TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
// Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) {
wakeUpService(context);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// We should check whether there are unread incoming
// messages in the Inbox and then update the notification icon.
// Called on the UI thread so don't block.
// Scan and send pending Mms once after boot completed since
// ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle
wakeUpService(context);
}
}
}
@@ -1,278 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Mms.Inbox;
import android.provider.Telephony.Threads;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.mms.util.DownloadManager;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.NotificationInd;
import com.google.android.mms.pdu_alt.NotifyRespInd;
import com.google.android.mms.pdu_alt.PduComposer;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.moez.QKSMS.MmsConfig;
import java.io.IOException;
import static com.android.mms.transaction.TransactionState.FAILED;
import static com.android.mms.transaction.TransactionState.INITIALIZED;
import static com.android.mms.transaction.TransactionState.SUCCESS;
import static com.google.android.mms.pdu_alt.PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF;
import static com.google.android.mms.pdu_alt.PduHeaders.STATUS_DEFERRED;
import static com.google.android.mms.pdu_alt.PduHeaders.STATUS_RETRIEVED;
import static com.google.android.mms.pdu_alt.PduHeaders.STATUS_UNRECOGNIZED;
/**
* The NotificationTransaction is responsible for handling multimedia
* message notifications (M-Notification.ind). It:
*
* <ul>
* <li>Composes the notification response (M-NotifyResp.ind).
* <li>Sends the notification response to the MMSC server.
* <li>Stores the notification indication.
* <li>Notifies the TransactionService about succesful completion.
* </ul>
*
* NOTE: This MMS client handles all notifications with a <b>deferred
* retrieval</b> response. The transaction service, upon succesful
* completion of this transaction, will trigger a retrieve transaction
* in case the client is in immediate retrieve mode.
*/
public class NotificationTransaction extends Transaction implements Runnable {
private static final String TAG = "NotificationTransaction";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private Uri mUri;
private NotificationInd mNotificationInd;
private String mContentLocation;
private Context mContext;
public NotificationTransaction(
Context context, int serviceId,
TransactionSettings connectionSettings, String uriString) {
super(context, serviceId, connectionSettings);
mUri = Uri.parse(uriString);
mContext = context;
try {
mNotificationInd = (NotificationInd)
PduPersister.getPduPersister(context).load(mUri);
} catch (MmsException e) {
Log.e(TAG, "Failed to load NotificationInd from: " + uriString, e);
throw new IllegalArgumentException();
}
mContentLocation = new String(mNotificationInd.getContentLocation());
mId = mContentLocation;
// Attach the transaction to the instance of RetryScheduler.
attach(RetryScheduler.getInstance(context));
}
/**
* This constructor is only used for test purposes.
*/
public NotificationTransaction(
Context context, int serviceId,
TransactionSettings connectionSettings, NotificationInd ind) {
super(context, serviceId, connectionSettings);
mContext = context;
try {
// Save the pdu. If we can start downloading the real pdu immediately, don't allow
// persist() to create a thread for the notificationInd because it causes UI jank.
boolean group;
try {
group = com.moez.QKSMS.mmssms.Transaction.settings.getGroup();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("group_message", true);
}
mUri = PduPersister.getPduPersister(context).persist(
ind, Inbox.CONTENT_URI, !allowAutoDownload(context),
group, null);
} catch (MmsException e) {
Log.e(TAG, "Failed to save NotificationInd in constructor.", e);
throw new IllegalArgumentException();
}
mNotificationInd = ind;
mId = new String(mNotificationInd.getContentLocation());
}
/*
* (non-Javadoc)
* @see com.google.android.mms.pdu.Transaction#process()
*/
@Override
public void process() {
new Thread(this, "NotificationTransaction").start();
}
public static boolean allowAutoDownload(Context context) {
try { Looper.prepare(); } catch (Exception e) { }
boolean autoDownload = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("pref_key_auto_download", true);
boolean dataSuspended = (((TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE)).getDataState() ==
TelephonyManager.DATA_SUSPENDED);
return autoDownload && !dataSuspended;
}
public void run() {
try {
Looper.prepare();
} catch (Exception e) {
Log.e(TAG, "exception thrown", e);
}
DownloadManager.init(mContext);
DownloadManager downloadManager = DownloadManager.getInstance();
boolean autoDownload = allowAutoDownload(mContext);
try {
if (LOCAL_LOGV) Log.v(TAG, "Notification transaction launched: " + this);
// By default, we set status to STATUS_DEFERRED because we
// should response MMSC with STATUS_DEFERRED when we cannot
// download a MM immediately.
int status = STATUS_DEFERRED;
// Don't try to download when data is suspended, as it will fail, so defer download
if (!autoDownload) {
downloadManager.markState(mUri, DownloadManager.STATE_UNSTARTED);
sendNotifyRespInd(status);
return;
}
downloadManager.markState(mUri, DownloadManager.STATE_DOWNLOADING);
if (LOCAL_LOGV) Log.v(TAG, "Content-Location: " + mContentLocation);
byte[] retrieveConfData = null;
// We should catch exceptions here to response MMSC
// with STATUS_DEFERRED.
try {
retrieveConfData = getPdu(mContentLocation);
} catch (IOException e) {
mTransactionState.setState(FAILED);
}
if (retrieveConfData != null) {
GenericPdu pdu = new PduParser(retrieveConfData).parse();
if ((pdu == null) || (pdu.getMessageType() != MESSAGE_TYPE_RETRIEVE_CONF)) {
Log.e(TAG, "Invalid M-RETRIEVE.CONF PDU. " +
(pdu != null ? "message type: " + pdu.getMessageType() : "null pdu"));
mTransactionState.setState(FAILED);
status = STATUS_UNRECOGNIZED;
} else {
// Save the received PDU (must be a M-RETRIEVE.CONF).
PduPersister p = PduPersister.getPduPersister(mContext);
Uri uri = p.persist(pdu, Inbox.CONTENT_URI, true,
com.moez.QKSMS.mmssms.Transaction.settings.getGroup(), null);
// Use local time instead of PDU time
ContentValues values = new ContentValues(1);
values.put(Mms.DATE, System.currentTimeMillis() / 1000L);
SqliteWrapper.update(mContext, mContext.getContentResolver(),
uri, values, null, null);
// We have successfully downloaded the new MM. Delete the
// M-NotifyResp.ind from Inbox.
SqliteWrapper.delete(mContext, mContext.getContentResolver(),
mUri, null, null);
Log.v(TAG, "NotificationTransaction received new mms message: " + uri);
// Delete obsolete threads
SqliteWrapper.delete(mContext, mContext.getContentResolver(),
Threads.OBSOLETE_THREADS_URI, null, null);
// Notify observers with newly received MM.
mUri = uri;
status = STATUS_RETRIEVED;
mContext.sendBroadcast(new Intent(com.moez.QKSMS.mmssms.Transaction.NOTIFY_OF_MMS));
}
}
if (LOCAL_LOGV) Log.v(TAG, "status=0x" + Integer.toHexString(status));
// Check the status and update the result state of this Transaction.
switch (status) {
case STATUS_RETRIEVED:
mTransactionState.setState(SUCCESS);
break;
case STATUS_DEFERRED:
// STATUS_DEFERRED, may be a failed immediate retrieval.
if (mTransactionState.getState() == INITIALIZED) {
mTransactionState.setState(SUCCESS);
}
break;
}
sendNotifyRespInd(status);
} catch (Throwable t) {
Log.e(TAG, Log.getStackTraceString(t));
} finally {
mTransactionState.setContentUri(mUri);
if (!autoDownload) {
// Always mark the transaction successful for deferred
// download since any error here doesn't make sense.
mTransactionState.setState(SUCCESS);
}
if (mTransactionState.getState() != SUCCESS) {
mTransactionState.setState(FAILED);
Log.e(TAG, "NotificationTransaction failed.");
}
notifyObservers();
}
}
private void sendNotifyRespInd(int status) throws MmsException, IOException {
// Create the M-NotifyResp.ind
NotifyRespInd notifyRespInd = new NotifyRespInd(
PduHeaders.CURRENT_MMS_VERSION,
mNotificationInd.getTransactionId(),
status);
// Pack M-NotifyResp.ind and send it
if(MmsConfig.getNotifyWapMMSC()) {
sendPdu(new PduComposer(mContext, notifyRespInd).make(), mContentLocation);
} else {
sendPdu(new PduComposer(mContext, notifyRespInd).make());
}
}
@Override
public int getType() {
return NOTIFICATION_TRANSACTION;
}
}
@@ -1,78 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import java.util.ArrayList;
import java.util.Iterator;
/**
* An interface to represent the state of an observable Transaction.
*/
public abstract class Observable {
private final ArrayList<Observer> mObservers;
private Iterator<Observer> mIterator;
public Observable() {
mObservers = new ArrayList<Observer>();
}
/**
* This method is implemented by the observable to represent its
* current state.
*
* @return A TransactionState object.
*/
abstract public TransactionState getState();
/**
* Attach an observer to this object.
*
* @param observer The observer object to be attached to.
*/
public void attach(Observer observer) {
mObservers.add(observer);
}
/**
* Detach an observer from this object.
*
* @param observer The observer object to be detached from.
*/
public void detach(Observer observer) {
if (mIterator != null) {
mIterator.remove();
} else {
mObservers.remove(observer);
}
}
/**
* Notify all observers that a status change has occurred.
*/
public void notifyObservers() {
mIterator = mObservers.iterator();
try {
while (mIterator.hasNext()) {
mIterator.next().update(this);
}
} finally {
mIterator = null;
}
}
}
@@ -1,32 +0,0 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
/**
* An interface for observing the state of a Transaction.
*/
public interface Observer {
/**
* Update the state of the observable.
*
* @param observable An observable object.
*/
void update(Observable observable);
}
@@ -1,90 +0,0 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.content.Context;
import android.content.Intent;
import org.apache.http.entity.ByteArrayEntity;
import java.io.IOException;
import java.io.OutputStream;
public class ProgressCallbackEntity extends ByteArrayEntity {
private static final int DEFAULT_PIECE_SIZE = 4096;
public static final String PROGRESS_STATUS_ACTION = "com.android.mms.PROGRESS_STATUS";
public static final int PROGRESS_START = -1;
public static final int PROGRESS_ABORT = -2;
public static final int PROGRESS_COMPLETE = 100;
private final Context mContext;
private final byte[] mContent;
private final long mToken;
public ProgressCallbackEntity(Context context, long token, byte[] b) {
super(b);
mContext = context;
mContent = b;
mToken = token;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
boolean completed = false;
try {
broadcastProgressIfNeeded(PROGRESS_START);
int pos = 0, totalLen = mContent.length;
while (pos < totalLen) {
int len = totalLen - pos;
if (len > DEFAULT_PIECE_SIZE) {
len = DEFAULT_PIECE_SIZE;
}
outstream.write(mContent, pos, len);
outstream.flush();
pos += len;
broadcastProgressIfNeeded(100 * pos / totalLen);
}
broadcastProgressIfNeeded(PROGRESS_COMPLETE);
completed = true;
} finally {
if (!completed) {
broadcastProgressIfNeeded(PROGRESS_ABORT);
}
}
}
private void broadcastProgressIfNeeded(int progress) {
if (mToken > 0) {
Intent intent = new Intent(PROGRESS_STATUS_ACTION);
intent.putExtra("progress", progress);
intent.putExtra("token", mToken);
mContext.sendBroadcast(intent);
}
}
}
@@ -1,111 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import java.io.IOException;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.PduComposer;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.ReadRecInd;
import com.moez.QKSMS.mmssms.Utils;
/**
* The ReadRecTransaction is responsible for sending read report
* notifications (M-read-rec.ind) to clients that have requested them.
* It:
*
* <ul>
* <li>Loads the read report indication from storage (Outbox).
* <li>Packs M-read-rec.ind and sends it.
* <li>Notifies the TransactionService about succesful completion.
* </ul>
*/
public class ReadRecTransaction extends Transaction implements Runnable{
private static final String TAG = "ReadRecTransaction";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private Thread mThread;
private final Uri mReadReportURI;
public ReadRecTransaction(Context context,
int transId,
TransactionSettings connectionSettings,
String uri) {
super(context, transId, connectionSettings);
mReadReportURI = Uri.parse(uri);
mId = uri;
// Attach the transaction to the instance of RetryScheduler.
attach(RetryScheduler.getInstance(context));
}
/*
* (non-Javadoc)
* @see com.android.mms.Transaction#process()
*/
@Override
public void process() {
mThread = new Thread(this, "ReadRecTransaction");
mThread.start();
}
public void run() {
PduPersister persister = PduPersister.getPduPersister(mContext);
try {
// Load M-read-rec.ind from outbox
ReadRecInd readRecInd = (ReadRecInd) persister.load(mReadReportURI);
// insert the 'from' address per spec
String lineNumber = Utils.getMyPhoneNumber(mContext);
readRecInd.setFrom(new EncodedStringValue(lineNumber));
// Pack M-read-rec.ind and send it
byte[] postingData = new PduComposer(mContext, readRecInd).make();
sendPdu(postingData);
Uri uri = persister.move(mReadReportURI, Uri.parse("content://mms/sent"));
mTransactionState.setState(TransactionState.SUCCESS);
mTransactionState.setContentUri(uri);
} catch (IOException e) {
if (LOCAL_LOGV) Log.v(TAG, "Failed to send M-Read-Rec.Ind.", e);
} catch (MmsException e) {
if (LOCAL_LOGV) Log.v(TAG, "Failed to load message from Outbox.", e);
} catch (RuntimeException e) {
Log.e(TAG, "Unexpected RuntimeException.", e);
} finally {
if (mTransactionState.getState() != TransactionState.SUCCESS) {
mTransactionState.setState(TransactionState.FAILED);
mTransactionState.setContentUri(mReadReportURI);
}
notifyObservers();
}
}
@Override
public int getType() {
return READREC_TRANSACTION;
}
}
@@ -1,303 +0,0 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import android.text.TextUtils;
import android.util.Log;
import com.android.mms.util.DownloadManager;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.AcknowledgeInd;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.PduComposer;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.RetrieveConf;
import com.moez.QKSMS.MmsConfig;
import com.moez.QKSMS.mmssms.Utils;
import java.io.IOException;
/**
* The RetrieveTransaction is responsible for retrieving multimedia
* messages (M-Retrieve.conf) from the MMSC server. It:
*
* <ul>
* <li>Sends a GET request to the MMSC server.
* <li>Retrieves the binary M-Retrieve.conf data and parses it.
* <li>Persists the retrieve multimedia message.
* <li>Determines whether an acknowledgement is required.
* <li>Creates appropriate M-Acknowledge.ind and sends it to MMSC server.
* <li>Notifies the TransactionService about succesful completion.
* </ul>
*/
public class RetrieveTransaction extends Transaction implements Runnable {
private static final String TAG = "RetrieveTransaction";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private final Uri mUri;
private final String mContentLocation;
private boolean mLocked;
static final String[] PROJECTION = new String[] {
Mms.CONTENT_LOCATION,
Mms.LOCKED
};
// The indexes of the columns which must be consistent with above PROJECTION.
static final int COLUMN_CONTENT_LOCATION = 0;
static final int COLUMN_LOCKED = 1;
public RetrieveTransaction(Context context, int serviceId,
TransactionSettings connectionSettings, String uri)
throws MmsException {
super(context, serviceId, connectionSettings);
if (uri.startsWith("content://")) {
mUri = Uri.parse(uri); // The Uri of the M-Notification.ind
mId = mContentLocation = getContentLocation(context, mUri);
if (LOCAL_LOGV) Log.v(TAG, "X-Mms-Content-Location: " + mContentLocation);
} else {
throw new IllegalArgumentException(
"Initializing from X-Mms-Content-Location is abandoned!");
}
// Attach the transaction to the instance of RetryScheduler.
attach(RetryScheduler.getInstance(context));
}
private String getContentLocation(Context context, Uri uri)
throws MmsException {
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
uri, PROJECTION, null, null, null);
mLocked = false;
if (cursor != null) {
try {
if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
// Get the locked flag from the M-Notification.ind so it can be transferred
// to the real message after the download.
mLocked = cursor.getInt(COLUMN_LOCKED) == 1;
return cursor.getString(COLUMN_CONTENT_LOCATION);
}
} finally {
cursor.close();
}
}
throw new MmsException("Cannot get X-Mms-Content-Location from: " + uri);
}
/*
* (non-Javadoc)
* @see com.android.mms.transaction.Transaction#process()
*/
@Override
public void process() {
new Thread(this, "RetrieveTransaction").start();
}
public void run() {
try {
// Change the downloading state of the M-Notification.ind.
DownloadManager.getInstance().markState(
mUri, DownloadManager.STATE_DOWNLOADING);
// Send GET request to MMSC and retrieve the response data.
byte[] resp = getPdu(mContentLocation);
// Parse M-Retrieve.conf
RetrieveConf retrieveConf = (RetrieveConf) new PduParser(resp).parse();
if (null == retrieveConf) {
throw new MmsException("Invalid M-Retrieve.conf PDU.");
}
Uri msgUri;
if (isDuplicateMessage(mContext, retrieveConf)) {
// Mark this transaction as failed to prevent duplicate
// notification to user.
mTransactionState.setState(TransactionState.FAILED);
mTransactionState.setContentUri(mUri);
} else {
boolean group;
try {
group = com.moez.QKSMS.mmssms.Transaction.settings.getGroup();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("pref_key_compose_group", true);
}
// Store M-Retrieve.conf into Inbox
PduPersister persister = PduPersister.getPduPersister(mContext);
msgUri = persister.persist(retrieveConf, Uri.parse("content://mms/inbox"), true,
group, null);
// Use local time instead of PDU time
ContentValues values = new ContentValues(1);
values.put(Mms.DATE, System.currentTimeMillis() / 1000L);
SqliteWrapper.update(mContext, mContext.getContentResolver(),
msgUri, values, null, null);
// The M-Retrieve.conf has been successfully downloaded.
mTransactionState.setState(TransactionState.SUCCESS);
mTransactionState.setContentUri(msgUri);
// Remember the location the message was downloaded from.
// Since it's not critical, it won't fail the transaction.
// Copy over the locked flag from the M-Notification.ind in case
// the user locked the message before activating the download.
updateContentLocation(mContext, msgUri, mContentLocation, mLocked);
}
// Delete the corresponding M-Notification.ind.
SqliteWrapper.delete(mContext, mContext.getContentResolver(),
mUri, null, null);
// Send ACK to the Proxy-Relay to indicate we have fetched the
// MM successfully.
// Don't mark the transaction as failed if we failed to send it.
sendAcknowledgeInd(retrieveConf);
} catch (Throwable t) {
Log.e(TAG, Log.getStackTraceString(t));
} finally {
if (mTransactionState.getState() != TransactionState.SUCCESS) {
mTransactionState.setState(TransactionState.FAILED);
mTransactionState.setContentUri(mUri);
Log.e(TAG, "Retrieval failed.");
} else {
mContext.sendBroadcast(new Intent(com.moez.QKSMS.mmssms.Transaction.NOTIFY_OF_MMS));
}
notifyObservers();
}
}
private static boolean isDuplicateMessage(Context context, RetrieveConf rc) {
byte[] rawMessageId = rc.getMessageId();
if (rawMessageId != null) {
String messageId = new String(rawMessageId);
String selection = "(" + Mms.MESSAGE_ID + " = ? AND "
+ Mms.MESSAGE_TYPE + " = ?)";
String[] selectionArgs = new String[] { messageId,
String.valueOf(PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF) };
Cursor cursor = SqliteWrapper.query(
context, context.getContentResolver(),
Mms.CONTENT_URI, new String[] { Mms._ID, Mms.SUBJECT, Mms.SUBJECT_CHARSET },
selection, selectionArgs, null);
if (cursor != null) {
try {
if (cursor.getCount() > 0) {
// A message with identical message ID and type found.
// Do some additional checks to be sure it's a duplicate.
return isDuplicateMessageExtra(cursor, rc);
}
} finally {
cursor.close();
}
}
}
return false;
}
private static boolean isDuplicateMessageExtra(Cursor cursor, RetrieveConf rc) {
// Compare message subjects, taking encoding into account
EncodedStringValue encodedSubjectReceived;
EncodedStringValue encodedSubjectStored = null;
String subjectReceived = null;
String subjectStored;
String subject;
encodedSubjectReceived = rc.getSubject();
if (encodedSubjectReceived != null) {
subjectReceived = encodedSubjectReceived.getString();
}
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
int subjectIdx = cursor.getColumnIndex(Mms.SUBJECT);
int charsetIdx = cursor.getColumnIndex(Mms.SUBJECT_CHARSET);
subject = cursor.getString(subjectIdx);
int charset = cursor.getInt(charsetIdx);
if (subject != null) {
encodedSubjectStored = new EncodedStringValue(charset, PduPersister
.getBytes(subject));
}
if (encodedSubjectStored == null && encodedSubjectReceived == null) {
// Both encoded subjects are null - return true
return true;
} else if (encodedSubjectStored != null && encodedSubjectReceived != null) {
subjectStored = encodedSubjectStored.getString();
if (!TextUtils.isEmpty(subjectStored) && !TextUtils.isEmpty(subjectReceived)) {
// Both decoded subjects are non-empty - compare them
return subjectStored.equals(subjectReceived);
} else if (TextUtils.isEmpty(subjectStored) && TextUtils.isEmpty(subjectReceived)) {
// Both decoded subjects are "" - return true
return true;
}
}
}
return false;
}
private void sendAcknowledgeInd(RetrieveConf rc) throws MmsException, IOException {
// Send M-Acknowledge.ind to MMSC if required.
// If the Transaction-ID isn't set in the M-Retrieve.conf, it means
// the MMS proxy-relay doesn't require an ACK.
byte[] tranId = rc.getTransactionId();
if (tranId != null) {
// Create M-Acknowledge.ind
AcknowledgeInd acknowledgeInd = new AcknowledgeInd(
PduHeaders.CURRENT_MMS_VERSION, tranId);
// insert the 'from' address per spec
String lineNumber = Utils.getMyPhoneNumber(mContext);
acknowledgeInd.setFrom(new EncodedStringValue(lineNumber));
// Pack M-Acknowledge.ind and send it
if(MmsConfig.getNotifyWapMMSC()) {
sendPdu(new PduComposer(mContext, acknowledgeInd).make(), mContentLocation);
} else {
sendPdu(new PduComposer(mContext, acknowledgeInd).make());
}
}
}
private static void updateContentLocation(Context context, Uri uri,
String contentLocation,
boolean locked) {
ContentValues values = new ContentValues(2);
values.put(Mms.CONTENT_LOCATION, contentLocation);
values.put(Mms.LOCKED, locked); // preserve the state of the M-Notification.ind lock.
SqliteWrapper.update(context, context.getContentResolver(),
uri, values, null, null);
}
@Override
public int getType() {
return RETRIEVE_TRANSACTION;
}
}

Some files were not shown because too many files have changed in this diff Show More