================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
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.
Copyright (C)
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 .
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:
Copyright (C)
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
.
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
.
================================================
FILE: README.md
================================================
# AutoDing
+ 目前release中的包名于24年圣诞节下午又又被加入黑名单了,为了不被再一次被加入黑名单,之后将不再提供APK包的更新,但我会详尽列出各位自行打包需要的步骤,请各位自行下载源码修改一个包名并做如下定制打包。
1. 起一个包名,结构类似com.furry.rimet这种,修改app级build.gradle中applicationId,daoPackage的前缀为自己的(查找替换即可)
2. 修改app/src/main/AndroidManifest.xml中包名,查找替换即可
3. 重新进行gradle sync,完成后执行Build————Rebuild Project
4. 然后去极光推送开发者后台建一个应用,用刚才自己重构的applicationId申请一个推送应用,把appKey,masterSecret保存
5. 在app级build.gradle配置中的manifestPlaceholders中的JPUSH_APPKEY值换成上一步的appKey
6. 在代码搜索类AuthInterceptor,替换里面的常量appKey和masterSecret
7. (可选)打包前也可修改app/src/main/res/values/strings.xml里面的app_name值,即应用名,防止应用名也被屏蔽
8. 重新打包,然后分别装在两个手机上,配置推送regID,测试是否可发送响应指令
-------------
钉钉打卡,包括定时打卡和远程推送打卡,定时打卡功能是根据AutoDingDing项目修改而来,不是此项目重点,此项目主要功能在于实现远程
打开钉钉,从而完成极速打卡,其主要是用极光推送SDK实现网络指令下发。
建议用一台闲置的手机放在公司来打卡,另一台手机来推送打卡指令。
需要一台打卡手机,一台自用手机,都安装上此APP后,把打卡手机的注册ID复制到推送界面推送打卡指令可以远程打开钉钉,完成极速打卡。使用须知:
1. 请先确认好要打卡的手机通知栏监听已开启,如不开启将无法监听打卡成功的通知。
2. 要打卡的手机保持连网,wifi或者数据都可,否则怎么收网络指令啊。
3. 要打卡的手机最好保持打开界面放置灭屏,因为如果应用被切到后台,过上一晚不活跃有可能会被安卓系统杀掉从而不能接收打卡指令。
4. 调起钉钉实现自动打卡,需要把打卡手机锁屏密码之类的取消掉,屏幕不用常亮,但锁屏手势、指纹、密码这些验证不能有,否则在熄屏状态下应用接收到消息也无法唤醒屏幕。
5. 部分手机需要授权允许后台打开窗口,先在设置里面测试下能否正常打开钉钉,第一次有些手机会让授权。
6. 将钉钉软件上下班都设置为“极速打卡”。
7. 设置好自己的发信和收信邮箱,跳转到“钉钉”打卡成功后会发送一封打卡成功的邮件到你自己设置好的邮箱。
8. 不要忘了,此应用只能打开钉钉,如果你钉钉没登录、被其他设备踢下线、打开时机不在考勤时间区间里,极速打卡是不会生效的。
+ 请在邮件配置中尽量使用自己的qq邮箱,申请邮箱授权码的方法请上网查询,目前邮箱只支持qq邮箱,因为邮箱服务器和端口在代码里写死了,想用别的邮箱的可以找到这部分代码修改这部分设置
-------------
可选建议
1. 在应用权限设置里设置成允许锁屏显示,能大幅降低打卡唤醒应用时被各种不能取消的锁屏带来的干扰
2. 在开发者模式中设置充电时不锁定屏幕,然后一直插电保持亮屏,则肯定能保证稳定运行和接收消息,可以把屏幕调到最暗来减少屏幕损耗
================================================
FILE: app/.gitignore
================================================
/build
================================================
FILE: app/build.gradle
================================================
plugins {
id 'com.android.application'
id 'org.greenrobot.greendao'
id 'kotlin-android'
id 'kotlin-kapt'
}
android {
compileSdk 33
defaultConfig {
applicationId "xcom.warof.chosen"
minSdkVersion 23
targetSdkVersion 33
versionCode 18
versionName "1.1.8"
ndk {
//选择要添加的对应 cpu 类型的 .so 库。
abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a'
// 还可以添加 'x86', 'x86_64', 'mips', 'mips64'
}
manifestPlaceholders = [
JPUSH_PKGNAME : applicationId,
JPUSH_APPKEY : "f01b8a02b66ea2d632e52e2e", //JPush 上注册的包名对应的 Appkey.
JPUSH_CHANNEL : "jpush", //暂时填写默认值即可.
VERSION_NAME : versionName,
CHANNEL : 'self',
DEBUG : true,
MEIZU_APPKEY : "MZ-魅族的APPKEY",
MEIZU_APPID : "MZ-魅族的APPID",
XIAOMI_APPID : "MI-小米的APPID",
XIAOMI_APPKEY : "MI-小米的APPKEY",
OPPO_APPKEY : "OP-oppo的APPKEY",
OPPO_APPID : "OP-oppo的APPID",
OPPO_APPSECRET : "OP-oppo的APPSECRET",
VIVO_APPKEY : "vivo的APPKEY",
VIVO_APPID : "vivo的APPID"
]
}
signingConfigs {
sign {
storeFile file("../sxwdsoft.jks")
storePassword "sxwdsoft4989"
keyAlias "sxwdsoft"
keyPassword "sxwdsoft4989"
}
}
buildTypes {
release {
minifyEnabled false
// 启用资源压缩,需配合 minifyEnabled=true 使用
shrinkResources false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.sign
}
debug {
debuggable true
manifestPlaceholders["DEBUG"] = debuggable
minifyEnabled false
shrinkResources false
signingConfig signingConfigs.sign
//禁用PNG压缩。
crunchPngs false
}
}
packagingOptions {
resources {
excludes += ['META-INF/NOTICE.md', 'META-INF/LICENSE.md']
}
}
compileOptions {
targetCompatibility JavaVersion.VERSION_17
sourceCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = '17'
}
greendao {
schemaVersion 1//数据库版本号
targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录
daoPackage 'xcom.warof.chosen.greendao'//设置DaoMaster、DaoSession、Dao包名
}
buildFeatures {
viewBinding true
dataBinding true
buildConfig true
}
namespace 'com.pengxh.autodingding'
lint {
checkReleaseBuilds false
}
}
tasks.configureEach { task ->
if (task.name.matches("\\w*compile\\w*Kotlin")) {
task.dependsOn('greendao')
}
if (task.name.matches("\\w*kaptGenerateStubs\\w*Kotlin")) {
task.dependsOn('greendao')
}
if (task.name.matches("\\w*kapt\\w*Kotlin")) {
task.dependsOn('greendao')
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.core:core-ktx:1.8.0'
implementation 'com.android.databinding:viewbinding:7.2.2'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
implementation "androidx.lifecycle:lifecycle-common-java8:2.2.0"
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
//Google官方授权库
implementation 'pub.devrel:easypermissions:3.0.0'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.jzxiang.pickerview:TimePickerDialog:1.0.1'
implementation 'com.sun.mail:android-mail:1.6.6'
implementation 'com.sun.mail:android-activation:1.6.6'
//事件总线
implementation 'com.github.liangjingkanji:Channel:1.1.5'
//retrofit okhttp
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2"
//上拉加载下拉刷新
implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0'
implementation group: 'net.sourceforge.jexcelapi', name: 'jxl', version: '2.6.12'
//沉浸式状态栏。基础依赖包,必须要依赖
implementation 'com.gyf.immersionbar:immersionbar:3.0.0'
implementation 'com.afollestad.material-dialogs:core:3.2.1'
//fragment快速实现
implementation 'com.gyf.immersionbar:immersionbar-components:3.0.0'
//数据库框架
implementation 'org.greenrobot:greendao:3.3.0'
implementation "com.blankj:utilcodex:1.30.5"
implementation 'cn.jiguang.sdk:jpush:5.2.2'
implementation 'cn.jiguang.sdk:joperate:2.0.2'
//无障碍
implementation 'com.github.Krosxx:Android-Auto-Api:4.1.2'
}
================================================
FILE: app/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
================================================
FILE: app/src/main/AndroidManifest.xml
================================================
================================================
FILE: app/src/main/java/com/pengxh/autodingding/AndroidxBaseActivity.java
================================================
package com.pengxh.autodingding;
import android.os.Bundle;
import android.view.LayoutInflater;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.viewbinding.ViewBinding;
import com.gyf.immersionbar.ImmersionBar;
import com.pengxh.autodingding.utils.StatusBarColorUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public abstract class AndroidxBaseActivity extends AppCompatActivity {
protected VB viewBinding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Type type = getClass().getGenericSuperclass();
if (type == null) {
throw new NullPointerException();
}
Class> cls = (Class>) ((ParameterizedType) type).getActualTypeArguments()[0];
try {
Method method = cls.getDeclaredMethod("inflate", LayoutInflater.class);
viewBinding = (VB) method.invoke(null, getLayoutInflater());
if (viewBinding == null) {
throw new NullPointerException();
}
setContentView(viewBinding.getRoot());
StatusBarColorUtil.setColor(this, ContextCompat.getColor(this, R.color.colorAppThemeLight));
ImmersionBar.with(this).statusBarDarkFont(false).init();//沉浸式状态栏
setupTopBarLayout();
initData();
initEvent();
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* 初始化默认数据
*/
protected abstract void initData();
/**
* 特定页面定制沉浸式状态栏
*/
protected abstract void setupTopBarLayout();
/**
* 初始化业务逻辑
*/
protected abstract void initEvent();
@Override
protected void onDestroy() {
viewBinding = null;
super.onDestroy();
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/AndroidxBaseFragment.java
================================================
package com.pengxh.autodingding;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public abstract class AndroidxBaseFragment extends Fragment {
protected VB viewBinding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Type type = getClass().getGenericSuperclass();
if (type == null) {
throw new NullPointerException();
}
Class> cls = (Class>) ((ParameterizedType) type).getActualTypeArguments()[0];
try {
Method method = cls.getDeclaredMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
viewBinding = (VB) method.invoke(null, getLayoutInflater(), container, false);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
if (viewBinding == null) {
throw new NullPointerException();
}
setupTopBarLayout();
initData();
initEvent();
return viewBinding.getRoot();
}
protected abstract void setupTopBarLayout();
/**
* 初始化默认数据
*/
protected abstract void initData();
/**
* 初始化业务逻辑
*/
protected abstract void initEvent();
@Override
public void onDestroyView() {
viewBinding = null;
super.onDestroyView();
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ApiException.kt
================================================
package com.pengxh.autodingding
class ApiException(val errorMessage: String, val errorCode: Int) :
Throwable()
================================================
FILE: app/src/main/java/com/pengxh/autodingding/BaseApplication.kt
================================================
package com.pengxh.autodingding
import android.app.Application
import android.content.Context
import cn.jpush.android.api.JPushInterface
import cn.vove7.andro_accessibility_api.AccessibilityApi
import com.blankj.utilcode.util.CacheDiskUtils
import com.pengxh.autodingding.greendao.DaoMaster
import com.pengxh.autodingding.greendao.DaoMaster.DevOpenHelper
import com.pengxh.autodingding.greendao.DaoSession
import com.pengxh.autodingding.service.BaseAccessibilityService
import com.pengxh.autodingding.service.GestureService
import com.pengxh.autodingding.utils.Utils
class BaseApplication : Application() {
override fun onCreate() {
super.onCreate()
application = this
Utils.init(this)
initDataBase()
JPushInterface.setDebugMode(true)
JPushInterface.init(this)
val strings = HashSet()
strings.add("main")
JPushInterface.setTags(this, 0, strings)
val pushRegId = JPushInterface.getRegistrationID(this)
CacheDiskUtils.getInstance().put("pushRegId", pushRegId)
//辅助服务
AccessibilityApi.apply {
BASE_SERVICE_CLS = BaseAccessibilityService::class.java
GESTURE_SERVICE_CLS = GestureService::class.java
}
}
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
application = this;
}
private fun initDataBase() {
val helper = DevOpenHelper(this, "DingRecord.db")
val db = helper.writableDatabase
val daoMaster = DaoMaster(db)
daoSession = daoMaster.newSession()
}
companion object {
@JvmStatic
var daoSession: DaoSession? = null
private set
@Volatile
var application: BaseApplication? = null
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/BatteryLevelReceiver.kt
================================================
package com.pengxh.autodingding
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.BatteryManager
import cn.jpush.android.api.JPushInterface
import com.blankj.utilcode.util.ProcessUtils
import com.blankj.utilcode.util.ScreenUtils
import com.pengxh.autodingding.utils.SendMailUtil
import com.pengxh.autodingding.utils.Utils
class BatteryLevelReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (Intent.ACTION_BATTERY_LOW == action){
val emailAddress = Utils.readEmailAddress()
val manager = context.getSystemService(AndroidxBaseActivity.BATTERY_SERVICE) as BatteryManager
val curBatteryCurrent = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW)
val curBattery = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)///当前电量百分比
val regId = JPushInterface.getRegistrationID(context)
val screenLock = ScreenUtils.isScreenLock()
val message = "警告!低电量!注册ID: $regId 是否锁屏:$screenLock " +
"当前电流:$curBatteryCurrent mA 当前电量百分比:$curBattery %"
SendMailUtil.send(emailAddress, message)
}
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/actions/Action.kt
================================================
package com.pengxh.autodingding.actions
import android.app.Activity
abstract class Action {
abstract val name: String
abstract suspend fun run(act: Activity)
override fun toString() = name
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/actions/DingSignAction.kt
================================================
package com.pengxh.autodingding.actions
import android.app.Activity
import android.graphics.Point
import cn.vove7.andro_accessibility_api.requireBaseAccessibility
import cn.vove7.auto.core.api.back
import cn.vove7.auto.core.api.click
import cn.vove7.auto.core.viewfinder.SF
import cn.vove7.auto.core.viewfinder.containsText
import cn.vove7.auto.core.viewfinder.id
import com.blankj.utilcode.util.TimeUtils
import com.pengxh.autodingding.utils.Constant
import com.pengxh.autodingding.utils.toast
import kotlinx.coroutines.delay
class DingSignAction : Action() {
private var result = false
var message = StringBuilder()
override val name: String
get() = "打开钉钉,手动打卡"
override suspend fun run(act: Activity) {
requireBaseAccessibility(true)
toast("1秒后启动钉钉")
delay(1000)
val targetApp = Constant.DINGDING
genLog("启动钉钉")
act.startActivity(act.packageManager.getLaunchIntentForPackage(targetApp))
delay(9000)
genLog("查找钉钉首页元素")
val messageTab = SF.containsText("消息").findFirst(false)
toast(if (messageTab != null) "找到消息按钮" else "未找到消息按钮")
if (messageTab != null) {
messageTab.tryClick()
delay(2000)
}
val signTab = SF.containsText("打卡").findFirst(false)
toast("找到${signTab != null}打卡")
genLog("查找打卡入口")
if (signTab != null) {
val signClick = signTab.tryClick()
genLog("点击打卡入口" + if (signClick) "成功" else "失败")
toast("8秒后尝试寻找打卡按钮")
delay(8000)
}
val webPage = SF.id("com.alibaba.android.rimet:id/h5_pc_container").findFirst()
genLog("查找打卡webView" + if (webPage != null) "成功" else "失败")
var clickSucceed = false
if (webPage != null) {
val centerP = webPage.getCenterPoint()
for (i in 1..5) {
val delta = 70
tryClick(Point(centerP.x, centerP.y + i * delta))
clickSucceed = SF.containsText("成功")
.findFirst(false) != null
if (clickSucceed) {
break
}
}
}
genLog("点击打卡" + if (clickSucceed) "成功" else "失败" + ",准备查看页面结果")
val succeed = SF.containsText("成功")
.findFirst(false) != null
toast("手动打卡 " + if (succeed) "成功" else "失败")
genLog("页面结果判断打卡" + if (succeed) "成功" else "失败" + ",准备回退")
delay(2000)
back()
genLog("回退第一次")
delay(2000)
back()
result = succeed
genLog("回退第二次,执行结束,最终执行判定:" + if (result) "成功" else "失败")
}
private fun genLog(actionDesc: String) {
message.append(actionDesc + "-----" + TimeUtils.getNowString() + "\n")
}
private suspend fun tryClick(p: Point) {
click(p.x, p.y)
val delayTime = 5L
genLog("点击坐标点${p.x},${p.y},并等待${delayTime}秒")
delay(delayTime * 1000)
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/actions/SwipeUnlockAction.kt
================================================
package com.pengxh.autodingding.actions
import android.app.Activity
import cn.vove7.auto.core.api.swipe
import kotlinx.coroutines.delay
class SwipeUnlockAction(val orientation: ORIENTATION=ORIENTATION.VERTICAL): Action() {
enum class ORIENTATION{
HORIZONTAL,VERTICAL,CUSTOM
}
constructor(startX:Int, startY:Int, endX:Int, endY:Int) : this(ORIENTATION.CUSTOM) {
this.startX = startX
this.startY = startY
this.endX = endX
this.endY = endY
}
var startX= 0
var startY = 0
var endX = 0
var endY = 0
override val name: String
get() = "解锁"
override suspend fun run(act: Activity) {
delay(1000)
//从下往上的滑动
when (orientation) {
ORIENTATION.VERTICAL -> swipe(500, 1200, 500, 400, 800)
ORIENTATION.HORIZONTAL -> swipe(100, 900, 600, 900, 800)
else -> swipe(startX, startY, endX, endY, 800)
}
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/adapter/FragAdapter.kt
================================================
package com.pengxh.autodingding.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
class FragAdapter(fragmentActivity: FragmentActivity,
private val pageList:List) : FragmentStateAdapter(fragmentActivity) {
override fun getItemCount(): Int {
return pageList.size
}
override fun createFragment(position: Int): Fragment = pageList[position]
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/adapter/HistoryRecordAdapter.kt
================================================
package com.pengxh.autodingding.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.pengxh.autodingding.R
import com.pengxh.autodingding.bean.HistoryRecordBean
class HistoryRecordAdapter(mContext: Context?, private val beanList: List?) :
BaseAdapter() {
private val mInflater: LayoutInflater
init {
mInflater = LayoutInflater.from(mContext)
}
override fun getCount(): Int {
return beanList?.size ?: 0
}
override fun getItem(position: Int): Any {
return beanList!![position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
val holder: HistoryViewHolder
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_list, parent)
holder = HistoryViewHolder()
holder.noticeDate = convertView.findViewById(R.id.noticeDate)
holder.noticeMessage = convertView.findViewById(R.id.noticeMessage)
holder.tagView = convertView.findViewById(R.id.tagView)
convertView.tag = holder
} else {
holder = convertView.tag as HistoryViewHolder
}
holder.bindData(beanList!![position])
return convertView!!
}
private class HistoryViewHolder {
var noticeDate: TextView? = null
var noticeMessage: TextView? = null
var tagView: ImageView? = null
fun bindData(historyBean: HistoryRecordBean) {
val message = historyBean.message
if (!message.contains("成功")) {
tagView!!.setBackgroundResource(R.drawable.bg_textview_error)
}
noticeMessage!!.text = message
noticeDate!!.text = historyBean.date
}
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/base/ApiResponse.kt
================================================
package com.pengxh.autodingding.base
data class ApiResponse(var errorCode: Int, var errorMsg: String, var data: T) {
fun isSucces(): Boolean {
return errorCode == 0
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/base/BaseViewModel.kt
================================================
package com.pengxh.autodingding.base
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.pengxh.autodingding.ApiException
import com.pengxh.autodingding.BuildConfig
import kotlinx.coroutines.*
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
typealias VmError = (e: ApiException) -> Unit
open class BaseViewModel: ViewModel() {
val coroutineExceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
throwable.printStackTrace()
LogUtils.e(coroutineContext, throwable)
}
/**
* 错误信息liveData
*/
val errorLiveData = MutableLiveData()
/**
* 无更多数据
*/
val footLiveDate = MutableLiveData()
/**
* 无数据
*/
val emptyLiveDate = MutableLiveData()
/**
* 处理错误
*/
protected fun launch(
block: () -> T
, error:VmError? = null) {
viewModelScope.launch {
runCatching {
block()
}.onFailure {
it.printStackTrace()
getApiException(it).apply {
withContext(Dispatchers.Main){
error?.invoke(this@apply)
}
}
}
}
}
protected fun launch(block: suspend () -> T) {
viewModelScope.launch {
runCatching {
block()
}.onFailure {
if (BuildConfig.DEBUG) {
it.printStackTrace()
}
getApiException(it).apply {
withContext(Dispatchers.Main){
//统一响应错误信息
errorLiveData.value = this@apply
}
}
}
}
}
/**
* 捕获异常信息
*/
private fun getApiException(e: Throwable): ApiException {
return when (e) {
is UnknownHostException -> {
ApiException("网络异常", -100)
}
is JSONException -> {//|| e is JsonParseException
ApiException("数据异常", -100)
}
is SocketTimeoutException -> {
ApiException("连接超时", -100)
}
is ConnectException -> {
ApiException("连接错误", -100)
}
is HttpException -> {
ApiException("http code ${e.code()}", -100)
}
is ApiException -> {
e
}
/**
* 如果协程还在运行,个别机型退出当前界面时,viewModel会通过抛出CancellationException,
* 强行结束协程,与java中InterruptException类似,所以不必理会,只需将toast隐藏即可
*/
is CancellationException -> {
ApiException("", -10)
}
else -> {
ApiException("未知错误", -100)
}
}
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/base/BaseVmFragment.kt
================================================
package com.pengxh.autodingding.base
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.Keep
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.pengxh.autodingding.utils.ParamUtil
@Keep
abstract class BaseVmFragment : Fragment() {
/**
* 开放给外部使用
*/
lateinit var mContext: Context
lateinit var mActivity: AppCompatActivity
private var fragmentProvider: ViewModelProvider? = null
private var activityProvider: ViewModelProvider? = null
protected lateinit var binding: BD
private var mBinding: ViewDataBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//由于同一个fragment对象可能被activity attach多次(比如viewPager+PagerStateAdapter中)
//所以fragmentViewModel不能放在onCreateView初始化,否则会产生多个fragmentViewModel
initFragmentViewModel()
}
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
mActivity = context as AppCompatActivity
// 必须要在Activity与Fragment绑定后,因为如果Fragment可能获取的是Activity中ViewModel
// 必须在onCreateView之前初始化viewModel,因为onCreateView中需要通过ViewModel与DataBinding绑定
initViewModel()
ParamUtil.initParam(this)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
getLayoutId()?.let {
//获取ViewDataBinding
binding = DataBindingUtil.inflate(inflater, it, container, false)
//将ViewDataBinding生命周期与Fragment绑定
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
init(savedInstanceState)
//observe一定要在初始化最后,因为observe会收到黏性事件,随后对ui做处理
observe()
onClick()
}
/**
* 初始化viewModel
* 之所以没有设计为抽象,是因为部分简单activity可能不需要viewModel
* observe同理
*/
open fun initViewModel() {
}
open fun initFragmentViewModel() {
}
/**
* 注册观察者
*/
open fun observe() {
}
/**
* 通过activity获取viewModel,跟随activity生命周期
*/
protected fun getActivityViewModel(modelClass: Class): T {
if (activityProvider == null) {
activityProvider = ViewModelProvider(mActivity)
}
return activityProvider!![modelClass]
}
/**
* 通过fragment获取viewModel,跟随fragment生命周期
*/
protected open fun getFragmentViewModel(modelClass: Class): T {
if (fragmentProvider == null) {
fragmentProvider = ViewModelProvider(this)
}
return fragmentProvider!![modelClass]
}
/**
* 点击事件
*/
open fun onClick() {
}
/**
* 初始化View以及事件
*/
open fun initView() {
}
/**
* 加载数据
*/
open fun loadData() {
}
/**
* 获取layout布局
*/
abstract fun getLayoutId(): Int?
/**
* 初始化入口
*/
abstract fun init(savedInstanceState: Bundle?)
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/AndroidNotif.kt
================================================
package com.pengxh.autodingding.bean
class AndroidNotif {
var title:String? = null
var category:String? = "CATEGORY_REMINDER"
var priority:Int = 1
val display_foreground:String = "1"
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/BodyMsg.kt
================================================
package com.pengxh.autodingding.bean
import org.json.JSONObject
class BodyMsg {
var msg_content:String = ""
var title = "cmd"
var content_type:String? = null
var extras:JSONObject? = null
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/HistoryRecordBean.java
================================================
package com.pengxh.autodingding.bean;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
@Entity
public class HistoryRecordBean {
@Id(autoincrement = true)
private Long id;//主键ID
private String uuid;
private String date;
private String message;
@Generated(hash = 1681950394)
public HistoryRecordBean(Long id, String uuid, String date, String message) {
this.id = id;
this.uuid = uuid;
this.date = date;
this.message = message;
}
@Generated(hash = 1791356846)
public HistoryRecordBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getUuid() {
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/MailInfo.kt
================================================
package com.pengxh.autodingding.bean
import java.io.File
import java.util.Properties
/**
* @author: lttclaw
* @email: lttclaw@qq.com
* @description: 邮件相关
* @date: 2020/1/16 15:40
*/
class MailInfo {
// 发送邮件的服务器的IP和端口
var mailServerHost: String? = null
var mailServerPort: String? = null
// 邮件发送者的地址
var fromAddress: String? = null
// 邮件接收者的地址
var toAddress: String? = null
// 登陆邮件发送服务器的用户名和密码
var userName: String? = null
var password: String? = null
// 是否需要身份验证
var isValidate = false
// 邮件主题
var subject: String? = null
// 邮件的文本内容
var content: String? = null
// 邮件的附件
var attachFile: File? = null
// 邮件附件的文件名
var attachFileName: String? = null
val properties: Properties
/**
* 获得邮件会话属性
*/
get() {
val p = Properties()
p["mail.smtp.host"] = mailServerHost
p["mail.smtp.port"] = mailServerPort
p["mail.smtp.ssl.enable"] = "true"
p["mail.smtp.auth"] = "true"
return p
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/PushAudience.kt
================================================
package com.pengxh.autodingding.bean
class PushAudience {
var registration_id: MutableList = mutableListOf()
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/PushChannel.kt
================================================
package com.pengxh.autodingding.bean
class PushChannel {
var distribution_customize = "secondary_push"
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/PushMessage.kt
================================================
package com.pengxh.autodingding.bean
class PushMessage {
var platform = "android"
var audience: PushAudience? = null
var notification: PushNotification? = null
var message: BodyMsg? = null
var options: PushOption? = null
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/PushNotification.kt
================================================
package com.pengxh.autodingding.bean
class PushNotification {
var alert:String?= null
var android:AndroidNotif? = null
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/PushOption.kt
================================================
package com.pengxh.autodingding.bean
class PushOption {
var third_party_channel:ThirdPartyConf? = ThirdPartyConf()
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/PushResp.kt
================================================
package com.pengxh.autodingding.bean
class PushResp {
var errorCode = 0
var messageCn:String? = null
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/ThirdPartyConf.kt
================================================
package com.pengxh.autodingding.bean
class ThirdPartyConf {
var huawei: PushChannel = PushChannel()
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/Version.kt
================================================
package com.pengxh.autodingding.bean
data class Version(val apkUrl:String, val versionCode: Int, val versionName: String, val description: String, val apkSize: String)
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/Workday.kt
================================================
package com.pengxh.autodingding.bean
data class Workday(val type:Int, val name: String, val date:String, val rest: Int)
================================================
FILE: app/src/main/java/com/pengxh/autodingding/bean/WorkdayResp.kt
================================================
package com.pengxh.autodingding.bean
class WorkdayResp{
val code :Int = 0
var workday: Workday? = null
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/greendao/DaoMaster.java
================================================
package com.pengxh.autodingding.greendao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
import org.greenrobot.greendao.AbstractDaoMaster;
import org.greenrobot.greendao.database.StandardDatabase;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseOpenHelper;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* Master of DAO (schema version 1): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(Database db, boolean ifNotExists) {
HistoryRecordBeanDao.createTable(db, ifNotExists);
}
/** Drops underlying database table using DAOs. */
public static void dropAllTables(Database db, boolean ifExists) {
HistoryRecordBeanDao.dropTable(db, ifExists);
}
/**
* WARNING: Drops all table on Upgrade! Use only during development.
* Convenience method using a {@link DevOpenHelper}.
*/
public static DaoSession newDevSession(Context context, String name) {
Database db = new DevOpenHelper(context, name).getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
return daoMaster.newSession();
}
public DaoMaster(SQLiteDatabase db) {
this(new StandardDatabase(db));
}
public DaoMaster(Database db) {
super(db, SCHEMA_VERSION);
registerDaoClass(HistoryRecordBeanDao.class);
}
public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
public DaoSession newSession(IdentityScopeType type) {
return new DaoSession(db, type, daoConfigMap);
}
/**
* Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} -
*/
public static abstract class OpenHelper extends DatabaseOpenHelper {
public OpenHelper(Context context, String name) {
super(context, name, SCHEMA_VERSION);
}
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}
@Override
public void onCreate(Database db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}
/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/greendao/DaoSession.java
================================================
package com.pengxh.autodingding.greendao;
import java.util.Map;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;
import com.pengxh.autodingding.bean.HistoryRecordBean;
import com.pengxh.autodingding.greendao.HistoryRecordBeanDao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see org.greenrobot.greendao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig historyRecordBeanDaoConfig;
private final HistoryRecordBeanDao historyRecordBeanDao;
public DaoSession(Database db, IdentityScopeType type, Map>, DaoConfig>
daoConfigMap) {
super(db);
historyRecordBeanDaoConfig = daoConfigMap.get(HistoryRecordBeanDao.class).clone();
historyRecordBeanDaoConfig.initIdentityScope(type);
historyRecordBeanDao = new HistoryRecordBeanDao(historyRecordBeanDaoConfig, this);
registerDao(HistoryRecordBean.class, historyRecordBeanDao);
}
public void clear() {
historyRecordBeanDaoConfig.clearIdentityScope();
}
public HistoryRecordBeanDao getHistoryRecordBeanDao() {
return historyRecordBeanDao;
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/greendao/HistoryRecordBeanDao.java
================================================
package com.pengxh.autodingding.greendao;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import com.pengxh.autodingding.bean.HistoryRecordBean;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "HISTORY_RECORD_BEAN".
*/
public class HistoryRecordBeanDao extends AbstractDao {
public static final String TABLENAME = "HISTORY_RECORD_BEAN";
/**
* Properties of entity HistoryRecordBean.
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Uuid = new Property(1, String.class, "uuid", false, "UUID");
public final static Property Date = new Property(2, String.class, "date", false, "DATE");
public final static Property Message = new Property(3, String.class, "message", false, "MESSAGE");
}
public HistoryRecordBeanDao(DaoConfig config) {
super(config);
}
public HistoryRecordBeanDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"HISTORY_RECORD_BEAN\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"\"UUID\" TEXT," + // 1: uuid
"\"DATE\" TEXT," + // 2: date
"\"MESSAGE\" TEXT);"); // 3: message
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"HISTORY_RECORD_BEAN\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, HistoryRecordBean entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String uuid = entity.getUuid();
if (uuid != null) {
stmt.bindString(2, uuid);
}
String date = entity.getDate();
if (date != null) {
stmt.bindString(3, date);
}
String message = entity.getMessage();
if (message != null) {
stmt.bindString(4, message);
}
}
@Override
protected final void bindValues(SQLiteStatement stmt, HistoryRecordBean entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String uuid = entity.getUuid();
if (uuid != null) {
stmt.bindString(2, uuid);
}
String date = entity.getDate();
if (date != null) {
stmt.bindString(3, date);
}
String message = entity.getMessage();
if (message != null) {
stmt.bindString(4, message);
}
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public HistoryRecordBean readEntity(Cursor cursor, int offset) {
HistoryRecordBean entity = new HistoryRecordBean( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // uuid
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // date
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3) // message
);
return entity;
}
@Override
public void readEntity(Cursor cursor, HistoryRecordBean entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setUuid(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setDate(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setMessage(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
}
@Override
protected final Long updateKeyAfterInsert(HistoryRecordBean entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(HistoryRecordBean entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(HistoryRecordBean entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/net/AuthInterceptor.kt
================================================
package com.pengxh.autodingding.net
import com.blankj.utilcode.util.EncodeUtils
import com.blankj.utilcode.util.LogUtils
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
object AuthInterceptor : Interceptor {
private const val appKey = "f01b8a02b66ea2d632e52e2e"
private const val masterSecret = "5e9ebea1163a6f3e2197f35d"
private const val authString = "$appKey:$masterSecret"
private var token = "Basic ${EncodeUtils.base64Encode2String(authString.toByteArray())}"
set(value) {
field = value
}
override fun intercept(chain: Interceptor.Chain): Response {
val origin = chain.request()
val builder = origin.newBuilder().addHeader("Authorization", token)
val response : Response
try {
response = chain.proceed(builder.build())
}catch (e:Exception){
e.printStackTrace()
throw IOException(e)
}
return response
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/net/RetrofitManager.kt
================================================
package com.pengxh.autodingding.net
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
object RetrofitManager {
private const val BASE_URL ="https://api.jpush.cn"
private const val API_DAY_URL = "http://timor.tech"
private const val UPDATE_BASE_URL = "http://smallfurrypaw.top"
lateinit var okHttpClient: OkHttpClient
val retrofitClient: Retrofit
get() {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(genericOkClient())
.build()
}
val workdayClient: Retrofit
get() {
return Retrofit.Builder()
.baseUrl(API_DAY_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(generateWorkdayClient())
.build()
}
val updateClient: Retrofit
get(){
return Retrofit.Builder()
.baseUrl(UPDATE_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(generateWorkdayClient())
.build()
}
private fun genericOkClient(): OkHttpClient {
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
return OkHttpClient.Builder()
.connectTimeout(5_000L, TimeUnit.MILLISECONDS)
.readTimeout(10_000, TimeUnit.MILLISECONDS)
.writeTimeout(30_000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(AuthInterceptor)
.build().also {
okHttpClient = it
}
}
private fun generateWorkdayClient(): OkHttpClient {
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
return OkHttpClient.Builder()
.connectTimeout(5_000L, TimeUnit.MILLISECONDS)
.readTimeout(10_000, TimeUnit.MILLISECONDS)
.writeTimeout(30_000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(false)
.addInterceptor(httpLoggingInterceptor)
.build()
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/net/api/PushApi.kt
================================================
package com.pengxh.autodingding.net.api
import com.pengxh.autodingding.bean.PushMessage
import com.pengxh.autodingding.bean.PushResp
import retrofit2.http.Body
import retrofit2.http.POST
interface PushApi {
@POST("v3/push")
suspend fun pushMsg(@Body pushMessage: PushMessage): PushResp
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/net/api/UpdateApi.kt
================================================
package com.pengxh.autodingding.net.api
import com.pengxh.autodingding.base.ApiResponse
import com.pengxh.autodingding.bean.Version
import retrofit2.http.GET
interface UpdateApi {
@GET("api/version.json")
suspend fun getVersion(): ApiResponse
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/net/api/WorkDayApi.kt
================================================
package com.pengxh.autodingding.net.api
import com.pengxh.autodingding.bean.WorkdayResp
import retrofit2.http.GET
import retrofit2.http.Headers
interface WorkDayApi {
@Headers("User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
@GET("/api/holiday/workday/next/")
suspend fun getNextWorkday(): WorkdayResp
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/service/BaseAccessibilityService.kt
================================================
package com.pengxh.autodingding.service
import android.util.Log
import cn.vove7.andro_accessibility_api.AccessibilityApi
import cn.vove7.auto.core.AppScope
class BaseAccessibilityService: AccessibilityApi() {
override val enableListenPageUpdate: Boolean
get() = true
companion object {
private const val TAG = "BaseAccessibilityService"
}
override fun onCreate() {
//must set
baseService = this
super.onCreate()
}
override fun onDestroy() {
//must set
baseService = null
super.onDestroy()
}
//页面更新回调
override fun onPageUpdate(currentScope: AppScope) {
Log.d(TAG, "onPageUpdate: $currentScope")
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/service/GestureService.kt
================================================
package com.pengxh.autodingding.service
import android.accessibilityservice.AccessibilityService
import android.view.accessibility.AccessibilityEvent
import cn.vove7.andro_accessibility_api.AccessibilityApi
class GestureService: AccessibilityService() {
override fun onCreate() {
super.onCreate()
//must call
AccessibilityApi.gestureService = this
}
override fun onDestroy() {
super.onDestroy()
//must call
AccessibilityApi.gestureService = null
}
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
}
override fun onInterrupt() {
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/service/NotificationMonitorService.kt
================================================
package com.pengxh.autodingding.service
import android.app.Notification
import android.content.ComponentName
import android.os.Build
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import com.drake.channel.sendEvent
import com.pengxh.autodingding.BaseApplication
import com.pengxh.autodingding.bean.HistoryRecordBean
import com.pengxh.autodingding.greendao.HistoryRecordBeanDao
import com.pengxh.autodingding.ui.fragment.SettingsFragment
import com.pengxh.autodingding.utils.TimeOrDateUtil
import java.util.*
class NotificationMonitorService : NotificationListenerService() {
private var recordBeanDao: HistoryRecordBeanDao? = null
/**
* 有可用的并且和通知管理器连接成功时回调
*/
override fun onListenerConnected() {
recordBeanDao = BaseApplication.daoSession?.historyRecordBeanDao
}
/**
* 当有新通知到来时会回调
*/
override fun onNotificationPosted(sbn: StatusBarNotification) {
val extras = sbn.notification.extras
// 获取接收消息APP的包名
val packageName = sbn.packageName
// 获取接收消息的内容
val notificationText = extras.getString(Notification.EXTRA_TEXT)
if (packageName == "com.alibaba.android.rimet") {
if (notificationText == null || notificationText == "") {
return
}
if (notificationText.contains("考勤打卡")) {
//保存打卡记录
val bean = HistoryRecordBean()
bean.uuid = UUID.randomUUID().toString()
bean.date = TimeOrDateUtil.timestampToDate(System.currentTimeMillis())
bean.message = notificationText
recordBeanDao!!.save(bean)
//通知发送邮件和更新界面
sendEvent(notificationText)
}
}else if(packageName == "com.pengxh.autodingding"){
if (notificationText == null || notificationText == "") {
return
}
if(notificationText.contains("")){
}
}
}
/**
* 当有通知移除时会回调
*/
override fun onNotificationRemoved(sbn: StatusBarNotification) {}
override fun onListenerDisconnected() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// 通知侦听器断开连接 - 请求重新绑定
requestRebind(ComponentName(this, NotificationListenerService::class.java))
}
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/service/PushCoreService.kt
================================================
package com.pengxh.autodingding.service
import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.BatteryManager
import android.os.Build
import android.os.PowerManager
import android.util.Log
import cn.jpush.android.api.CustomMessage
import cn.jpush.android.api.JPushInterface
import cn.jpush.android.service.JPushMessageService
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.CacheDiskUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ToastUtils
import com.pengxh.autodingding.AndroidxBaseActivity
import com.pengxh.autodingding.actions.SwipeUnlockAction
import com.pengxh.autodingding.bean.BodyMsg
import com.pengxh.autodingding.bean.PushAudience
import com.pengxh.autodingding.bean.PushMessage
import com.pengxh.autodingding.net.RetrofitManager
import com.pengxh.autodingding.net.api.PushApi
import com.pengxh.autodingding.ui.MainActivity
import com.pengxh.autodingding.utils.SendMailUtil
import com.pengxh.autodingding.utils.Utils
import com.pengxh.autodingding.utils.launchWithExpHandler
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
class PushCoreService : JPushMessageService() {
override fun onMessage(context: Context, customMessage: CustomMessage) {
Log.d(TAG, customMessage.message)
val intent = Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val senderRegId = customMessage.title
if (MSG_MAIL_CHECK == customMessage.message) {
wakePhone(context)
unlockPhone(context){
intent.putExtra(MainActivity.EXTRA_ACTION, MainActivity.ACTION_SEND_MAIL)
context.startActivity(intent)
}
reply(senderRegId)
} else if (MSG_SIGN == customMessage.message) {
wakePhone(context)
unlockPhone(context){
intent.putExtra(MainActivity.EXTRA_ACTION, MainActivity.ACTION_LAUNCH_DING)
context.startActivity(intent)
}
} else if (MSG_STATUS_REPORT == customMessage.message){
val emailAddress = Utils.readEmailAddress()
val manager = context.getSystemService(AndroidxBaseActivity.BATTERY_SERVICE) as BatteryManager
val charging = manager.isCharging
val curBattery = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)///当前电量百分比
val regId = JPushInterface.getRegistrationID(context)
val screenLock = ScreenUtils.isScreenLock()
val androidAPI = Build.VERSION.SDK_INT
val manufacturer = Build.MANUFACTURER
val model = DeviceUtils.getModel()
val appInfo = AppUtils.getAppInfo()
val message = "注册ID: $regId ${if (screenLock) "是" else "未"}锁屏 " +
"当前${if (charging) "正在" else "未"}充电: 当前电量百分比:$curBattery %," +
"安卓版本:${androidAPI}, 厂商:${manufacturer},型号:${model}, 应用版本${appInfo.versionName}"
SendMailUtil.send(emailAddress, message)
} else if (MSG_SCREEN_SHOT == customMessage.message){
wakePhone(context)
unlockPhone(context){
intent.putExtra(MainActivity.EXTRA_ACTION, MainActivity.ACTION_SCREENSHOT)
context.startActivity(intent)
}
} else if (MSG_SLEEP == customMessage.message){
val ifLock = ScreenUtils.isScreenLock()
if (ifLock.not()){
//TODO turn off screen
}
} else if (MSG_MANUAL_SIGN == customMessage.message){
wakePhone(context)
unlockPhone(context){
intent.putExtra(MainActivity.EXTRA_ACTION, MainActivity.ACTION_MANUAL_SIGN)
context.startActivity(intent)
}
}
super.onMessage(context, customMessage)
}
@OptIn(DelicateCoroutinesApi::class)
private fun wakePhone(context: Context){
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
val screenOn = powerManager.isInteractive
if (!screenOn) {
//唤醒屏幕
Log.d(TAG, "screen off, now waking up phone")
val wakeLock = powerManager.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK,
"autoDing:bright"
)
wakeLock.acquire(10000)
launchWithExpHandler {
withContext(Dispatchers.IO){
delay(50000)
wakeLock.release()
}
}
}
}
private fun unlockPhone(context: Context, callback: (()->Unit)){
val keyGuardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
if (keyGuardManager.isKeyguardLocked){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.d("unlock", "8.0+ version dismiss function")
keyGuardManager.requestDismissKeyguard(ActivityUtils.getTopActivity(), object : KeyguardManager.KeyguardDismissCallback(){
override fun onDismissSucceeded() {
Log.d("unlock", "success")
callback.invoke()
}
override fun onDismissError() {
Log.d("unlock", "error")
ToastUtils.showShort("解锁错误")
val emailAddress = Utils.readEmailAddress()
SendMailUtil.send(emailAddress, "解锁手机异常,可能手机未设置锁屏显示,导致手机收到了消息但无法正常唤醒手机锁屏");
// launchWithExpHandler {
// SwipeUnlockAction().run(ActivityUtils.getTopActivity())
// delay(3000)
// callback.invoke()
// }
}
override fun onDismissCancelled() {
Log.d("unlock", "cancelled")
ToastUtils.showShort("解锁取消")
}
})
}else{
Log.d("unlock", "old version dismiss function")
keyGuardManager.newKeyguardLock("dismiss").disableKeyguard()
callback.invoke()
}
}else{
callback.invoke()
}
}
@OptIn(DelicateCoroutinesApi::class)
private fun reply(targetRegId:String){
launchWithExpHandler {
withContext(Dispatchers.IO){
val api = RetrofitManager.retrofitClient.create(PushApi::class.java)
val pushMessage = PushMessage()
pushMessage.audience = PushAudience().apply {
registration_id = mutableListOf(targetRegId)
}
pushMessage.message = BodyMsg().apply {
msg_content = MSG_REPLY
title = CacheDiskUtils.getInstance().getString("pushRegId")
}
api.pushMsg(pushMessage)
}
}
}
companion object {
private const val TAG = "MyReceiver"
const val MSG_MAIL_CHECK = "check"
const val MSG_SIGN = "sign"
const val MSG_STATUS_REPORT = "statusReport"
const val MSG_SCREEN_SHOT = "screenShot"
const val MSG_SLEEP = "goToSleep"
const val MSG_MANUAL_SIGN = "manualSign"
const val MSG_REPLY = "reply"
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/service/PushService.kt
================================================
package com.pengxh.autodingding.service
import cn.jpush.android.service.JCommonService
class PushService : JCommonService()
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/HistoryRecordActivity.kt
================================================
package com.pengxh.autodingding.ui
import android.os.CountDownTimer
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.view.View
import androidx.core.content.ContextCompat
import com.afollestad.materialdialogs.MaterialDialog
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.autodingding.AndroidxBaseActivity
import com.pengxh.autodingding.BaseApplication.Companion.daoSession
import com.pengxh.autodingding.R
import com.pengxh.autodingding.adapter.HistoryRecordAdapter
import com.pengxh.autodingding.bean.HistoryRecordBean
import com.pengxh.autodingding.databinding.ActivityHistoryBinding
import com.pengxh.autodingding.greendao.HistoryRecordBeanDao
import com.pengxh.autodingding.utils.ExcelUtils
import com.pengxh.autodingding.utils.StatusBarColorUtil
import com.pengxh.autodingding.utils.Utils
import com.pengxh.autodingding.widgets.EasyPopupWindow
import com.scwang.smartrefresh.layout.api.RefreshLayout
import java.io.File
import java.lang.ref.WeakReference
class HistoryRecordActivity : AndroidxBaseActivity(),
View.OnClickListener {
private var weakReferenceHandler: WeakReferenceHandler? = null
private lateinit var recordBeanDao: HistoryRecordBeanDao
private var dataBeans: MutableList = ArrayList()
private var isRefresh = false
private var historyAdapter: HistoryRecordAdapter? = null
override fun setupTopBarLayout() {
StatusBarColorUtil.setColor(this, ContextCompat.getColor(this, R.color.colorAppThemeLight))
ImmersionBar.with(this).statusBarDarkFont(false).init()
viewBinding!!.titleView.text = "打卡记录"
viewBinding!!.titleRightView.setOnClickListener(this)
}
public override fun initData() {
weakReferenceHandler = WeakReferenceHandler(this)
recordBeanDao = daoSession!!.historyRecordBeanDao
dataBeans = recordBeanDao.loadAll()
weakReferenceHandler!!.sendEmptyMessage(2022021403)
}
public override fun initEvent() {
viewBinding!!.refreshLayout.setOnRefreshListener { layout: RefreshLayout ->
isRefresh = true
object : CountDownTimer(1500, 500) {
override fun onTick(millisUntilFinished: Long) {}
override fun onFinish() {
dataBeans.clear()
dataBeans = recordBeanDao.loadAll()
layout.finishRefresh()
isRefresh = false
weakReferenceHandler!!.sendEmptyMessage(2022021403)
}
}.start()
}
viewBinding!!.refreshLayout.setEnableLoadMore(false)
}
private class WeakReferenceHandler(activity: HistoryRecordActivity) : Handler() {
private val reference: WeakReference
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
val activity = reference.get()
if (msg.what == 2022021403) {
if (activity!!.isRefresh) {
activity.historyAdapter!!.notifyDataSetChanged()
} else { //首次加载数据
if (activity.dataBeans.size == 0) {
activity.viewBinding!!.emptyView.visibility = View.VISIBLE
} else {
activity.viewBinding!!.emptyView.visibility = View.GONE
activity.historyAdapter = HistoryRecordAdapter(activity, activity.dataBeans)
activity.viewBinding!!.historyListView.adapter = activity.historyAdapter
}
}
}
}
init {
reference = WeakReference(activity)
}
}
override fun onClick(view: View) {
val easyPopupWindow = EasyPopupWindow(this, items)
easyPopupWindow.setPopupWindowClickListener(object: EasyPopupWindow.PopupWindowClickListener{
override fun popupWindowClick(position: Int) {
if (position == 0) {
//添加导出功能
if (dataBeans.size == 0) {
MaterialDialog(this@HistoryRecordActivity).show {
title(text = "温馨提示")
message(text = "空空如也,无法删除")
positiveButton()
}
} else {
MaterialDialog(this@HistoryRecordActivity).show {
title(text="清除")
message(text = "是否确定清除打卡记录?")
positiveButton{
recordBeanDao.deleteAll()
dataBeans.clear()
historyAdapter?.notifyDataSetChanged()
}
}
}
} else if (position == 1) {
val emailAddress = Utils.readEmailAddress()
if (emailAddress == "") {
ToastUtils.showShort("未设置邮箱,无法导出")
return
}
if (dataBeans.size == 0) {
ToastUtils.showShort("无打卡记录,无法导出")
return
}
MaterialDialog(this@HistoryRecordActivity).show {
title(text ="导出")
message(text= "导出到$emailAddress?")
positiveButton {
pullToEmail(dataBeans)
}
negativeButton()
}
}
}
})
easyPopupWindow.showAsDropDown(
viewBinding!!.titleRightView, viewBinding!!.titleRightView.width, SizeUtils.dp2px(10f)
)
}
private fun pullToEmail(historyBeans: List) {
//{"date":"2020-04-15","message":"考勤打卡:11:42 下班打卡 早退","uuid":"26btND0uLqU"},{"date":"2020-04-15","message":"考勤打卡:16:32 下班打卡 早退","uuid":"UTWQJzCfTl9"}
val dir = File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "DingRecord")
if (!dir.exists()) {
dir.mkdir()
}
ExcelUtils.initExcel("$dir/打卡记录表.xls", excelTitle)
val fileName = "$dir/打卡记录表.xls"
ExcelUtils.writeObjListToExcel(historyBeans, fileName)
}
companion object {
private val items = listOf("删除记录", "导出记录")
private val excelTitle:Array = arrayOf("uuid", "日期", "打卡信息")
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/MainActivity.kt
================================================
package com.pengxh.autodingding.ui
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.view.WindowManager
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.afollestad.materialdialogs.MaterialDialog
import com.blankj.utilcode.util.CacheDiskUtils
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.IntentUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.TimeUtils
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.autodingding.AndroidxBaseActivity
import com.pengxh.autodingding.R
import com.pengxh.autodingding.actions.DingSignAction
import com.pengxh.autodingding.adapter.FragAdapter
import com.pengxh.autodingding.databinding.ActivityMainBinding
import com.pengxh.autodingding.service.BaseAccessibilityService
import com.pengxh.autodingding.ui.fragment.AutoDingDingFragment
import com.pengxh.autodingding.ui.fragment.SettingsFragment
import com.pengxh.autodingding.utils.AccessibilityUtil
import com.pengxh.autodingding.utils.Constant
import com.pengxh.autodingding.utils.MailSender
import com.pengxh.autodingding.utils.SendMailUtil
import com.pengxh.autodingding.utils.SendMailUtil.createMail
import com.pengxh.autodingding.utils.SendMailUtil.send
import com.pengxh.autodingding.utils.StatusBarColorUtil
import com.pengxh.autodingding.utils.Utils
import com.pengxh.autodingding.utils.launchWithExpHandler
import com.pengxh.autodingding.utils.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
class MainActivity : AndroidxBaseActivity() {
private var menuItem: MenuItem? = null
private var actionJob: Job? = null
private val fragmentList: MutableList = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.window.addFlags(
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
)
}
override fun setupTopBarLayout() {
StatusBarColorUtil.setColor(this, ContextCompat.getColor(this, R.color.colorAppThemeLight))
ImmersionBar.with(this).statusBarDarkFont(false).init()
viewBinding!!.titleView.text = "远程启动钉钉"
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
execAction(intent)
}
override fun initData() {
execAction(intent)
fragmentList.add(AutoDingDingFragment())
fragmentList.add(SettingsFragment())
}
private fun execAction(intent: Intent) {
val action = intent.getStringExtra(EXTRA_ACTION)
if (ACTION_SEND_MAIL == action) {
val emailAddress = Utils.readEmailAddress()
Log.d("action", "sending email:$emailAddress")
val emailMessage =
"如果发送指令1分钟内收到,说明应用正常运行中。" + TimeUtils.getNowString()
send(emailAddress, emailMessage)
} else if (ACTION_LAUNCH_DING == action) {
try {
viewBinding!!.root.postDelayed({
Log.d("action", "trying to launch dingding")
startActivity(IntentUtils.getLaunchAppIntent(Constant.DINGDING))
}, 2000)
} catch (e: Exception) {
e.printStackTrace()
}
} else if (ACTION_SCREENSHOT == action) {
val emailAddress = Utils.readEmailAddress()
GlobalScope.launch(Dispatchers.IO) {
delay(2000)
val screenBitmap = ScreenUtils.screenShot(this@MainActivity, false)
val temp = filesDir.absolutePath + "screenShot${TimeUtils.getNowString()}.jpg"
ImageUtils.save(screenBitmap, temp, Bitmap.CompressFormat.JPEG)
val mailInfo = SendMailUtil.createAttachMail(
emailAddress, File(temp),
CacheDiskUtils.getInstance().getString("senderEmail", "lttclaw@qq.com"),
CacheDiskUtils.getInstance().getString("senderAuth", "hwpzapzrkmgpgaba")
)
LogUtils.d(
temp,
mailInfo.fromAddress,
mailInfo.toAddress,
mailInfo.attachFile?.absolutePath
)
MailSender().sendAccessoryMail(mailInfo)
}
} else if (ACTION_MANUAL_SIGN == action) {
val dingAction = DingSignAction()
if (actionJob?.isCompleted.let { it != null && !it }) {
toast("有正在运行的任务")
return
} else if (AccessibilityUtil.isServiceOn(
this,
BaseAccessibilityService::class.java.canonicalName ?: ""
).not()
) {
toast("未开启相应的辅助服务")
return
}
actionJob = launchWithExpHandler {
dingAction.run(this@MainActivity)
}
actionJob?.invokeOnCompletion {
toast("执行结束")
val emailAddress = Utils.readEmailAddress()
val emailMessage = dingAction.message.toString()
MailSender().sendTextMail(createMail(emailAddress, emailMessage))
}
}
}
public override fun initEvent() {
viewBinding!!.bottomNavigation.setOnItemSelectedListener { item: MenuItem ->
val itemId = item.itemId
if (itemId == R.id.nav_auto_sign) {
viewBinding!!.mViewPager.currentItem = 0
viewBinding!!.titleView.text = "定时打卡"
} else if (itemId == R.id.nav_settings) {
viewBinding!!.mViewPager.currentItem = 1
viewBinding!!.titleView.text = "设置"
}
false
}
val fragmentAdapter = FragAdapter(this, fragmentList)
viewBinding!!.mViewPager.adapter = fragmentAdapter
viewBinding!!.mViewPager.offscreenPageLimit = fragmentList.size
viewBinding!!.mViewPager.registerOnPageChangeCallback(object :
ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
if (menuItem != null) {
menuItem!!.isChecked = false
} else {
viewBinding!!.bottomNavigation.menu.getItem(0).isChecked = false
}
menuItem = viewBinding!!.bottomNavigation.menu.getItem(position)
menuItem!!.isChecked = true
}
})
if (!Utils.isAppAvailable(Constant.DINGDING)) {
MaterialDialog(this).show {
title(text = "温馨提醒")
message(text = "手机没有安装钉钉软件,无法自动打卡")
positiveButton(text = "退出") {
finish()
}
}
}
}
@Deprecated("Deprecated in Java", ReplaceWith("moveTaskToBack(false)"))
override fun onBackPressed() {
moveTaskToBack(false)
}
companion object {
const val EXTRA_ACTION = "action"
const val ACTION_SEND_MAIL = "sendMail"
const val ACTION_LAUNCH_DING = "launchDing"
const val ACTION_SCREENSHOT = "screenShot"
const val ACTION_MANUAL_SIGN = "manualSign"
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/WelcomeActivity.kt
================================================
package com.pengxh.autodingding.ui
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.ToastUtils
import com.pengxh.autodingding.utils.Constant
import com.pengxh.autodingding.utils.mainHandler
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.EasyPermissions.PermissionCallbacks
class WelcomeActivity : AppCompatActivity(), PermissionCallbacks {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startMainActivity()
}
private fun startMainActivity() {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
override fun onPermissionsGranted(requestCode: Int, perms: List) {
startMainActivity()
}
override fun onPermissionsDenied(requestCode: Int, perms: List) {
if (perms.size == Constant.USER_PERMISSIONS.size) { //授权全部失败,则提示用户
ToastUtils.showShort("授权失败")
mainHandler.postDelayed({ this@WelcomeActivity.finish() }, 1500)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//将请求结果传递EasyPermission库处理
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/fragment/AutoDingDingFragment.kt
================================================
package com.pengxh.autodingding.ui.fragment
import android.content.Intent
import android.graphics.Color
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import com.blankj.utilcode.util.ToastUtils
import com.drake.channel.receiveEvent
import com.jzxiang.pickerview.TimePickerDialog
import com.jzxiang.pickerview.data.Type
import com.pengxh.autodingding.AndroidxBaseFragment
import com.pengxh.autodingding.R
import com.pengxh.autodingding.databinding.FragmentDayBinding
import com.pengxh.autodingding.net.RetrofitManager
import com.pengxh.autodingding.net.api.WorkDayApi
import com.pengxh.autodingding.ui.WelcomeActivity
import com.pengxh.autodingding.utils.Constant
import com.pengxh.autodingding.utils.SendMailUtil
import com.pengxh.autodingding.utils.TimeOrDateUtil
import com.pengxh.autodingding.utils.Utils
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.Timer
import java.util.TimerTask
class AutoDingDingFragment : AndroidxBaseFragment(), View.OnClickListener {
private var amCountDownTimer: CountDownTimer? = null
private var pmCountDownTimer: CountDownTimer? = null
private var timer: Timer? = null
override fun setupTopBarLayout() {}
override fun initData() {
timer = Timer()
timer!!.schedule(object : TimerTask() {
override fun run() {
val systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis())
viewBinding!!.currentTime.post {
viewBinding?.currentTime?.text = systemTime
}
}
}, 0, 1000)
viewBinding!!.startLayoutView.setOnClickListener(this)
viewBinding!!.endLayoutView.setOnClickListener(this)
viewBinding!!.endAmDuty.setOnClickListener(this)
viewBinding!!.endPmDuty.setOnClickListener(this)
receiveEvent {
val intent = Intent(context, WelcomeActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context?.startActivity(intent)
val emailAddress = Utils.readEmailAddress()
if (emailAddress == "") {
Log.d("receive event", "邮箱地址为空")
ToastUtils.showShort("收件邮箱未设置")
} else {
if (it.isNotEmpty()){
SendMailUtil.send(emailAddress, it)
}
}
}
}
override fun initEvent() {}
override fun onClick(v: View) {
val id = v.id
if (id == R.id.startLayoutView) {
//设置上班时间
TimePickerDialog.Builder().setThemeColor(Color.BLUE)
.setWheelItemTextSize(15)
.setCyclic(false)
.setMinMillseconds(System.currentTimeMillis())
.setMaxMillseconds(System.currentTimeMillis() + Constant.ONE_WEEK)
.setType(Type.ALL)
.setCallBack { timePickerView: TimePickerDialog?, millSeconds: Long ->
viewBinding!!.amTime.text = TimeOrDateUtil.timestampToDate(millSeconds)
//计算时间差
onDuty(millSeconds)
}.build().show(childFragmentManager, "year_month_day_hour_minute")
} else if (id == R.id.endLayoutView) {
//设置下班时间
TimePickerDialog.Builder().setThemeColor(Color.BLUE)
.setWheelItemTextSize(15)
.setCyclic(false)
.setMinMillseconds(System.currentTimeMillis())
.setMaxMillseconds(System.currentTimeMillis() + Constant.ONE_WEEK)
.setType(Type.ALL)
.setCallBack { timePickerView: TimePickerDialog?, millSeconds: Long ->
viewBinding!!.pmTime.text = TimeOrDateUtil.timestampToDate(millSeconds)
//计算时间差
offDuty(millSeconds)
}.build().show(childFragmentManager, "year_month_day_hour_minute")
} else if (id == R.id.endAmDuty) {
if (amCountDownTimer != null) {
amCountDownTimer!!.cancel()
viewBinding!!.startTimeView.text = "--"
}
} else if (id == R.id.endPmDuty) {
if (pmCountDownTimer != null) {
pmCountDownTimer!!.cancel()
viewBinding!!.endTimeView.text = "--"
}
}
}
private fun onDuty(millSeconds: Long) {
val deltaTime = TimeOrDateUtil.deltaTime(millSeconds / 1000)
if (deltaTime == 0L) {
return
}
viewBinding!!.amTime.text = TimeOrDateUtil.timestampToDate(millSeconds)
//显示倒计时
val text = viewBinding!!.startTimeView.text.toString()
if (text == "--") {
amCountDownTimer = object : CountDownTimer(deltaTime * 1000, 1000) {
override fun onTick(l: Long) {
viewBinding!!.startTimeView.text = (l / 1000).toInt().toString()
}
override fun onFinish() {
viewBinding!!.startTimeView.text = "--"
Utils.openDingDing(Constant.DINGDING)
setNextPeriod(millSeconds){
onDuty(it)
}
}
}
(amCountDownTimer as CountDownTimer).start()
} else {
ToastUtils.showShort("已有任务在进行中")
}
}
private fun offDuty(millSeconds: Long) {
val deltaTime = TimeOrDateUtil.deltaTime(millSeconds / 1000)
if (deltaTime == 0L) {
return
}
viewBinding!!.pmTime.text = TimeOrDateUtil.timestampToDate(millSeconds)
//显示倒计时
val text = viewBinding!!.endTimeView.text.toString()
if (text == "--") {
pmCountDownTimer = object : CountDownTimer(deltaTime * 1000, 1000) {
override fun onTick(l: Long) {
viewBinding!!.endTimeView.text = (l / 1000).toInt().toString()
}
override fun onFinish() {
viewBinding!!.endTimeView.text = "--"
Utils.openDingDing(Constant.DINGDING)
setNextPeriod(millSeconds){
offDuty(it)
}
}
}
(pmCountDownTimer as CountDownTimer).start()
} else {
ToastUtils.showShort("已有任务在进行中")
}
}
@OptIn(DelicateCoroutinesApi::class)
private fun setNextPeriod(millSeconds: Long, block: (timeStamp:Long)->Unit){
val retrofit = RetrofitManager.workdayClient
val api = retrofit.create(WorkDayApi::class.java)
GlobalScope.launch(Dispatchers.Main) {
val nextWorkdayCal = withContext(Dispatchers.IO){
val resp = api.getNextWorkday()
resp.workday?.date?.let {
val curCal = Calendar.getInstance()
curCal.timeInMillis = millSeconds
val df = SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE)
val nextWorkdayCal = Calendar.getInstance()
nextWorkdayCal.time = df.parse(it)!!
nextWorkdayCal.set(Calendar.HOUR_OF_DAY, curCal.get(Calendar.HOUR_OF_DAY))
nextWorkdayCal.set(Calendar.MINUTE, curCal.get(Calendar.MINUTE))
nextWorkdayCal.set(Calendar.SECOND, curCal.get(Calendar.SECOND))
nextWorkdayCal
}
}
if (nextWorkdayCal != null) {
block.invoke(nextWorkdayCal.timeInMillis)
}
}
}
override fun onDestroyView() {
if (timer != null) {
timer!!.cancel()
}
super.onDestroyView()
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/fragment/MailConfFragment.kt
================================================
package com.pengxh.autodingding.ui.fragment
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.CacheDiskUtils
import com.blankj.utilcode.util.ToastUtils
import com.pengxh.autodingding.databinding.FragmentMailConfBinding
import com.pengxh.autodingding.utils.Utils
class MailConfFragment :Fragment() {
private var fragmentProvider: ViewModelProvider? = null
private lateinit var binding: FragmentMailConfBinding
private var configTested = false
private lateinit var vm: MailConfVM
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentMailConfBinding.inflate(inflater, container, false);
return binding.root
}
override fun onAttach(context: Context) {
super.onAttach(context)
vm = getFragmentViewModel(MailConfVM::class.java)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val savedFromAddress = CacheDiskUtils.getInstance().getString("senderEmail", "lttclaw@qq.com")
val savedFromAuth = CacheDiskUtils.getInstance().getString("senderAuth", "hwpzapzrkmgpgaba")
val savedToAddress = Utils.readEmailAddress()
binding.etSenderEmailAddress.setText(savedFromAddress)
binding.etSenderEmailAuth.setText(savedFromAuth)
binding.etReceiverEmailAddress.setText(savedToAddress)
binding.btnCheck.setOnClickListener {
val fromAddress = binding.etSenderEmailAddress.text.toString()
val fromAuth = binding.etSenderEmailAuth.text.toString()
val toAddress = binding.etReceiverEmailAddress.text.toString()
if(fromAddress.isEmpty() || fromAuth.isEmpty() || toAddress.isEmpty()){
ToastUtils.showShort("配置选项缺失!")
}else{
vm.sendMail(fromAddress, fromAuth, toAddress)
configTested = true
ToastUtils.showShort("已尝试发送邮件")
}
}
binding.btnSave.setOnClickListener {
val fromAddress = binding.etSenderEmailAddress.text.toString()
val fromAuth = binding.etSenderEmailAuth.text.toString()
val toAddress = binding.etReceiverEmailAddress.text.toString()
if(configTested){
CacheDiskUtils.getInstance().put("senderEmail" , fromAddress)
CacheDiskUtils.getInstance().put("senderAuth", fromAuth)
Utils.saveEmailAddress(toAddress)
ToastUtils.showShort("保存配置成功")
}else{
ToastUtils.showShort("请先进行配置测试")
}
}
binding.ivBack.setOnClickListener {
parentFragmentManager.beginTransaction()
.hide(this)
.commit()
}
}
private fun getFragmentViewModel(modelClass: Class): T {
if (fragmentProvider == null) {
fragmentProvider = ViewModelProvider(this)
}
return fragmentProvider!![modelClass]
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/fragment/MailConfVM.kt
================================================
package com.pengxh.autodingding.ui.fragment
import com.pengxh.autodingding.base.BaseViewModel
import com.pengxh.autodingding.utils.MailSender
import com.pengxh.autodingding.utils.SendMailUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class MailConfVM : BaseViewModel() {
fun sendMail(fromEmail: String, fromAuth: String, toEmail: String) = launch {
withContext(Dispatchers.IO) {
MailSender().sendTextMail(
SendMailUtil.createMail(
toEmail,
"测试邮件",
fromEmail,
fromAuth
)
)
}
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/fragment/PermissionFragment.kt
================================================
package com.pengxh.autodingding.ui.fragment
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import com.blankj.utilcode.util.IntentUtils
import com.pengxh.autodingding.R
import com.pengxh.autodingding.base.BaseVmFragment
import com.pengxh.autodingding.databinding.PermissionFragmentBinding
import com.pengxh.autodingding.service.BaseAccessibilityService
import com.pengxh.autodingding.utils.AccessibilityUtil
import com.pengxh.autodingding.utils.RomUtils
import com.pengxh.autodingding.utils.clickNoRepeat
class PermissionFragment : BaseVmFragment() {
private lateinit var viewModel: PermissionVM
override fun getLayoutId() = R.layout.permission_fragment
override fun init(savedInstanceState: Bundle?) {
initView()
}
override fun initViewModel() {
viewModel = getFragmentViewModel(PermissionVM::class.java)
}
override fun initView() {
binding.vm = viewModel
}
override fun onClick() {
binding.ivBack.setOnClickListener {
parentFragmentManager.beginTransaction()
.hide(this)
.commit()
}
binding.rlAccessibility.clickNoRepeat {
val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
activity?.startActivity(intent)
}
binding.rlBgStart.clickNoRepeat {
activity?.startActivity(IntentUtils.getLaunchAppDetailsSettingsIntent(context?.packageName))
}
}
override fun onStart() {
super.onStart()
viewModel.bgStartEnable.set(RomUtils.isBackgroundStartAllowed(requireContext()))
viewModel.accessibilityEnable.set(AccessibilityUtil.isServiceOn(requireContext(),
BaseAccessibilityService::class.java.canonicalName?:""))
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/fragment/PermissionVM.kt
================================================
package com.pengxh.autodingding.ui.fragment
import androidx.databinding.ObservableBoolean
import com.pengxh.autodingding.base.BaseViewModel
class PermissionVM : BaseViewModel() {
val accessibilityEnable = ObservableBoolean()
val bgStartEnable = ObservableBoolean()
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/fragment/PushFragment.kt
================================================
package com.pengxh.autodingding.ui.fragment
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.CacheDiskUtils
import com.blankj.utilcode.util.ToastUtils
import com.pengxh.autodingding.databinding.FragmentPushBinding
import com.pengxh.autodingding.utils.clickNoRepeat
open class PushFragment : Fragment() {
private var fragmentProvider: ViewModelProvider? = null
private var binding: FragmentPushBinding? = null
private lateinit var pushVM: PushVM
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentPushBinding.inflate(inflater, container, false)
return binding!!.root
}
override fun onAttach(context: Context) {
super.onAttach(context)
pushVM = getFragmentViewModel(PushVM::class.java)
}
@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pushVM.pushResult.observe(viewLifecycleOwner){
if (it.errorCode == 0){
ToastUtils.showShort("指令下发成功")
saveRegId()
}else{
ToastUtils.showShort(it.messageCn)
}
}
val savedRegId = CacheDiskUtils.getInstance().getString("regId")
if (savedRegId != null){
binding!!.etTargetRegId.setText(savedRegId)
}
binding!!.ivBack.setOnClickListener {
parentFragmentManager.beginTransaction()
.hide(this)
.commit()
}
binding!!.btnCheck.setOnClickListener {
if (binding!!.etTargetRegId.text.toString() == "") {
ToastUtils.showShort("注册id必须填写")
}else {
pushVM.pushCheck(binding!!.etTargetRegId.text.toString())
}
}
binding!!.btnPush.setOnClickListener {
if (binding!!.etTargetRegId.text.toString() == "") {
ToastUtils.showShort("注册id必须填写")
}else {
pushVM.pushSign(binding!!.etTargetRegId.text.toString())
}
}
binding!!.btnStatus.setOnClickListener {
if (binding!!.etTargetRegId.text.toString() == "") {
ToastUtils.showShort("注册id必须填写")
} else {
pushVM.pushStatusFetch(binding!!.etTargetRegId.text.toString())
}
}
binding!!.btnScreenShot.setOnClickListener {
if (binding!!.etTargetRegId.text.toString() == "") {
ToastUtils.showShort("注册id必须填写")
} else {
pushVM.pushScreenShot(binding!!.etTargetRegId.text.toString())
}
}
binding!!.btnManualSign.clickNoRepeat(1000) {
if (binding!!.etTargetRegId.text.toString() == "") {
ToastUtils.showShort("注册id必须填写")
} else {
pushVM.pushManualSign(binding!!.etTargetRegId.text.toString())
}
}
}
private fun getFragmentViewModel(modelClass: Class): T {
if (fragmentProvider == null) {
fragmentProvider = ViewModelProvider(this)
}
return fragmentProvider!![modelClass]
}
private fun saveRegId(){
val curRegId = binding!!.etTargetRegId.text.toString()
CacheDiskUtils.getInstance().put("regId", curRegId)
}
companion object {
@JvmStatic
fun newInstance(): PushFragment {
return PushFragment()
}
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/fragment/PushVM.kt
================================================
package com.pengxh.autodingding.ui.fragment
import androidx.lifecycle.MutableLiveData
import cn.jpush.android.api.JPushInterface
import com.blankj.utilcode.util.CacheDiskUtils
import com.pengxh.autodingding.base.BaseViewModel
import com.pengxh.autodingding.bean.BodyMsg
import com.pengxh.autodingding.bean.PushAudience
import com.pengxh.autodingding.bean.PushMessage
import com.pengxh.autodingding.bean.PushResp
import com.pengxh.autodingding.net.RetrofitManager
import com.pengxh.autodingding.net.api.PushApi
import com.pengxh.autodingding.service.PushCoreService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class PushVM: BaseViewModel() {
val pushResult = MutableLiveData()
fun pushCheck(regId:String) {
pushCmd(regId, PushCoreService.MSG_MAIL_CHECK)
}
fun pushSign(regId:String) {
pushCmd(regId, PushCoreService.MSG_SIGN)
}
fun pushStatusFetch(regId: String){
pushCmd(regId, PushCoreService.MSG_STATUS_REPORT)
}
fun pushScreenShot(regId: String){
pushCmd(regId, PushCoreService.MSG_SCREEN_SHOT)
}
fun pushManualSign(regId: String){
pushCmd(regId, PushCoreService.MSG_MANUAL_SIGN)
}
private fun pushCmd(regId: String, cmd: String) = launch {
pushResult.value = withContext(Dispatchers.IO){
val api = RetrofitManager.retrofitClient.create(PushApi::class.java)
val pushMessage = PushMessage()
pushMessage.audience = PushAudience().apply {
registration_id = mutableListOf(regId)
}
pushMessage.message = BodyMsg().apply {
msg_content = cmd
title = CacheDiskUtils.getInstance().getString("pushRegId")
}
api.pushMsg(pushMessage)
}
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/fragment/RemoteSignFragment.kt
================================================
package com.pengxh.autodingding.ui.fragment
import com.pengxh.autodingding.AndroidxBaseFragment
import com.pengxh.autodingding.databinding.FragmentRemoteSignBinding
class RemoteSignFragment: AndroidxBaseFragment() {
override fun setupTopBarLayout() {
}
override fun initData() {
// check if is master or slave first, then lis
}
override fun initEvent() {
TODO("Not yet implemented")
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/ui/fragment/SettingsFragment.kt
================================================
package com.pengxh.autodingding.ui.fragment
import android.content.*
import android.content.pm.PackageManager
import android.provider.Settings
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.core.app.NotificationManagerCompat
import cn.jpush.android.api.JPushInterface
import com.blankj.utilcode.util.CacheDiskUtils
import com.blankj.utilcode.util.IntentUtils
import com.blankj.utilcode.util.ToastUtils
import com.pengxh.autodingding.AndroidxBaseFragment
import com.pengxh.autodingding.BaseApplication.Companion.daoSession
import com.pengxh.autodingding.BuildConfig
import com.pengxh.autodingding.R
import com.pengxh.autodingding.actions.DingSignAction
import com.pengxh.autodingding.databinding.FragmentSettingsBinding
import com.pengxh.autodingding.service.NotificationMonitorService
import com.pengxh.autodingding.ui.HistoryRecordActivity
import com.pengxh.autodingding.ui.fragment.PushFragment.Companion.newInstance
import com.pengxh.autodingding.utils.Constant
import com.pengxh.autodingding.utils.Utils
import com.pengxh.autodingding.utils.launchWithExpHandler
import com.pengxh.autodingding.utils.toast
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Job
class SettingsFragment : AndroidxBaseFragment(), View.OnClickListener {
private var actionJob: Job? = null
override fun initData() {
val historyBeanDao = daoSession!!.historyRecordBeanDao
val emailAddress = Utils.readEmailAddress()
if (emailAddress != "") {
viewBinding!!.emailTextView.text = emailAddress
}
viewBinding!!.recordSize.text = historyBeanDao.loadAll().size.toString()
viewBinding!!.appVersion.text = BuildConfig.VERSION_NAME
val savedRegId = CacheDiskUtils.getInstance().getString("regId")
if (savedRegId != null) viewBinding!!.pushTextView.text = savedRegId
}
private val settingsLauncher =
registerForActivityResult(StartActivityForResult()) {
if (isNotificationEnable) {
startNotificationMonitorService()
}
}
//检测通知监听服务是否被授权
private val isNotificationEnable: Boolean
get() {
val packageNames =
NotificationManagerCompat.getEnabledListenerPackages(requireContext())
return packageNames.contains(context?.packageName)
}
override fun initEvent() {
if (!isNotificationEnable) {
try {
//打开通知监听设置页面
val intent = Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
settingsLauncher.launch(intent)
} catch (e: Exception) {
e.printStackTrace()
}
} else {
startNotificationMonitorService()
}
viewBinding!!.tvRegValue.text = JPushInterface.getRegistrationID(context)
viewBinding!!.btnCopy.setOnClickListener(this)
viewBinding!!.btnTestLaunchDing.setOnClickListener(this)
viewBinding!!.emailLayout.setOnClickListener(this)
viewBinding!!.historyLayout.setOnClickListener(this)
viewBinding!!.introduceLayout.setOnClickListener(this)
viewBinding!!.pushLayout.setOnClickListener(this)
viewBinding!!.testLayout.setOnClickListener(this)
viewBinding!!.rlVersion.setOnClickListener(this)
viewBinding!!.permissionLayout.setOnClickListener(this)
}
//切换通知监听器服务
private fun startNotificationMonitorService() {
//创建常住通知栏
Utils.createNotification()
val pm = requireContext().packageManager
pm.setComponentEnabledSetting(
ComponentName(requireContext(), NotificationMonitorService::class.java),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP
)
pm.setComponentEnabledSetting(
ComponentName(requireContext(), NotificationMonitorService::class.java),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP
)
viewBinding!!.noticeCheckBox.isChecked = isNotificationEnable
}
@OptIn(DelicateCoroutinesApi::class)
override fun onClick(v: View) {
when (v.id) {
R.id.emailLayout -> {
parentFragmentManager
.beginTransaction()
.add(R.id.fragmentContainer, MailConfFragment())
.commit()
}
R.id.historyLayout -> {
startActivity(Intent(context, HistoryRecordActivity::class.java))
}
R.id.introduceLayout -> {
Utils.showAlertDialog(
activity,
"功能介绍",
context?.getString(R.string.about),
"看完了",
true
)
}
R.id.btnCopy -> {
val clipboardManager = context
?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboardManager.setPrimaryClip(
ClipData.newPlainText(
null,
JPushInterface.getRegistrationID(context)
)
)
ToastUtils.showShort("已复制")
}
R.id.btnTestLaunchDing -> {
activity?.startActivity(IntentUtils.getLaunchAppIntent(Constant.DINGDING))
}
R.id.pushLayout -> {
parentFragmentManager
.beginTransaction()
.replace(R.id.fragmentContainer, newInstance())
.commit()
}
R.id.rlVersion -> {
// undone
}
R.id.testLayout -> {
val action = DingSignAction()
if (actionJob?.isCompleted.let { it != null && !it }) {
toast("有正在运行的任务")
return
}
actionJob = launchWithExpHandler {
activity?.let { action.run(it) }
}
actionJob?.invokeOnCompletion {
Utils.showAlertDialog(activity, "执行日志", action.message.toString(),
"确定", true)
}
}
R.id.permissionLayout -> {
parentFragmentManager
.beginTransaction()
.replace(R.id.fragmentContainer, PermissionFragment())
.commit()
}
}
}
override fun setupTopBarLayout() {
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/AccessibilityUtil.kt
================================================
package com.pengxh.autodingding.utils
import android.content.Context
import android.provider.Settings
import android.text.TextUtils.SimpleStringSplitter
import android.util.Log
import android.view.accessibility.AccessibilityManager
object AccessibilityUtil {
fun isServiceOn(context: Context, serviceName: String): Boolean{
val am = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
if (am.isEnabled){
val fullAccName = "${context.packageName}/${serviceName}"
return isAccessibilitySettingsOn(context, fullAccName)
}
return false
}
private fun isAccessibilitySettingsOn(context: Context, service: String): Boolean {
Log.d("param service name", service)
val mStringColonSplitter = SimpleStringSplitter(':')
val settingValue: String = Settings.Secure.getString(
context.applicationContext.contentResolver,
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
)
mStringColonSplitter.setString(settingValue)
while (mStringColonSplitter.hasNext()) {
val accessibilityService = mStringColonSplitter.next()
Log.d("accessibility services", accessibilityService)
if (accessibilityService.equals(service, ignoreCase = true)) {
return true
}
}
return false
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/Constant.java
================================================
package com.pengxh.autodingding.utils;
import android.Manifest;
import com.pengxh.autodingding.R;
public class Constant {
public static final int PERMISSIONS_CODE = 999;
public static final String[] USER_PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE};
//钉钉包名:com.alibaba.android.rimet
//打卡页面类名:com.alibaba.lightapp.runtime.activity.CommonWebViewActivity
public static final String DINGDING = "com.alibaba.android.rimet";
public static final int[] images = {R.mipmap.delete, R.mipmap.output};
public static final long ONE_WEEK = 5 * 24 * 60 * 60 * 1000L;
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/EmailAuthenticator.kt
================================================
package com.pengxh.autodingding.utils
import javax.mail.Authenticator
import javax.mail.PasswordAuthentication
class EmailAuthenticator(private val userName: String, private val password: String) :
Authenticator() {
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(userName, password)
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/ExcelUtils.kt
================================================
package com.pengxh.autodingding.utils
import android.util.Log
import com.blankj.utilcode.util.ToastUtils
import com.pengxh.autodingding.bean.HistoryRecordBean
import com.pengxh.autodingding.utils.SendMailUtil.sendAttachFileEmail
import jxl.Workbook
import jxl.WorkbookSettings
import jxl.format.Alignment
import jxl.format.Border
import jxl.format.BorderLineStyle
import jxl.format.Colour
import jxl.write.*
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
object ExcelUtils {
private const val TAG = "ExcelUtils"
private var arial14format: WritableCellFormat? = null
private var arial10format: WritableCellFormat? = null
private var arial12format: WritableCellFormat? = null
private const val UTF8_ENCODING = "UTF-8"
/**
* 初始化Excel
*
* @param fileName
* @param colName
*/
fun initExcel(fileName: String?, colName: Array) {
format()
var workbook: WritableWorkbook? = null
try {
val file = File(fileName)
if (!file.exists()) {
file.createNewFile()
}
workbook = Workbook.createWorkbook(file)
val sheet = workbook.createSheet("打卡记录表", 0)
//创建标题栏
sheet.addCell(Label(0, 0, fileName, arial14format))
for (col in colName.indices) {
sheet.addCell(Label(col, 0, colName[col], arial10format))
}
sheet.setRowView(0, 340) //设置行高
workbook.write()
} catch (e: Exception) {
e.printStackTrace()
} finally {
if (workbook != null) {
try {
workbook.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
/**
* 单元格的格式设置 字体大小 颜色 对齐方式、背景颜色等...
*/
private fun format() {
try {
val arial14font = WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD)
arial14font.colour = Colour.LIGHT_BLUE
arial14format = WritableCellFormat(arial14font)
arial14format!!.alignment = Alignment.CENTRE
arial14format!!.setBorder(Border.ALL, BorderLineStyle.THIN)
arial14format!!.setBackground(Colour.VERY_LIGHT_YELLOW)
arial10format =
WritableCellFormat(WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD))
arial10format!!.alignment = Alignment.CENTRE
arial10format!!.setBorder(Border.ALL, BorderLineStyle.THIN)
arial10format!!.setBackground(Colour.GRAY_25)
arial12format = WritableCellFormat(WritableFont(WritableFont.ARIAL, 10))
arial10format!!.alignment = Alignment.CENTRE //对齐格式
arial12format!!.setBorder(Border.ALL, BorderLineStyle.THIN) //设置边框
} catch (e: WriteException) {
e.printStackTrace()
}
}
fun writeObjListToExcel(objList: List?, fileName: String?) {
if (objList != null && objList.size > 0) {
var writebook: WritableWorkbook? = null
var `in`: InputStream? = null
try {
val setEncode = WorkbookSettings()
setEncode.encoding = UTF8_ENCODING
`in` = FileInputStream(File(fileName))
val workbook = Workbook.getWorkbook(`in`)
writebook = Workbook.createWorkbook(File(fileName), workbook)
val sheet = writebook.getSheet(0)
for (j in objList.indices) {
val historyBean = objList[j]
val uuid = historyBean.uuid
val date = historyBean.date
val message = historyBean.message
//第一行留作表头
sheet.addCell(Label(0, j + 1, uuid, arial12format))
sheet.addCell(Label(1, j + 1, date, arial12format))
sheet.addCell(Label(2, j + 1, message, arial12format))
sheet.setRowView(j + 1, 350) //设置行高
}
writebook.write()
Log.d(TAG, "writeObjListToExcel: 导出表格到本地成功")
//然后发送邮件到指定邮箱
val emailAddress = Utils.readEmailAddress()
if (emailAddress == "") {
ToastUtils.showLong("邮箱未填写,无法导出")
return
}
sendAttachFileEmail(emailAddress, fileName)
} catch (e: Exception) {
e.printStackTrace()
} finally {
if (writebook != null) {
try {
writebook.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
if (`in` != null) {
try {
`in`.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/KtUtils.kt
================================================
package com.pengxh.autodingding.utils
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import com.pengxh.autodingding.BaseApplication
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
@DelicateCoroutinesApi
fun launchWithExpHandler(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
) = GlobalScope.launch(context + ExceptionHandler, start, block)
val ExceptionHandler by lazy {
CoroutineExceptionHandler { _, throwable ->
toast(throwable.message ?: "$throwable")
throwable.printStackTrace()
}
}
val mainHandler by lazy {
Handler(Looper.getMainLooper())
}
fun runOnUi(block: () -> Unit) {
if (Looper.getMainLooper() == Looper.myLooper()) {
block()
} else {
mainHandler.post(block)
}
}
fun toast(m: String) =
runOnUi {
Toast.makeText(BaseApplication.application, m, Toast.LENGTH_SHORT).show()
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/MailSender.kt
================================================
package com.pengxh.autodingding.utils
import android.util.Log
import com.blankj.utilcode.util.ToastUtils
import com.pengxh.autodingding.bean.MailInfo
import java.util.*
import javax.activation.DataHandler
import javax.activation.DataSource
import javax.activation.FileDataSource
import javax.mail.*
import javax.mail.internet.*
class MailSender {
/**
* 以文本格式发送邮件
* @param mailInfo 待发送的邮件的信息
*/
@Throws(MessagingException::class)
fun sendTextMail(mailInfo: MailInfo) {
// 判断是否需要身份认证
var authenticator: EmailAuthenticator? = null
val pro = mailInfo.properties
if (mailInfo.isValidate) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = EmailAuthenticator(mailInfo.userName ?: "", mailInfo.password ?: "")
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
val sendMailSession = Session.getInstance(pro, authenticator)
// 根据session创建一个邮件消息
val mailMessage: Message = MimeMessage(sendMailSession)
// 创建邮件发送者地址
val from: Address = InternetAddress(mailInfo.fromAddress)
// 设置邮件消息的发送者
mailMessage.setFrom(from)
// 创建邮件的接收者地址,并设置到邮件消息中
val to: Address = InternetAddress(mailInfo.toAddress)
mailMessage.setRecipient(Message.RecipientType.TO, to)
// 设置邮件消息的主题
val mailSubject = mailInfo.subject
mailMessage.subject = mailSubject
// 设置邮件消息发送的时间
mailMessage.sentDate = Date()
// 设置邮件消息的主要内容
val mailContent = mailInfo.content
mailMessage.setText(mailContent)
// 发送邮件
Transport.send(mailMessage)
}
// 发送带附件的邮件
fun sendAccessoryMail(mailInfo: MailInfo): Boolean {
Log.d("MailSender", "sendAccessoryMail: 发送带附件的邮件")
// 判断是否需要身份验证
var authenticator: EmailAuthenticator? = null
val p = mailInfo.properties
// 如果需要身份验证,则创建一个密码验证器
if (mailInfo.isValidate) {
authenticator = EmailAuthenticator(mailInfo.userName ?: "", mailInfo.password ?: "")
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
val sendMailSession = Session.getInstance(p, authenticator)
try {
// 根据session创建一个邮件消息
val mailMessage: Message = MimeMessage(sendMailSession)
// 创建邮件发送者的地址
val fromAddress: Address = InternetAddress(mailInfo.fromAddress)
// 设置邮件消息的发送者
mailMessage.setFrom(fromAddress)
// 创建邮件接收者的地址
val toAddress: Address = InternetAddress(mailInfo.toAddress)
// 设置邮件消息的接收者
mailMessage.setRecipient(Message.RecipientType.TO, toAddress)
// 设置邮件消息的主题
mailMessage.subject = mailInfo.subject
// 设置邮件消息的发送时间
mailMessage.sentDate = Date()
// MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
val mainPart: Multipart = MimeMultipart()
val file = mailInfo.attachFile!!
if (!file.exists()) {
ToastUtils.showShort("需要导出的表格不存在,请重试")
return false
} else {
// 创建一个MimeBodyPart来包含附件
val bodyPart: BodyPart = MimeBodyPart()
val source: DataSource = FileDataSource(file)
bodyPart.dataHandler = DataHandler(source)
bodyPart.fileName = MimeUtility.encodeWord(file.name)
mainPart.addBodyPart(bodyPart)
}
// 将MimeMultipart对象设置为邮件内容
mailMessage.setContent(mainPart)
// 发送邮件
Transport.send(mailMessage)
return true
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/Param.java
================================================
package com.pengxh.autodingding.utils;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* des 参数解析注解
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Param {
String value() default "";
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/ParamUtil.kt
================================================
package com.pengxh.autodingding.utils
import android.app.Activity
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import androidx.fragment.app.Fragment
/**
* 页面跳转传参 注解+反射获取页面入参
*/
object ParamUtil {
/**
* Fragment
*/
fun initParam(fragment: Fragment) {
val javaClass = fragment.javaClass
fragment.arguments?.apply {
setParam(fragment, this)
}
}
/**
* Activity
*/
fun initParam(activity: Activity) {
activity.intent.extras?.apply {
setParam(activity, this)
}
}
private fun setParam(obj: Any, intent: Bundle) {
val javaClass = obj.javaClass
val fields = javaClass.declaredFields
for (item in fields) {
if (item.isAnnotationPresent(Param::class.java)) {
item.getAnnotation(Param::class.java)?.let {
val key: String = if (TextUtils.isEmpty(it.value)) item.name else it.value
if (intent.containsKey(key)) {
val type = item.type
when (type) {
Boolean::class.javaPrimitiveType -> {
intent.getBoolean(key, false)
}
Int::class.javaPrimitiveType -> {
intent.getInt(key, 0)
}
Long::class.javaPrimitiveType -> {
intent.getLong(key, 0L)
}
String::class.java -> {
intent.getString(key)
}
Double::class.javaPrimitiveType -> {
intent.getDouble(key, 0.0)
}
Byte::class.javaPrimitiveType -> {
intent.getByte(key, "".toByte())
}
Char::class.javaPrimitiveType -> {
intent.getChar(key, '\u0000')
}
Float::class.javaPrimitiveType -> {
intent.getFloat(key, 0f)
}
else -> {
if((type as Class).interfaces.asList().contains(Parcelable::class.java)){
intent.getParcelable(key)
}else{
intent.getSerializable(key)
}
}
}?.apply {
item.isAccessible = true
try {
item[obj] = this
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
item.isAccessible = false
}
}
}
}
}
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/RomUtils.kt
================================================
package com.pengxh.autodingding.utils
import android.annotation.SuppressLint
import android.app.AppOpsManager
import android.content.Context
import android.net.Uri
import android.os.Build
import android.provider.Settings
import java.lang.reflect.Method
object RomUtils {
private val TAG = RomUtils::class.java.simpleName
private fun isXiaoMi(): Boolean {
return checkManufacturer("xiaomi")
}
private fun isOppo(): Boolean {
return checkManufacturer("oppo")
}
private fun isVivo(): Boolean {
return checkManufacturer("vivo")
}
private fun checkManufacturer(manufacturer: String): Boolean {
return manufacturer.equals(Build.MANUFACTURER, true)
}
fun isBackgroundStartAllowed(context: Context): Boolean {
if (isXiaoMi()) {
return isXiaomiBgStartPermissionAllowed(context)
}
if (isVivo()) {
return isVivoBgStartPermissionAllowed(context)
}
if (isOppo() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return Settings.canDrawOverlays(context)
}
return true
}
private fun isXiaomiBgStartPermissionAllowed(context: Context): Boolean {
val ops = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
try {
val op = 10021
val method: Method = ops.javaClass.getMethod("checkOpNoThrow", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, String::class.java)
val result = method.invoke(ops, op, android.os.Process.myUid(), context.packageName) as Int
return result == AppOpsManager.MODE_ALLOWED
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
private fun isVivoBgStartPermissionAllowed(context: Context): Boolean {
return getVivoBgStartPermissionStatus(context) == 0
}
/**
* 判断Vivo后台弹出界面状态, 1无权限,0有权限
* @param context context
*/
@SuppressLint("Range")
private fun getVivoBgStartPermissionStatus(context: Context): Int {
val uri: Uri = Uri.parse("content://com.vivo.permissionmanager.provider.permission/start_bg_activity")
val selection = "pkgname = ?"
val selectionArgs = arrayOf(context.packageName)
var state = 1
try {
context.contentResolver.query(uri, null, selection, selectionArgs, null)?.use {
if (it.moveToFirst()) {
state = it.getInt(it.getColumnIndex("currentstate"))
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return state
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/SendMailUtil.kt
================================================
package com.pengxh.autodingding.utils
import com.blankj.utilcode.util.CacheDiskUtils
import com.blankj.utilcode.util.ToastUtils
import com.pengxh.autodingding.bean.MailInfo
import java.io.File
object SendMailUtil {
fun send(
toAddress: String?, emailMessage: String
) {
Thread {
MailSender().sendTextMail(
createMail(
toAddress,
emailMessage,
CacheDiskUtils.getInstance().getString("senderEmail", "lttclaw@qq.com"),
CacheDiskUtils.getInstance().getString("senderAuth", "hwpzapzrkmgpgaba")
)
)
}
.start()
}
@JvmStatic
fun sendAttachFileEmail(toAddress: String, filePath: String?) {
val file = File(filePath)
if (!file.exists()) {
ToastUtils.showLong("打卡记录不存在,请检查")
return
}
Thread {
val isSendSuccess = MailSender().sendAccessoryMail(
createAttachMail(
toAddress,
file
)
)
}.start()
}
fun createMail(
toAddress: String?,
emailMessage: String,
senderEmail: String = "lttclaw@qq.com",
senderAuth: String = "hwpzapzrkmgpgaba"
): MailInfo {
val mailInfo = MailInfo()
mailInfo.mailServerHost = "smtp.qq.com" //发送方邮箱服务器
mailInfo.mailServerPort = "465" //发送方邮箱端口号
mailInfo.isValidate = true
mailInfo.userName = senderEmail // 发送者邮箱地址
mailInfo.password = senderAuth //邮箱授权码,不是密码
mailInfo.toAddress = toAddress // 接收者邮箱
mailInfo.fromAddress = senderEmail // 发送者邮箱
mailInfo.subject = "自动打卡通知" // 邮件主题
if (emailMessage == "") {
mailInfo.content =
"未监听到打卡成功的通知,请手动登录检查" + TimeOrDateUtil.timestampToDate(System.currentTimeMillis()) // 邮件文本
} else {
mailInfo.content = emailMessage // 邮件文本
}
return mailInfo
}
fun createAttachMail(
toAddress: String,
file: File,
senderEmail: String = "lttclaw@qq.com",
senderAuth: String = "hwpzapzrkmgpgaba"
): MailInfo {
val mailInfo = MailInfo()
mailInfo.mailServerHost = "smtp.qq.com" //发送方邮箱服务器
mailInfo.mailServerPort = "465" //发送方邮箱端口号
mailInfo.isValidate = true
mailInfo.userName = senderEmail // 发送者邮箱地址
mailInfo.password = senderAuth //邮箱授权码,不是密码
mailInfo.toAddress = toAddress // 接收者邮箱
mailInfo.fromAddress = senderEmail // 发送者邮箱
mailInfo.subject = "打卡记录" // 邮件主题
mailInfo.attachFile = file
return mailInfo
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/StatusBarColorUtil.java
================================================
package com.pengxh.autodingding.utils;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
public class StatusBarColorUtil {
public static void setColor(Activity activity, int color) {
//限制android系统的版本
// 设置状态栏透明
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 生成一个状态栏大小的矩形
View statusView = createStatusView(activity, color);
// 添加 statusView 到布局中
ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
decorView.addView(statusView);
// 设置根布局的参数
ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
rootView.setFitsSystemWindows(true);
rootView.setClipToPadding(true);
}
/**
* 生成一个和状态栏大小相同的矩形条
*
* @param activity 需要设置的activity
* @param color 状态栏颜色值
* @return 状态栏矩形条
*/
private static View createStatusView(Activity activity, int color) {
// 获得状态栏高度
int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
int statusBarHeight = activity.getResources().getDimensionPixelSize(resourceId);
// 绘制一个和状态栏一样高的矩形
View statusView = new View(activity);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight);
statusView.setLayoutParams(params);
statusView.setBackgroundColor(color);
return statusView;
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/TimeOrDateUtil.kt
================================================
package com.pengxh.autodingding.utils
import com.blankj.utilcode.util.ToastUtils
import java.text.SimpleDateFormat
import java.util.*
object TimeOrDateUtil {
private var dateFormat: SimpleDateFormat? = null
/**
* 时间戳转日期
*/
fun rTimestampToDate(millSeconds: Long): String {
dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
return dateFormat!!.format(Date(millSeconds))
}
/**
* 时间戳转时间
*/
fun timestampToTime(millSeconds: Long): String {
dateFormat = SimpleDateFormat("HH:mm:ss", Locale.CHINA)
return dateFormat!!.format(Date(millSeconds))
}
/**
* 时间戳转详细日期时间
*/
fun timestampToDate(millSeconds: Long): String {
dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
return dateFormat!!.format(Date(millSeconds))
}
/**
* 计算时间差
*
* @param fixedTime 结束时间
*/
fun deltaTime(fixedTime: Long): Long {
val currentTime = System.currentTimeMillis() / 1000
if (fixedTime > currentTime) {
return fixedTime - currentTime
} else {
ToastUtils.showLong("时间设置异常")
}
return 0L
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/Utils.java
================================================
package com.pengxh.autodingding.utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import androidx.appcompat.app.AlertDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.pengxh.autodingding.R;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class Utils {
private static final String TAG = "Utils";
private static final String fileName = "emailAddress.txt";
@SuppressLint("StaticFieldLeak")
private static Context mContext;
private static NotificationManager notificationManager;
public static void init(Context context) {
Utils.mContext = context.getApplicationContext();//获取全局上下文,最长生命周期
File filePath = context.getExternalFilesDir("setting");
File file = new File(filePath, fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Log.d(TAG, "init: " + file);
}
/**
* 检查手机上是否安装了指定的软件
*
* @param packageName 应用包名
*/
public static boolean isAppAvailable(String packageName) {
PackageManager packageManager = mContext.getPackageManager();
//获取所有已安装程序的包信息
List packageInfos = packageManager.getInstalledPackages(0);
List packageNames = new ArrayList<>();
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
packageNames.add(packName);
}
return packageNames.contains(packageName);
}
public static void createNotification() {
//Android8.0以上必须添加 渠道 才能显示通知栏
Notification.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//创建渠道
String name = mContext.getResources().getString(R.string.app_name);
String id = name + "_DefaultChannel";
NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(mChannel);
builder = new Notification.Builder(mContext, id);
} else {
builder = new Notification.Builder(mContext);
}
builder.setContentTitle("钉钉打卡通知监听已打开")
.setContentText("如果通知消失,请重新开启应用")
.setSmallIcon(R.mipmap.logo_round)
.setAutoCancel(false);
Notification notification = builder.build();
notification.flags = Notification.FLAG_NO_CLEAR;
notificationManager.notify(111, notification);
}
/**
* 打开指定包名的apk
*
* @param packageName 应用包名
*/
public static void openDingDing(String packageName) {
wakeUpAndUnlock();
Log.d(TAG, "openDingDing: 已亮屏,1s后启动钉钉");
new CountDownTimer(1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
startPackageLauncherIntent(packageName);
}
}.start();
}
public static void startPackageLauncherIntent(String packageName) {
PackageManager packageManager = mContext.getPackageManager();
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resolveIntent.setPackage(packageName);
List apps = packageManager.queryIntentActivities(resolveIntent, 0);
ResolveInfo resolveInfo = apps.iterator().next();
if (resolveInfo != null) {
String className = resolveInfo.activityInfo.name;
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ComponentName cn = new ComponentName(packageName, className);
intent.setComponent(cn);
mContext.startActivity(intent);
}
}
/**
* 唤醒屏幕并解锁
*/
public static void wakeUpAndUnlock() {
Log.d(TAG, "wakeUpAndUnlock: 亮屏解锁");
PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
boolean screenOn = powerManager.isInteractive();
if (!screenOn) {
//唤醒屏幕
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "autoDing:bright");
wakeLock.acquire(10000);
wakeLock.release();
}
//解锁屏幕
KeyguardManager keyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
keyguardManager.requestDismissKeyguard(ActivityUtils.getTopActivity(), new KeyguardManager.KeyguardDismissCallback() {
@Override
public void onDismissError() {
super.onDismissError();
}
});
}else {
KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("unLock");
keyguardLock.disableKeyguard();
}
}
/**
* 将数据写入文件
*/
public static void saveEmailAddress(String email) {
//准备写入
FileOutputStream outputStream;
BufferedWriter bufferedWriter = null;
try {
outputStream = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(email);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 读取文件存储内容
*/
public static String readEmailAddress() {
FileInputStream inputStream;
BufferedReader bufferedReader = null;
StringBuilder content = new StringBuilder();
try {
inputStream = mContext.openFileInput(fileName);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
public static void showAlertDialog(Activity activity, String title, String message, String positiveButton, boolean cancelable) {
createBuilder(activity, title, message)
.setCancelable(cancelable)
.setPositiveButton(positiveButton, null)
.create()
.show();
}
private static AlertDialog.Builder createBuilder(Activity activity, String title, String message) {
return new AlertDialog.Builder(activity)
.setIcon(R.mipmap.logo)
.setTitle(title)
.setMessage(message);
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/utils/ViewExt.kt
================================================
package com.pengxh.autodingding.utils
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.res.TypedArray
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import com.scwang.smartrefresh.layout.SmartRefreshLayout
/**
* 防止重复点击
* @param interval 重复间隔
* @param onClick 事件响应
*/
var lastTime = 0L
fun View.clickNoRepeat(interval: Long = 400, onClick: (View) -> Unit) {
setOnClickListener {
val currentTime = System.currentTimeMillis()
if (lastTime != 0L && (currentTime - lastTime < interval)) {
return@setOnClickListener
}
lastTime = currentTime
onClick(it)
}
}
/**
* 复制剪切板
*/
fun copy(context: Context, msg: String) {
val clip = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clip.setPrimaryClip(ClipData.newPlainText("text", msg))
toast("已复制")
}
/**
* 隐藏刷新加载ui
*/
fun SmartRefreshLayout.smartDismiss() {
finishRefresh(0)
finishLoadMore(0)
}
/**
* 获取当前主图颜色属性
*/
fun Context.getThemeColor(attr: Int): Int {
val array: TypedArray = theme.obtainStyledAttributes(
intArrayOf(
attr
)
)
val color = array.getColor(0, -0x50506)
array.recycle()
return color
}
/**
* editText搜索按钮
* @param onClick 搜索点击事件
*/
fun EditText.keyBoardSearch(onClick: () -> Unit) {
//添加搜索按钮
setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
onClick()
} else {
toast("请输入关键字")
return@setOnEditorActionListener false
}
return@setOnEditorActionListener true
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/widgets/EasyPopupWindow.kt
================================================
package com.pengxh.autodingding.widgets
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.AdapterView.OnItemClickListener
import android.widget.ListView
import android.widget.PopupWindow
import com.pengxh.autodingding.R
/**
* @description: TODO 顶部下拉菜单
* @author: Pengxh
* @email: 290677893@qq.com
* @date: 2019/12/28 20:35
*/
class EasyPopupWindow(private val mContext: Context, private val itemList: List) :
PopupWindow(
mContext
) {
private var mClickListener: PopupWindowClickListener? = null
init {
width = 400
height = ViewGroup.LayoutParams.WRAP_CONTENT
isOutsideTouchable = true
isFocusable = true
animationStyle = R.style.PopupAnimation
val contentView = LayoutInflater.from(mContext).inflate(R.layout.easy_popup, null, false)
setContentView(contentView)
val popupListView = contentView.findViewById(R.id.popupListView)
setupListView(popupListView)
}
//给PopupWindow列表绑定数据
private fun setupListView(popupListView: ListView) {
val adapter = PopupAdapter(mContext, itemList)
popupListView.adapter = adapter
popupListView.onItemClickListener = OnItemClickListener { adapterView, view, i, l ->
if (mClickListener != null) {
mClickListener!!.popupWindowClick(i)
}
dismiss()
}
}
interface PopupWindowClickListener {
fun popupWindowClick(position: Int)
}
fun setPopupWindowClickListener(windowClickListener: PopupWindowClickListener?) {
mClickListener = windowClickListener
}
}
================================================
FILE: app/src/main/java/com/pengxh/autodingding/widgets/PopupAdapter.java
================================================
package com.pengxh.autodingding.widgets;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.pengxh.autodingding.R;
import com.pengxh.autodingding.utils.Constant;
import java.util.List;
/**
* @description: TODO
* @author: Pengxh
* @email: 290677893@qq.com
* @date: 2019/12/28 20:46
*/
public class PopupAdapter extends BaseAdapter {
private final List itemList;
private final LayoutInflater inflater;
public PopupAdapter(Context mContext, List stringList) {
this.itemList = stringList;
inflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return itemList == null ? 0 : itemList.size();
}
@Override
public Object getItem(int position) {
return itemList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
PopupWindowHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_easy_popup, null);
holder = new PopupWindowHolder();
holder.itemIcon = convertView.findViewById(R.id.itemIcon);
holder.itemName = convertView.findViewById(R.id.itemName);
convertView.setTag(holder);
} else {
holder = (PopupWindowHolder) convertView.getTag();
}
holder.bindData(itemList.get(position), position);
return convertView;
}
private static class PopupWindowHolder {
private ImageView itemIcon;
private TextView itemName;
void bindData(String s, int index) {
itemIcon.setImageResource(Constant.images[index]);
itemName.setText(s);
}
}
}
================================================
FILE: app/src/main/java/xcom/warof/chosen/greendao/DaoMaster.java
================================================
package xcom.warof.chosen.greendao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
import org.greenrobot.greendao.AbstractDaoMaster;
import org.greenrobot.greendao.database.StandardDatabase;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseOpenHelper;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* Master of DAO (schema version 1): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(Database db, boolean ifNotExists) {
HistoryRecordBeanDao.createTable(db, ifNotExists);
}
/** Drops underlying database table using DAOs. */
public static void dropAllTables(Database db, boolean ifExists) {
HistoryRecordBeanDao.dropTable(db, ifExists);
}
/**
* WARNING: Drops all table on Upgrade! Use only during development.
* Convenience method using a {@link DevOpenHelper}.
*/
public static DaoSession newDevSession(Context context, String name) {
Database db = new DevOpenHelper(context, name).getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
return daoMaster.newSession();
}
public DaoMaster(SQLiteDatabase db) {
this(new StandardDatabase(db));
}
public DaoMaster(Database db) {
super(db, SCHEMA_VERSION);
registerDaoClass(HistoryRecordBeanDao.class);
}
public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
public DaoSession newSession(IdentityScopeType type) {
return new DaoSession(db, type, daoConfigMap);
}
/**
* Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} -
*/
public static abstract class OpenHelper extends DatabaseOpenHelper {
public OpenHelper(Context context, String name) {
super(context, name, SCHEMA_VERSION);
}
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}
@Override
public void onCreate(Database db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}
/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
}
================================================
FILE: app/src/main/java/xcom/warof/chosen/greendao/DaoSession.java
================================================
package xcom.warof.chosen.greendao;
import java.util.Map;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;
import com.pengxh.autodingding.bean.HistoryRecordBean;
import xcom.warof.chosen.greendao.HistoryRecordBeanDao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see org.greenrobot.greendao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig historyRecordBeanDaoConfig;
private final HistoryRecordBeanDao historyRecordBeanDao;
public DaoSession(Database db, IdentityScopeType type, Map>, DaoConfig>
daoConfigMap) {
super(db);
historyRecordBeanDaoConfig = daoConfigMap.get(HistoryRecordBeanDao.class).clone();
historyRecordBeanDaoConfig.initIdentityScope(type);
historyRecordBeanDao = new HistoryRecordBeanDao(historyRecordBeanDaoConfig, this);
registerDao(HistoryRecordBean.class, historyRecordBeanDao);
}
public void clear() {
historyRecordBeanDaoConfig.clearIdentityScope();
}
public HistoryRecordBeanDao getHistoryRecordBeanDao() {
return historyRecordBeanDao;
}
}
================================================
FILE: app/src/main/java/xcom/warof/chosen/greendao/HistoryRecordBeanDao.java
================================================
package xcom.warof.chosen.greendao;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import com.pengxh.autodingding.bean.HistoryRecordBean;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "HISTORY_RECORD_BEAN".
*/
public class HistoryRecordBeanDao extends AbstractDao {
public static final String TABLENAME = "HISTORY_RECORD_BEAN";
/**
* Properties of entity HistoryRecordBean.
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Uuid = new Property(1, String.class, "uuid", false, "UUID");
public final static Property Date = new Property(2, String.class, "date", false, "DATE");
public final static Property Message = new Property(3, String.class, "message", false, "MESSAGE");
}
public HistoryRecordBeanDao(DaoConfig config) {
super(config);
}
public HistoryRecordBeanDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"HISTORY_RECORD_BEAN\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"\"UUID\" TEXT," + // 1: uuid
"\"DATE\" TEXT," + // 2: date
"\"MESSAGE\" TEXT);"); // 3: message
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"HISTORY_RECORD_BEAN\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, HistoryRecordBean entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String uuid = entity.getUuid();
if (uuid != null) {
stmt.bindString(2, uuid);
}
String date = entity.getDate();
if (date != null) {
stmt.bindString(3, date);
}
String message = entity.getMessage();
if (message != null) {
stmt.bindString(4, message);
}
}
@Override
protected final void bindValues(SQLiteStatement stmt, HistoryRecordBean entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String uuid = entity.getUuid();
if (uuid != null) {
stmt.bindString(2, uuid);
}
String date = entity.getDate();
if (date != null) {
stmt.bindString(3, date);
}
String message = entity.getMessage();
if (message != null) {
stmt.bindString(4, message);
}
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public HistoryRecordBean readEntity(Cursor cursor, int offset) {
HistoryRecordBean entity = new HistoryRecordBean( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // uuid
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // date
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3) // message
);
return entity;
}
@Override
public void readEntity(Cursor cursor, HistoryRecordBean entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setUuid(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setDate(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setMessage(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
}
@Override
protected final Long updateKeyAfterInsert(HistoryRecordBean entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(HistoryRecordBean entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(HistoryRecordBean entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}
================================================
FILE: app/src/main/res/anim/popup_hide.xml
================================================
================================================
FILE: app/src/main/res/anim/popup_show.xml
================================================
================================================
FILE: app/src/main/res/drawable/bg_textview.xml
================================================
================================================
FILE: app/src/main/res/drawable/bg_textview_error.xml
================================================
================================================
FILE: app/src/main/res/drawable/bottom_text_color.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_launcher_background.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_stop.xml
================================================
================================================
FILE: app/src/main/res/drawable/list_divider.xml
================================================
================================================
FILE: app/src/main/res/drawable/popup_list_divider.xml
================================================
================================================
FILE: app/src/main/res/drawable/select_switch_background.xml
================================================
================================================
FILE: app/src/main/res/drawable/select_switch_circle.xml
================================================
================================================
FILE: app/src/main/res/drawable/svg_back.xml
================================================
================================================
FILE: app/src/main/res/drawable/swich_background_off.xml
================================================
================================================
FILE: app/src/main/res/drawable/swich_background_on.xml
================================================
================================================
FILE: app/src/main/res/drawable/switch_circle_off.xml
================================================
================================================
FILE: app/src/main/res/drawable/switch_circle_on.xml
================================================
================================================
FILE: app/src/main/res/drawable-v24/ic_launcher_foreground.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_history.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_main.xml
================================================
================================================
FILE: app/src/main/res/layout/easy_popup.xml
================================================
================================================
FILE: app/src/main/res/layout/fragment_day.xml
================================================
================================================
FILE: app/src/main/res/layout/fragment_mail_conf.xml
================================================
================================================
FILE: app/src/main/res/layout/fragment_push.xml
================================================
================================================
FILE: app/src/main/res/layout/fragment_remote_sign.xml
================================================
================================================
FILE: app/src/main/res/layout/fragment_settings.xml
================================================
================================================
FILE: app/src/main/res/layout/include_title.xml
================================================
================================================
FILE: app/src/main/res/layout/item_easy_popup.xml
================================================
================================================
FILE: app/src/main/res/layout/item_list.xml
================================================
================================================
FILE: app/src/main/res/layout/item_tab.xml
================================================
================================================
FILE: app/src/main/res/layout/permission_fragment.xml
================================================
================================================
FILE: app/src/main/res/menu/bottom_nav_menu.xml
================================================
================================================
FILE: app/src/main/res/raw/tip
================================================
妈我建议你可以考虑这几个方向。
1、见下国强小姑,和国强小姑商量一下你怎么和院长发个短信打个电话之类的方法跟进一下事情进展,
让院长能给到我爸明确的彩礼数字和给的时间的答复。
2、见下小辰她妈妈,和她妈妈一起吐槽一下爸这边态度问题,舒缓一下两家紧张的关系,再私下在领证前给到她妈妈3万,请她临场只问我爸要5万8,
我爸要是高兴了可能还是会坚持按院长说的给足8万8的话引玲姨自然会把你多给的3万再私下退回给你
================================================
FILE: app/src/main/res/values/attrs.xml
================================================
================================================
FILE: app/src/main/res/values/colors.xml
================================================
#3F51B5#303F9F#FF4081#FFFFFF#CCCCCC#0D0D0D#171717#333333#313131#0094FF#4DDC64#0094FF#ffa500#00ffff#32cd32
================================================
FILE: app/src/main/res/values/strings.xml
================================================
上班帮手
Tips:此版本是测试版本,可能会有些问题我自测试没有发现的,有问题请发邮件给lttclaw@qq.com。建议用一台闲置的手机
放在公司来打卡,另一台手机来推送打卡指令。基本用法只需要一台闲置手机,定好时间后会自动打开钉钉,完成极速打卡;进阶用法
需要一台打卡手机,一台自用手机,把打卡手机的注册ID复制到推送界面推送打卡指令可以远程打开钉钉,完成极速打卡。设置须知:\n
1、请先确认好通知栏监听已开启,如不开启将无法监听打卡成功的通知。\n
2、调起钉钉实现自动打卡,需要把打卡手机锁屏密码之类的取消掉\n
3、部分手机需要授权允许后台打开窗口\n
3、先在设置里面测试下能否正常打开钉钉,第一次有些手机会让授权\n
4、将钉钉软件上下班都设置为“极速打卡”。\n
5、设置好自己的收信邮箱,跳转到“钉钉”打卡成功后会发送一封打卡成功的邮件到你自己设置好的邮箱。\n
空白页
请注意,如果您使用应用内自带的发件邮箱配置,即开发者本人的个人qq邮箱来发送打卡通知,您的这些邮件都会被本人在qq邮箱的
发件箱中看到,而且如果使用我的邮箱发件人数太多,我会考虑更换邮箱授权码,界时用此授权码的发邮件功能将无法正常工作。
因此,为了您的隐私考虑,请您最好去自己的qq邮箱设置里打开smtp服务获取自己的邮箱授权码在此配置
远程启钉基础辅助服务远程启钉手势服务前台服务
================================================
FILE: app/src/main/res/values/styles.xml
================================================
================================================
FILE: app/src/main/res/xml/base_accessibility_config.xml
================================================
================================================
FILE: app/src/main/res/xml-v24/gesture_accessibility_config.xml
================================================
================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
maven { url "https://maven.aliyun.com/repository/public" }
maven { url 'https://maven.aliyun.com/repository/google' }
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.4.2'
classpath 'org.greenrobot:greendao-gradle-plugin:3.3.1'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
tasks.register('clean', Delete) {
delete rootProject.buildDir
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Wed Apr 27 09:13:07 CST 2022
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-all.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
org.gradle.jvmargs=-Xmx1536m
android.injected.testOnly=false
android.nonTransitiveRClass=false
android.nonFinalResIds=false
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
================================================
FILE: gradlew
================================================
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: settings.gradle
================================================
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven { url 'https://jitpack.io' }
maven { url "https://maven.aliyun.com/repository/public" }
maven { url 'https://maven.aliyun.com/repository/google' }
maven { url 'https://developer.huawei.com/repo/'
allowInsecureProtocol = true}
}
}
include ':app'