├── .gradle
└── 2.8
│ └── taskArtifacts
│ ├── cache.properties
│ ├── cache.properties.lock
│ ├── fileHashes.bin
│ ├── fileSnapshots.bin
│ ├── outputFileStates.bin
│ └── taskArtifacts.bin
├── .idea
└── vcs.xml
├── DemoMarsdaemon
├── .gitignore
├── DemoMarsdaemon.iml
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── marswin89
│ │ └── marsdaemon
│ │ └── demo
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── marswin89
│ │ │ └── marsdaemon
│ │ │ └── demo
│ │ │ ├── MainActivity.java
│ │ │ ├── MyApplication1.java
│ │ │ ├── MyApplication2.java
│ │ │ ├── Receiver1.java
│ │ │ ├── Receiver2.java
│ │ │ ├── Service1.java
│ │ │ └── Service2.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-v21
│ │ └── styles.xml
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── marswin89
│ └── marsdaemon
│ └── demo
│ └── ExampleUnitTest.java
├── LICENSE
├── LibMarsdaemon
├── .gitignore
├── LibMarsdaemon.iml
├── build.gradle
├── jni
│ ├── Android.mk
│ ├── Application.mk
│ ├── com_marswin89_marsdaemon_nativ_NativeDaemonAPI20.h
│ ├── com_marswin89_marsdaemon_nativ_NativeDaemonAPI21.h
│ ├── common.c
│ ├── constant.h
│ ├── daemon.c
│ ├── daemon_api20.c
│ ├── daemon_api21.c
│ └── log.h
├── libs
│ ├── armeabi-v7a
│ │ ├── libdaemon_api20.so
│ │ └── libdaemon_api21.so
│ ├── armeabi
│ │ ├── libdaemon_api20.so
│ │ └── libdaemon_api21.so
│ └── x86
│ │ ├── libdaemon_api20.so
│ │ └── libdaemon_api21.so
├── proguard-rules.pro
└── src
│ ├── main
│ ├── AndroidManifest.xml
│ ├── assets
│ │ ├── armeabi-v7a
│ │ │ └── daemon
│ │ ├── armeabi
│ │ │ └── daemon
│ │ └── x86
│ │ │ └── daemon
│ ├── java
│ │ └── com
│ │ │ └── marswin89
│ │ │ └── marsdaemon
│ │ │ ├── DaemonApplication.java
│ │ │ ├── DaemonClient.java
│ │ │ ├── DaemonConfigurations.java
│ │ │ ├── IDaemonClient.java
│ │ │ ├── IDaemonStrategy.java
│ │ │ ├── NativeDaemonBase.java
│ │ │ ├── PackageUtils.java
│ │ │ ├── nativ
│ │ │ ├── NativeDaemonAPI20.java
│ │ │ └── NativeDaemonAPI21.java
│ │ │ └── strategy
│ │ │ ├── DaemonStrategy21.java
│ │ │ ├── DaemonStrategy22.java
│ │ │ ├── DaemonStrategy23.java
│ │ │ ├── DaemonStrategyUnder21.java
│ │ │ └── DaemonStrategyXiaomi.java
│ └── res
│ │ └── values
│ │ └── strings.xml
│ └── test
│ └── java
│ └── com
│ └── marswin89
│ └── marsdaemon
│ └── ExampleUnitTest.java
├── Marsdaemon2.iml
├── README.md
├── build.gradle
├── build
└── intermediates
│ └── dex-cache
│ └── cache.xml
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── local.properties
└── settings.gradle
/.gradle/2.8/taskArtifacts/cache.properties:
--------------------------------------------------------------------------------
1 | #Thu Dec 24 18:13:42 CST 2015
2 |
--------------------------------------------------------------------------------
/.gradle/2.8/taskArtifacts/cache.properties.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/.gradle/2.8/taskArtifacts/cache.properties.lock
--------------------------------------------------------------------------------
/.gradle/2.8/taskArtifacts/fileHashes.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/.gradle/2.8/taskArtifacts/fileHashes.bin
--------------------------------------------------------------------------------
/.gradle/2.8/taskArtifacts/fileSnapshots.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/.gradle/2.8/taskArtifacts/fileSnapshots.bin
--------------------------------------------------------------------------------
/.gradle/2.8/taskArtifacts/outputFileStates.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/.gradle/2.8/taskArtifacts/outputFileStates.bin
--------------------------------------------------------------------------------
/.gradle/2.8/taskArtifacts/taskArtifacts.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/.gradle/2.8/taskArtifacts/taskArtifacts.bin
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/DemoMarsdaemon.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | generateDebugSources
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "com.marswin89.marsdaemon.demo"
9 | minSdkVersion 10
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | }
15 |
16 | dependencies {
17 | compile fileTree(dir: 'libs', include: ['*.jar'])
18 | testCompile 'junit:junit:4.12'
19 | compile 'com.android.support:appcompat-v7:23.1.1'
20 | compile 'com.android.support:design:23.1.1'
21 | compile project(':LibMarsdaemon')
22 | }
23 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/guoyang/Developer/android-sdk-macosx/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/androidTest/java/com/marswin89/marsdaemon/demo/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.demo;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/java/com/marswin89/marsdaemon/demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.demo;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 |
7 | /**
8 | *
9 | * Created by Mars on 12/24/15.
10 | */
11 | public class MainActivity extends Activity {
12 |
13 | @Override
14 | protected void onCreate(Bundle savedInstanceState) {
15 | super.onCreate(savedInstanceState);
16 | setContentView(R.layout.activity_main);
17 |
18 | //you have to start the service once.
19 | startService(new Intent(MainActivity.this, Service1.class));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/java/com/marswin89/marsdaemon/demo/MyApplication1.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.demo;
2 |
3 | import android.content.Context;
4 |
5 | import com.marswin89.marsdaemon.DaemonApplication;
6 | import com.marswin89.marsdaemon.DaemonConfigurations;
7 |
8 | /**
9 | * Implementation 1
10 | * override one method is ok.
11 | *
12 | * Created by Mars on 12/24/15.
13 | */
14 | public class MyApplication1 extends DaemonApplication {
15 |
16 | /**
17 | * you can override this method instead of {@link android.app.Application attachBaseContext}
18 | * @param base
19 | */
20 | @Override
21 | public void attachBaseContextByDaemon(Context base) {
22 | super.attachBaseContextByDaemon(base);
23 | }
24 |
25 |
26 | /**
27 | * give the configuration to lib in this callback
28 | * @return
29 | */
30 | @Override
31 | protected DaemonConfigurations getDaemonConfigurations() {
32 | DaemonConfigurations.DaemonConfiguration configuration1 = new DaemonConfigurations.DaemonConfiguration(
33 | "com.marswin89.marsdaemon.demo:process1",
34 | Service1.class.getCanonicalName(),
35 | Receiver1.class.getCanonicalName());
36 |
37 | DaemonConfigurations.DaemonConfiguration configuration2 = new DaemonConfigurations.DaemonConfiguration(
38 | "com.marswin89.marsdaemon.demo:process2",
39 | Service2.class.getCanonicalName(),
40 | Receiver2.class.getCanonicalName());
41 |
42 | DaemonConfigurations.DaemonListener listener = new MyDaemonListener();
43 | //return new DaemonConfigurations(configuration1, configuration2);//listener can be null
44 | return new DaemonConfigurations(configuration1, configuration2, listener);
45 | }
46 |
47 |
48 | class MyDaemonListener implements DaemonConfigurations.DaemonListener{
49 | @Override
50 | public void onPersistentStart(Context context) {
51 | }
52 |
53 | @Override
54 | public void onDaemonAssistantStart(Context context) {
55 | }
56 |
57 | @Override
58 | public void onWatchDaemonDaed() {
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/java/com/marswin89/marsdaemon/demo/MyApplication2.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.demo;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 | import com.marswin89.marsdaemon.DaemonApplication;
7 | import com.marswin89.marsdaemon.DaemonClient;
8 | import com.marswin89.marsdaemon.DaemonConfigurations;
9 |
10 | /**
11 | * Implementation 2
12 | * if you have to extends other Application, use this method.
13 | *
14 | * Created by Mars on 12/24/15.
15 | */
16 | public class MyApplication2 extends Application {
17 |
18 | private DaemonClient mDaemonClient;
19 |
20 | @Override
21 | protected void attachBaseContext(Context base) {
22 | super.attachBaseContext(base);
23 | mDaemonClient = new DaemonClient(createDaemonConfigurations());
24 | mDaemonClient.onAttachBaseContext(base);
25 | }
26 |
27 |
28 |
29 | private DaemonConfigurations createDaemonConfigurations(){
30 | DaemonConfigurations.DaemonConfiguration configuration1 = new DaemonConfigurations.DaemonConfiguration(
31 | "com.marswin89.marsdaemon.demo:process1",
32 | Service1.class.getCanonicalName(),
33 | Receiver1.class.getCanonicalName());
34 | DaemonConfigurations.DaemonConfiguration configuration2 = new DaemonConfigurations.DaemonConfiguration(
35 | "com.marswin89.marsdaemon.demo:process2",
36 | Service2.class.getCanonicalName(),
37 | Receiver2.class.getCanonicalName());
38 | DaemonConfigurations.DaemonListener listener = new MyDaemonListener();
39 | //return new DaemonConfigurations(configuration1, configuration2);//listener can be null
40 | return new DaemonConfigurations(configuration1, configuration2, listener);
41 | }
42 |
43 |
44 | class MyDaemonListener implements DaemonConfigurations.DaemonListener{
45 | @Override
46 | public void onPersistentStart(Context context) {
47 | }
48 |
49 | @Override
50 | public void onDaemonAssistantStart(Context context) {
51 | }
52 |
53 | @Override
54 | public void onWatchDaemonDaed() {
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/java/com/marswin89/marsdaemon/demo/Receiver1.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.demo;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 |
7 | /**
8 | * DO NOT do anything in this Receiver!
9 | *
10 | * Created by Mars on 12/24/15.
11 | */
12 | public class Receiver1 extends BroadcastReceiver {
13 | @Override
14 | public void onReceive(Context context, Intent intent) {
15 |
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/java/com/marswin89/marsdaemon/demo/Receiver2.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.demo;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 |
7 | /**
8 | * DO NOT do anything in this Receiver!
9 | *
10 | * Created by Mars on 12/24/15.
11 | */
12 | public class Receiver2 extends BroadcastReceiver {
13 | @Override
14 | public void onReceive(Context context, Intent intent) {
15 |
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/java/com/marswin89/marsdaemon/demo/Service1.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.demo;
2 |
3 | import android.app.Service;
4 | import android.content.Intent;
5 | import android.os.IBinder;
6 |
7 | /**
8 | * This Service is Persistent Service. Do some what you want to do here.
9 | *
10 | * Created by Mars on 12/24/15.
11 | */
12 | public class Service1 extends Service{
13 |
14 | @Override
15 | public void onCreate() {
16 | super.onCreate();
17 | //TODO do some thing what you want..
18 | }
19 |
20 | @Override
21 | public IBinder onBind(Intent intent) {
22 | return null;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/java/com/marswin89/marsdaemon/demo/Service2.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.demo;
2 |
3 | import android.app.Service;
4 | import android.content.Intent;
5 | import android.os.IBinder;
6 |
7 | /**
8 | * DO NOT do anything in this Service!
9 | *
10 | * Created by Mars on 12/24/15.
11 | */
12 | public class Service2 extends Service{
13 |
14 | @Override
15 | public IBinder onBind(Intent intent) {
16 | return null;
17 | }
18 |
19 | @Override
20 | public int onStartCommand(Intent intent, int flags, int startId) {
21 | return Service.START_NOT_STICKY;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/DemoMarsdaemon/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/DemoMarsdaemon/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/DemoMarsdaemon/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/DemoMarsdaemon/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/DemoMarsdaemon/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 | 16dp
6 |
7 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Hello, this is Mars.
3 | MarsDaemon
4 |
5 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/DemoMarsdaemon/src/test/java/com/marswin89/marsdaemon/demo/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.demo;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/LibMarsdaemon/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/LibMarsdaemon/LibMarsdaemon.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | generateDebugSources
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/LibMarsdaemon/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | minSdkVersion 10
9 | targetSdkVersion 23
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | sourceSets {
20 | main {
21 | jniLibs.srcDirs =['libs']
22 | }
23 | }
24 | }
25 |
26 | dependencies {
27 | compile fileTree(dir: 'libs', include: ['*.jar'])
28 | testCompile 'junit:junit:4.12'
29 | compile 'com.android.support:appcompat-v7:23.1.1'
30 | }
31 |
--------------------------------------------------------------------------------
/LibMarsdaemon/jni/Android.mk:
--------------------------------------------------------------------------------
1 | LOCAL_PATH := $(call my-dir)
2 | include $(CLEAR_VARS)
3 | LOCAL_MODULE := daemon_api20
4 | LOCAL_SRC_FILES := daemon_api20.c \
5 | common.c
6 | LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
7 | LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog -lm -lz
8 | include $(BUILD_SHARED_LIBRARY)
9 |
10 | include $(CLEAR_VARS)
11 | LOCAL_MODULE := daemon_api21
12 | LOCAL_SRC_FILES := daemon_api21.c \
13 | common.c
14 | LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
15 | LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog -lm -lz
16 | include $(BUILD_SHARED_LIBRARY)
17 |
18 | include $(CLEAR_VARS)
19 | LOCAL_MODULE := daemon
20 | LOCAL_SRC_FILES := daemon.c
21 | LOCAL_CFLAGS += -pie -fPIE
22 | LOCAL_LDFLAGS += -pie -fPIE
23 | LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
24 | LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog -lm -lz
25 | include $(BUILD_EXECUTABLE)
26 |
27 |
--------------------------------------------------------------------------------
/LibMarsdaemon/jni/Application.mk:
--------------------------------------------------------------------------------
1 | APP_ABI := armeabi armeabi-v7a x86
2 | APP_PLATFORM := android-15
--------------------------------------------------------------------------------
/LibMarsdaemon/jni/com_marswin89_marsdaemon_nativ_NativeDaemonAPI20.h:
--------------------------------------------------------------------------------
1 | /* DO NOT EDIT THIS FILE - it is machine generated */
2 | #include
3 | /* Header for class com_marswin89_marsdaemon_nativ_NativeDaemonAPI20 */
4 |
5 | #ifndef _Included_com_marswin89_marsdaemon_nativ_NativeDaemonAPI20
6 | #define _Included_com_marswin89_marsdaemon_nativ_NativeDaemonAPI20
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 | /*
11 | * Class: com_marswin89_marsdaemon_nativ_NativeDaemonAPI20
12 | * Method: doDaemon
13 | * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
14 | */
15 | JNIEXPORT void JNICALL Java_com_marswin89_marsdaemon_nativ_NativeDaemonAPI20_doDaemon
16 | (JNIEnv *, jobject, jstring, jstring, jstring);
17 |
18 | #ifdef __cplusplus
19 | }
20 | #endif
21 | #endif
22 |
--------------------------------------------------------------------------------
/LibMarsdaemon/jni/com_marswin89_marsdaemon_nativ_NativeDaemonAPI21.h:
--------------------------------------------------------------------------------
1 | /* DO NOT EDIT THIS FILE - it is machine generated */
2 | #include
3 | /* Header for class com_marswin89_marsdaemon_nativ_NativeDaemonAPI21 */
4 |
5 | #ifndef _Included_com_marswin89_marsdaemon_nativ_NativeDaemonAPI21
6 | #define _Included_com_marswin89_marsdaemon_nativ_NativeDaemonAPI21
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 | /*
11 | * Class: com_marswin89_marsdaemon_nativ_NativeDaemonAPI21
12 | * Method: doDaemon
13 | * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
14 | */
15 | JNIEXPORT void JNICALL Java_com_marswin89_marsdaemon_nativ_NativeDaemonAPI21_doDaemon
16 | (JNIEnv *, jobject, jstring, jstring, jstring, jstring);
17 |
18 | #ifdef __cplusplus
19 | }
20 | #endif
21 | #endif
22 |
--------------------------------------------------------------------------------
/LibMarsdaemon/jni/common.c:
--------------------------------------------------------------------------------
1 | /*
2 | * File : daemon_api21.c
3 | * Author : Mars Kwok
4 | * Date : Jul. 21, 2015
5 | * Description : common method here
6 | *
7 | * Copyright (C) Mars Kwok
8 | *
9 | */
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 |
16 | #include "log.h"
17 |
18 | /**
19 | * get the android version code
20 | */
21 | int get_version(){
22 | char value[8] = "";
23 | __system_property_get("ro.build.version.sdk", value);
24 | return atoi(value);
25 | }
26 |
27 | /**
28 | * stitch three string to one
29 | */
30 | char *str_stitching(const char *str1, const char *str2, const char *str3){
31 | char *result;
32 | result = (char*) malloc(strlen(str1) + strlen(str2) + strlen(str3) + 1);
33 | if (!result){
34 | return NULL;
35 | }
36 | strcpy(result, str1);
37 | strcat(result, str2);
38 | strcat(result, str3);
39 | return result;
40 | }
41 |
42 | /**
43 | * get android context
44 | */
45 | jobject get_context(JNIEnv* env, jobject jobj){
46 | jclass thiz_cls = (*env)->GetObjectClass(env, jobj);
47 | jfieldID context_field = (*env)->GetFieldID(env, thiz_cls, "mContext", "Landroid/content/Context;");
48 | return (*env)->GetObjectField(env, jobj, context_field);
49 | }
50 |
51 |
52 | char* get_package_name(JNIEnv* env, jobject jobj){
53 | jobject context_obj = get_context(env, jobj);
54 | jclass context_cls = (*env)->GetObjectClass(env, context_obj);
55 | jmethodID getpackagename_method = (*env)->GetMethodID(jobj, context_cls, "getPackageName", "()Ljava/lang/String;");
56 | jstring package_name = (jstring)(*env)->CallObjectMethod(env, context_obj, getpackagename_method);
57 | return (char*)(*env)->GetStringUTFChars(env, package_name, 0);
58 | }
59 |
60 |
61 | /**
62 | * call java callback
63 | */
64 | void java_callback(JNIEnv* env, jobject jobj, char* method_name){
65 | jclass cls = (*env)->GetObjectClass(env, jobj);
66 | jmethodID cb_method = (*env)->GetMethodID(env, cls, method_name, "()V");
67 | (*env)->CallVoidMethod(env, jobj, cb_method);
68 | }
69 |
70 | /**
71 | * start a android service
72 | */
73 | void start_service(char* package_name, char* service_name){
74 | pid_t pid = fork();
75 | if(pid < 0){
76 | //error, do nothing...
77 | }else if(pid == 0){
78 | if(package_name == NULL || service_name == NULL){
79 | exit(EXIT_SUCCESS);
80 | }
81 | int version = get_version();
82 | char* pkg_svc_name = str_stitching(package_name, "/", service_name);
83 | if (version >= 17 || version == 0) {
84 | execlp("am", "am", "startservice", "--user", "0", "-n", pkg_svc_name, (char *) NULL);
85 | } else {
86 | execlp("am", "am", "startservice", "-n", pkg_svc_name, (char *) NULL);
87 | }
88 | exit(EXIT_SUCCESS);
89 | }else{
90 | waitpid(pid, NULL, 0);
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/LibMarsdaemon/jni/constant.h:
--------------------------------------------------------------------------------
1 | #define NATIVE_DAEMON_NAME "mars_d"
2 | #define BUFFER_SIZE 2048
3 | #define DAEMON_CALLBACK_NAME "onDaemonDead"
4 | #define PARAM_PIPE_1_READ "-p1r"
5 | #define PARAM_PIPE_1_WRITE "-p1w"
6 | #define PARAM_PIPE_2_READ "-p2r"
7 | #define PARAM_PIPE_2_WRITE "-p2w"
8 | #define PARAM_PKG_NAME "-p"
9 | #define PARAM_SVC_NAME "-s"
10 |
11 |
12 |
--------------------------------------------------------------------------------
/LibMarsdaemon/jni/daemon.c:
--------------------------------------------------------------------------------
1 | /*
2 | * File : daemon_api21.c
3 | * Author : Mars Kwok
4 | * Date : Jul. 21, 2015
5 | * Description : This is native process to watch parent process.
6 | *
7 | * Copyright (C) Mars Kwok
8 | *
9 | */
10 | #include
11 | #include
12 |
13 | #include "log.h"
14 | #include "constant.h"
15 |
16 |
17 | /**
18 | * get the android version code
19 | */
20 | int get_version(){
21 | char value[8] = "";
22 | __system_property_get("ro.build.version.sdk", value);
23 | return atoi(value);
24 | }
25 |
26 | char *str_stitching(const char *str1, const char *str2, const char *str3){
27 | char *result;
28 | result = (char*) malloc(strlen(str1) + strlen(str2) + strlen(str3) + 1);
29 | if (!result){
30 | return NULL;
31 | }
32 | strcpy(result, str1);
33 | strcat(result, str2);
34 | strcat(result, str3);
35 | return result;
36 | }
37 |
38 | /**
39 | * start a android service
40 | */
41 | void start_service(char* package_name, char* service_name){
42 | pid_t pid = fork();
43 | if(pid < 0){
44 | //error, do nothing...
45 | }else if(pid == 0){
46 | if(package_name == NULL || service_name == NULL){
47 | exit(EXIT_SUCCESS);
48 | }
49 | int version = get_version();
50 | char* pkg_svc_name = str_stitching(package_name, "/", service_name);
51 | if (version >= 17 || version == 0) {
52 | execlp("am", "am", "startservice", "--user", "0", "-n", pkg_svc_name, (char *) NULL);
53 | } else {
54 | execlp("am", "am", "startservice", "-n", pkg_svc_name, (char *) NULL);
55 | }
56 | exit(EXIT_SUCCESS);
57 | }else{
58 | waitpid(pid, NULL, 0);
59 | }
60 | }
61 |
62 |
63 |
64 | int main(int argc, char *argv[]){
65 | pid_t pid = fork();
66 | if(pid == 0){
67 | setsid();
68 | int pipe_fd1[2];
69 | int pipe_fd2[2];
70 | char* pkg_name;
71 | char* svc_name;
72 | if(argc < 13){
73 | LOGE("daemon parameters error");
74 | return ;
75 | }
76 | int i;
77 | for (i = 0; i < argc; i ++){
78 | if(argv[i] == NULL){
79 | continue;
80 | }
81 | if (!strcmp(PARAM_PKG_NAME, argv[i])){
82 | pkg_name = argv[i + 1];
83 | }else if (!strcmp(PARAM_SVC_NAME, argv[i])) {
84 | svc_name = argv[i + 1];
85 | }else if (!strcmp(PARAM_PIPE_1_READ, argv[i])){
86 | char* p1r = argv[i + 1];
87 | pipe_fd1[0] = atoi(p1r);
88 | }else if (!strcmp(PARAM_PIPE_1_WRITE, argv[i])) {
89 | char* p1w = argv[i + 1];
90 | pipe_fd1[1] = atoi(p1w);
91 | }else if (!strcmp(PARAM_PIPE_2_READ, argv[i])) {
92 | char* p2r = argv[i + 1];
93 | pipe_fd2[0] = atoi(p2r);
94 | }else if (!strcmp(PARAM_PIPE_2_WRITE, argv[i])) {
95 | char* p2w = argv[i + 1];
96 | pipe_fd2[1] = atoi(p2w);
97 | }
98 | }
99 |
100 | close(pipe_fd1[0]);
101 | close(pipe_fd2[1]);
102 |
103 | char r_buf[100];
104 | int r_num;
105 | memset(r_buf,0, sizeof(r_buf));
106 |
107 | r_num=read(pipe_fd2[0], r_buf, 100);
108 | LOGE("Watch >>>>PARENT<<<< Dead !!");
109 | int count = 0;
110 | while(count < 50){
111 | start_service(pkg_name, svc_name);
112 | usleep(100000);
113 | count++;
114 | }
115 | }else{
116 | exit(EXIT_SUCCESS);
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/LibMarsdaemon/jni/daemon_api20.c:
--------------------------------------------------------------------------------
1 | /*
2 | * File : daemon_api21.c
3 | * Author : Mars Kwok
4 | * Date : Jul. 21, 2015
5 | * Description : This is used to watch process dead under api 20
6 | *
7 | * Copyright (C) Mars Kwok
8 | *
9 | */
10 | #include
11 | #include
12 | #include
13 |
14 | #include "log.h"
15 | #include "constant.h"
16 | #include "com_marswin89_marsdaemon_nativ_NativeDaemonAPI20.h"
17 |
18 |
19 |
20 | /**
21 | * get the process pid by process name
22 | */
23 | int find_pid_by_name(char *pid_name, int *pid_list){
24 | DIR *dir;
25 | struct dirent *next;
26 | int i = 0;
27 | pid_list[0] = 0;
28 | dir = opendir("/proc");
29 | if (!dir){
30 | return 0;
31 | }
32 | while ((next = readdir(dir)) != NULL){
33 | FILE *status;
34 | char proc_file_name[BUFFER_SIZE];
35 | char buffer[BUFFER_SIZE];
36 | char process_name[BUFFER_SIZE];
37 |
38 | if (strcmp(next->d_name, "..") == 0){
39 | continue;
40 | }
41 | if (!isdigit(*next->d_name)){
42 | continue;
43 | }
44 | sprintf(proc_file_name, "/proc/%s/cmdline", next->d_name);
45 | if (!(status = fopen(proc_file_name, "r"))){
46 | continue;
47 | }
48 | if (fgets(buffer, BUFFER_SIZE - 1, status) == NULL){
49 | fclose(status);
50 | continue;
51 | }
52 | fclose(status);
53 | sscanf(buffer, "%[^-]", process_name);
54 | if (strcmp(process_name, pid_name) == 0){
55 | pid_list[i ++] = atoi(next->d_name);
56 | }
57 | }
58 | if (pid_list){
59 | pid_list[i] = 0;
60 | }
61 | closedir(dir);
62 | return i;
63 | }
64 |
65 | /**
66 | * kill all process by name
67 | */
68 | void kill_zombie_process(char* zombie_name){
69 | int pid_list[200];
70 | int total_num = find_pid_by_name(zombie_name, pid_list);
71 | LOGD("zombie process name is %s, and number is %d, killing...", zombie_name, total_num);
72 | int i;
73 | for (i = 0; i < total_num; i ++) {
74 | int retval = 0;
75 | int daemon_pid = pid_list[i];
76 | if (daemon_pid > 1 && daemon_pid != getpid() && daemon_pid != getppid()){
77 | retval = kill(daemon_pid, SIGTERM);
78 | if (!retval){
79 | LOGD("kill zombie successfully, zombie`s pid = %d", daemon_pid);
80 | }else{
81 | LOGE("kill zombie failed, zombie`s pid = %d", daemon_pid);
82 | }
83 | }
84 | }
85 | }
86 |
87 | JNIEXPORT void JNICALL Java_com_marswin89_marsdaemon_nativ_NativeDaemonAPI20_doDaemon(JNIEnv *env, jobject jobj, jstring pkgName, jstring svcName, jstring daemonPath){
88 | if(pkgName == NULL || svcName == NULL || daemonPath == NULL){
89 | LOGE("native doDaemon parameters cannot be NULL !");
90 | return ;
91 | }
92 |
93 | char *pkg_name = (char*)(*env)->GetStringUTFChars(env, pkgName, 0);
94 | char *svc_name = (char*)(*env)->GetStringUTFChars(env, svcName, 0);
95 | char *daemon_path = (char*)(*env)->GetStringUTFChars(env, daemonPath, 0);
96 |
97 | kill_zombie_process(NATIVE_DAEMON_NAME);
98 |
99 | int pipe_fd1[2];//order to watch child
100 | int pipe_fd2[2];//order to watch parent
101 |
102 | pid_t pid;
103 | char r_buf[100];
104 | int r_num;
105 | memset(r_buf, 0, sizeof(r_buf));
106 | if(pipe(pipe_fd1)<0){
107 | LOGE("pipe1 create error");
108 | return ;
109 | }
110 | if(pipe(pipe_fd2)<0){
111 | LOGE("pipe2 create error");
112 | return ;
113 | }
114 |
115 | char str_p1r[10];
116 | char str_p1w[10];
117 | char str_p2r[10];
118 | char str_p2w[10];
119 |
120 | sprintf(str_p1r,"%d",pipe_fd1[0]);
121 | sprintf(str_p1w,"%d",pipe_fd1[1]);
122 | sprintf(str_p2r,"%d",pipe_fd2[0]);
123 | sprintf(str_p2w,"%d",pipe_fd2[1]);
124 |
125 |
126 | if((pid=fork())==0){
127 | execlp(daemon_path,
128 | NATIVE_DAEMON_NAME,
129 | PARAM_PKG_NAME, pkg_name,
130 | PARAM_SVC_NAME, svc_name,
131 | PARAM_PIPE_1_READ, str_p1r,
132 | PARAM_PIPE_1_WRITE, str_p1w,
133 | PARAM_PIPE_2_READ, str_p2r,
134 | PARAM_PIPE_2_WRITE, str_p2w,
135 | (char *) NULL);
136 | }else if(pid>0){
137 | close(pipe_fd1[1]);
138 | close(pipe_fd2[0]);
139 | //wait for child
140 | r_num=read(pipe_fd1[0], r_buf, 100);
141 | LOGE("Watch >>>>CHILD<<<< Dead !!!");
142 | java_callback(env, jobj, DAEMON_CALLBACK_NAME);
143 | }
144 | }
145 |
146 |
--------------------------------------------------------------------------------
/LibMarsdaemon/jni/daemon_api21.c:
--------------------------------------------------------------------------------
1 | /*
2 | * File : daemon_api21.c
3 | * Author : Mars Kwok
4 | * Date : Jul. 21, 2015
5 | * Description : This is used to watch process dead over api 21
6 | *
7 | * Copyright (C) Mars Kwok
8 | *
9 | */
10 | #include
11 | #include
12 | #include
13 |
14 | #include "com_marswin89_marsdaemon_nativ_NativeDaemonAPI21.h"
15 | #include "log.h"
16 | #include "constant.h"
17 |
18 | void waitfor_self_observer(char* observer_file_path){
19 | int lockFileDescriptor = open(observer_file_path, O_RDONLY);
20 | if (lockFileDescriptor == -1){
21 | LOGE("Watched >>>>OBSERVER<<<< has been ready before watching...");
22 | return ;
23 | }
24 |
25 | void *p_buf = malloc(sizeof(struct inotify_event));
26 | if (p_buf == NULL){
27 | LOGE("malloc failed !!!");
28 | return;
29 | }
30 | int maskStrLength = 7 + 10 + 1;
31 | char *p_maskStr = malloc(maskStrLength);
32 | if (p_maskStr == NULL){
33 | free(p_buf);
34 | LOGE("malloc failed !!!");
35 | return;
36 | }
37 | int fileDescriptor = inotify_init();
38 | if (fileDescriptor < 0){
39 | free(p_buf);
40 | free(p_maskStr);
41 | LOGE("inotify_init failed !!!");
42 | return;
43 | }
44 |
45 | int watchDescriptor = inotify_add_watch(fileDescriptor, observer_file_path, IN_ALL_EVENTS);
46 | if (watchDescriptor < 0){
47 | free(p_buf);
48 | free(p_maskStr);
49 | LOGE("inotify_add_watch failed !!!");
50 | return;
51 | }
52 |
53 |
54 | while(1){
55 | size_t readBytes = read(fileDescriptor, p_buf, sizeof(struct inotify_event));
56 | if (4 == ((struct inotify_event *) p_buf)->mask){
57 | LOGE("Watched >>>>OBSERVER<<<< has been ready...");
58 | free(p_maskStr);
59 | free(p_buf);
60 | return;
61 | }
62 | }
63 | }
64 |
65 | void notify_daemon_observer(unsigned char is_persistent, char* observer_file_path){
66 | if(!is_persistent){
67 | int lockFileDescriptor = open(observer_file_path, O_RDONLY);
68 | while(lockFileDescriptor == -1){
69 | lockFileDescriptor = open(observer_file_path, O_RDONLY);
70 | }
71 | }
72 | remove(observer_file_path);
73 | }
74 |
75 | notify_and_waitfor(char *observer_self_path, char *observer_daemon_path){
76 | int observer_self_descriptor = open(observer_self_path, O_RDONLY);
77 | if (observer_self_descriptor == -1){
78 | observer_self_descriptor = open(observer_self_path, O_CREAT, S_IRUSR | S_IWUSR);
79 | }
80 | int observer_daemon_descriptor = open(observer_daemon_path, O_RDONLY);
81 | while (observer_daemon_descriptor == -1){
82 | usleep(1000);
83 | observer_daemon_descriptor = open(observer_daemon_path, O_RDONLY);
84 | }
85 | remove(observer_daemon_path);
86 | LOGE("Watched >>>>OBSERVER<<<< has been ready...");
87 | }
88 |
89 |
90 | /**
91 | * Lock the file, this is block method.
92 | */
93 | int lock_file(char* lock_file_path){
94 | LOGD("start try to lock file >> %s <<", lock_file_path);
95 | int lockFileDescriptor = open(lock_file_path, O_RDONLY);
96 | if (lockFileDescriptor == -1){
97 | lockFileDescriptor = open(lock_file_path, O_CREAT, S_IRUSR);
98 | }
99 | int lockRet = flock(lockFileDescriptor, LOCK_EX);
100 | if (lockRet == -1){
101 | LOGE("lock file failed >> %s <<", lock_file_path);
102 | return 0;
103 | }else{
104 | LOGD("lock file success >> %s <<", lock_file_path);
105 | return 1;
106 | }
107 | }
108 |
109 |
110 | JNIEXPORT void JNICALL Java_com_marswin89_marsdaemon_nativ_NativeDaemonAPI21_doDaemon(JNIEnv *env, jobject jobj, jstring indicatorSelfPath, jstring indicatorDaemonPath, jstring observerSelfPath, jstring observerDaemonPath){
111 | if(indicatorSelfPath == NULL || indicatorDaemonPath == NULL || observerSelfPath == NULL || observerDaemonPath == NULL){
112 | LOGE("parameters cannot be NULL !");
113 | return ;
114 | }
115 |
116 | char* indicator_self_path = (char*)(*env)->GetStringUTFChars(env, indicatorSelfPath, 0);
117 | char* indicator_daemon_path = (char*)(*env)->GetStringUTFChars(env, indicatorDaemonPath, 0);
118 | char* observer_self_path = (char*)(*env)->GetStringUTFChars(env, observerSelfPath, 0);
119 | char* observer_daemon_path = (char*)(*env)->GetStringUTFChars(env, observerDaemonPath, 0);
120 |
121 | int lock_status = 0;
122 | int try_time = 0;
123 | while(try_time < 3 && !(lock_status = lock_file(indicator_self_path))){
124 | try_time++;
125 | LOGD("Persistent lock myself failed and try again as %d times", try_time);
126 | usleep(10000);
127 | }
128 | if(!lock_status){
129 | LOGE("Persistent lock myself failed and exit");
130 | return ;
131 | }
132 |
133 | // notify_daemon_observer(observer_daemon_path);
134 | // waitfor_self_observer(observer_self_path);
135 | notify_and_waitfor(observer_self_path, observer_daemon_path);
136 |
137 | lock_status = lock_file(indicator_daemon_path);
138 | if(lock_status){
139 | LOGE("Watch >>>>DAEMON<<<<< Daed !!");
140 | remove(observer_self_path);// it`s important ! to prevent from deadlock
141 | java_callback(env, jobj, DAEMON_CALLBACK_NAME);
142 | }
143 |
144 | }
145 |
--------------------------------------------------------------------------------
/LibMarsdaemon/jni/log.h:
--------------------------------------------------------------------------------
1 | /*
2 | * File : daemon_below20.c
3 | * Author : Guoyang3
4 | * Date : Aug. 14, 2015
5 | * Description : for easy log.
6 | */
7 |
8 | #include
9 | #include
10 |
11 | #define TAG "Daemon"
12 |
13 | #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
14 | #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
15 | #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
16 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
--------------------------------------------------------------------------------
/LibMarsdaemon/libs/armeabi-v7a/libdaemon_api20.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/LibMarsdaemon/libs/armeabi-v7a/libdaemon_api20.so
--------------------------------------------------------------------------------
/LibMarsdaemon/libs/armeabi-v7a/libdaemon_api21.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/LibMarsdaemon/libs/armeabi-v7a/libdaemon_api21.so
--------------------------------------------------------------------------------
/LibMarsdaemon/libs/armeabi/libdaemon_api20.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/LibMarsdaemon/libs/armeabi/libdaemon_api20.so
--------------------------------------------------------------------------------
/LibMarsdaemon/libs/armeabi/libdaemon_api21.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/LibMarsdaemon/libs/armeabi/libdaemon_api21.so
--------------------------------------------------------------------------------
/LibMarsdaemon/libs/x86/libdaemon_api20.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/LibMarsdaemon/libs/x86/libdaemon_api20.so
--------------------------------------------------------------------------------
/LibMarsdaemon/libs/x86/libdaemon_api21.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/LibMarsdaemon/libs/x86/libdaemon_api21.so
--------------------------------------------------------------------------------
/LibMarsdaemon/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/guoyang/Developer/android-sdk-macosx/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | -keep class com.marswin89.marsdaemon.NativeDaemonBase{*;}
20 | -keep class com.marswin89.marsdaemon.nativ.NativeDaemonAPI20{*;}
21 | -keep class com.marswin89.marsdaemon.nativ.NativeDaemonAPI21{*;}
22 | -keep class com.marswin89.marsdaemon.DaemonApplication{*;}
23 | -keep class com.marswin89.marsdaemon.DaemonClient{*;}
24 | -keepattributes Exceptions,InnerClasses,...
25 | -keep class com.marswin89.marsdaemon.DaemonConfigurations{*;}
26 | -keep class com.marswin89.marsdaemon.DaemonConfigurations$*{*;}
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/assets/armeabi-v7a/daemon:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/LibMarsdaemon/src/main/assets/armeabi-v7a/daemon
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/assets/armeabi/daemon:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/LibMarsdaemon/src/main/assets/armeabi/daemon
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/assets/x86/daemon:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/LibMarsdaemon/src/main/assets/x86/daemon
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/DaemonApplication.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 | /**
7 | * make your Application extends it
8 | * @author Mars
9 | *
10 | */
11 | public abstract class DaemonApplication extends Application{
12 | /**
13 | * Daemon SDK needs the Daemon Configurations contains two process informations
14 | * see {@link DaemonConfigurations} and {@link DaemonConfigurations.DaemonConfiguration}
15 | *
16 | * @return DaemonConfigurations
17 | */
18 | protected abstract DaemonConfigurations getDaemonConfigurations();
19 |
20 |
21 |
22 | private IDaemonClient mDaemonClient;
23 | public DaemonApplication(){
24 | mDaemonClient = new DaemonClient(getDaemonConfigurations());
25 | }
26 |
27 |
28 | /**
29 | * order to prevent performing super.attachBaseContext() by child class
30 | * if do it, it will cause the IllegalStateException if a base context has already been set.
31 | */
32 | private boolean mHasAttachBaseContext = false;
33 |
34 | @Override
35 | public final void attachBaseContext(Context base) {
36 | if(mHasAttachBaseContext){
37 | return ;
38 | }
39 | mHasAttachBaseContext = true;
40 | super.attachBaseContext(base);
41 | mDaemonClient.onAttachBaseContext(base);
42 | attachBaseContextByDaemon(base);
43 | }
44 |
45 | /**
46 | * instead of {{@link #attachBaseContext(Context)}, you can override this.
47 | * @param base
48 | */
49 | public void attachBaseContextByDaemon(Context base){
50 |
51 | }
52 |
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/DaemonClient.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.File;
5 | import java.io.FileReader;
6 | import java.io.IOException;
7 |
8 | import android.content.Context;
9 | import android.content.SharedPreferences;
10 | import android.content.SharedPreferences.Editor;
11 |
12 | /**
13 | *
14 | * @author Mars
15 | *
16 | */
17 | public class DaemonClient implements IDaemonClient{
18 | private DaemonConfigurations mConfigurations;
19 | public DaemonClient(DaemonConfigurations configurations) {
20 | this.mConfigurations = configurations;
21 | }
22 | @Override
23 | public void onAttachBaseContext(Context base) {
24 | initDaemon(base);
25 | }
26 |
27 |
28 | private final String DAEMON_PERMITTING_SP_FILENAME = "d_permit";
29 | private final String DAEMON_PERMITTING_SP_KEY = "permitted";
30 |
31 |
32 | private BufferedReader mBufferedReader;//release later to save time
33 |
34 |
35 | /**
36 | * do some thing about daemon
37 | * @param base
38 | */
39 | private void initDaemon(Context base) {
40 | if(!isDaemonPermitting(base) || mConfigurations == null){
41 | return ;
42 | }
43 | String processName = getProcessName();
44 | String packageName = base.getPackageName();
45 |
46 | if(processName.startsWith(mConfigurations.PERSISTENT_CONFIG.PROCESS_NAME)){
47 | IDaemonStrategy.Fetcher.fetchStrategy().onPersistentCreate(base, mConfigurations);
48 | }else if(processName.startsWith(mConfigurations.DAEMON_ASSISTANT_CONFIG.PROCESS_NAME)){
49 | IDaemonStrategy.Fetcher.fetchStrategy().onDaemonAssistantCreate(base, mConfigurations);
50 | }else if(processName.startsWith(packageName)){
51 | IDaemonStrategy.Fetcher.fetchStrategy().onInitialization(base);
52 | }
53 |
54 | releaseIO();
55 | }
56 |
57 |
58 | /* spend too much time !! 60+ms
59 | private String getProcessName(){
60 | ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
61 | int pid = android.os.Process.myPid();
62 | List infos = am.getRunningAppProcesses();
63 | for (int i = 0; i < infos.size(); i++) {
64 | RunningAppProcessInfo info = infos.get(i);
65 | if(pid == info.pid){
66 | return info.processName;
67 | }
68 | }
69 | return null;
70 | }
71 | */
72 |
73 | private String getProcessName() {
74 | try {
75 | File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
76 | mBufferedReader = new BufferedReader(new FileReader(file));
77 | return mBufferedReader.readLine();
78 | } catch (Exception e) {
79 | e.printStackTrace();
80 | return null;
81 | }
82 | }
83 |
84 | /**
85 | * release reader IO
86 | */
87 | private void releaseIO(){
88 | if(mBufferedReader != null){
89 | try {
90 | mBufferedReader.close();
91 | } catch (IOException e) {
92 | e.printStackTrace();
93 | }
94 | mBufferedReader = null;
95 | }
96 | }
97 |
98 | private boolean isDaemonPermitting(Context context){
99 | SharedPreferences sp = context.getSharedPreferences(DAEMON_PERMITTING_SP_FILENAME, Context.MODE_PRIVATE);
100 | return sp.getBoolean(DAEMON_PERMITTING_SP_KEY, true);
101 | }
102 |
103 | protected boolean setDaemonPermiiting(Context context, boolean isPermitting) {
104 | SharedPreferences sp = context.getSharedPreferences(DAEMON_PERMITTING_SP_FILENAME, Context.MODE_PRIVATE);
105 | Editor editor = sp.edit();
106 | editor.putBoolean(DAEMON_PERMITTING_SP_KEY, isPermitting);
107 | return editor.commit();
108 | }
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/DaemonConfigurations.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon;
2 |
3 | import android.content.Context;
4 |
5 | /**
6 | * the configurations of Daemon SDK, contains two process configuration.
7 | * @author Mars
8 | *
9 | */
10 | public class DaemonConfigurations {
11 |
12 | public final DaemonConfiguration PERSISTENT_CONFIG;
13 | public final DaemonConfiguration DAEMON_ASSISTANT_CONFIG;
14 | public final DaemonListener LISTENER;
15 |
16 | public DaemonConfigurations(DaemonConfiguration persistentConfig, DaemonConfiguration daemonAssistantConfig){
17 | this.PERSISTENT_CONFIG = persistentConfig;
18 | this.DAEMON_ASSISTANT_CONFIG = daemonAssistantConfig;
19 | this.LISTENER = null;
20 | }
21 |
22 | public DaemonConfigurations(DaemonConfiguration persistentConfig, DaemonConfiguration daemonAssistantConfig, DaemonListener listener){
23 | this.PERSISTENT_CONFIG = persistentConfig;
24 | this.DAEMON_ASSISTANT_CONFIG = daemonAssistantConfig;
25 | this.LISTENER = listener;
26 | }
27 |
28 |
29 |
30 | /**
31 | * the configuration of a daemon process, contains process name, service name and receiver name if Android 6.0
32 | * @author guoyang
33 | *
34 | */
35 | public static class DaemonConfiguration{
36 |
37 | public final String PROCESS_NAME;
38 | public final String SERVICE_NAME;
39 | public final String RECEIVER_NAME;
40 |
41 | public DaemonConfiguration(String processName, String serviceName, String receiverName){
42 | this.PROCESS_NAME = processName;
43 | this.SERVICE_NAME = serviceName;
44 | this.RECEIVER_NAME = receiverName;
45 | }
46 | }
47 |
48 | /**
49 | * listener of daemon for external
50 | *
51 | * @author Mars
52 | *
53 | */
54 | public interface DaemonListener {
55 | void onPersistentStart(Context context);
56 | void onDaemonAssistantStart(Context context);
57 | void onWatchDaemonDaed();
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/IDaemonClient.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon;
2 |
3 | import android.content.Context;
4 |
5 | /**
6 | *
7 | * @author Mars
8 | *
9 | */
10 | public interface IDaemonClient {
11 | /**
12 | * override this method by {@link android.app.Application}
13 | * ****************************************************************
14 | * DO super.attchBaseContext() first !
15 | * ****************************************************************
16 | *
17 | * @param base
18 | */
19 | void onAttachBaseContext(Context base);
20 | }
21 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/IDaemonStrategy.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon;
2 |
3 | import com.marswin89.marsdaemon.strategy.DaemonStrategy21;
4 | import com.marswin89.marsdaemon.strategy.DaemonStrategy22;
5 | import com.marswin89.marsdaemon.strategy.DaemonStrategy23;
6 | import com.marswin89.marsdaemon.strategy.DaemonStrategyUnder21;
7 | import com.marswin89.marsdaemon.strategy.DaemonStrategyXiaomi;
8 |
9 | import android.content.Context;
10 | import android.os.Build;
11 |
12 | /**
13 | * define strategy method
14 | *
15 | * @author Mars
16 | *
17 | */
18 | public interface IDaemonStrategy {
19 | /**
20 | * Initialization some files or other when 1st time
21 | *
22 | * @param context
23 | * @return
24 | */
25 | boolean onInitialization(Context context);
26 |
27 | /**
28 | * when Persistent process create
29 | *
30 | * @param context
31 | * @param configs
32 | */
33 | void onPersistentCreate(Context context, DaemonConfigurations configs);
34 |
35 | /**
36 | * when DaemonAssistant process create
37 | * @param context
38 | * @param configs
39 | */
40 | void onDaemonAssistantCreate(Context context, DaemonConfigurations configs);
41 |
42 | /**
43 | * when watches the process dead which it watched
44 | */
45 | void onDaemonDead();
46 |
47 |
48 |
49 | /**
50 | * all about strategy on different device here
51 | *
52 | * @author Mars
53 | *
54 | */
55 | public static class Fetcher {
56 |
57 | private static IDaemonStrategy mDaemonStrategy;
58 |
59 | /**
60 | * fetch the strategy for this device
61 | *
62 | * @return the daemon strategy for this device
63 | */
64 | static IDaemonStrategy fetchStrategy() {
65 | if (mDaemonStrategy != null) {
66 | return mDaemonStrategy;
67 | }
68 | int sdk = Build.VERSION.SDK_INT;
69 | switch (sdk) {
70 | case 23:
71 | mDaemonStrategy = new DaemonStrategy23();
72 | break;
73 |
74 | case 22:
75 | mDaemonStrategy = new DaemonStrategy22();
76 | break;
77 |
78 | case 21:
79 | if("MX4 Pro".equalsIgnoreCase(Build.MODEL)){
80 | mDaemonStrategy = new DaemonStrategyUnder21();
81 | }else{
82 | mDaemonStrategy = new DaemonStrategy21();
83 | }
84 | break;
85 |
86 | default:
87 | if(Build.MODEL != null && Build.MODEL.toLowerCase().startsWith("mi")){
88 | mDaemonStrategy = new DaemonStrategyXiaomi();
89 | }else if(Build.MODEL != null && Build.MODEL.toLowerCase().startsWith("a31")){
90 | mDaemonStrategy = new DaemonStrategy21();
91 | }else{
92 | mDaemonStrategy = new DaemonStrategyUnder21();
93 | }
94 | break;
95 | }
96 | return mDaemonStrategy;
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/NativeDaemonBase.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon;
2 |
3 | import android.content.Context;
4 |
5 | /**
6 | * native base class
7 | *
8 | * @author Mars
9 | *
10 | */
11 | public class NativeDaemonBase {
12 | /**
13 | * used for native
14 | */
15 | protected Context mContext;
16 |
17 | public NativeDaemonBase(Context context){
18 | this.mContext = context;
19 | }
20 |
21 | /**
22 | * native call back
23 | */
24 | protected void onDaemonDead(){
25 | IDaemonStrategy.Fetcher.fetchStrategy().onDaemonDead();
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/PackageUtils.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon;
2 |
3 | import android.content.ComponentName;
4 | import android.content.Context;
5 | import android.content.pm.PackageManager;
6 |
7 | /**
8 | * Utils to prevent component from third-party app forbidding
9 | *
10 | * @author Mars
11 | *
12 | */
13 | public class PackageUtils {
14 | /**
15 | * set the component in our package default
16 | * @param context
17 | * @param componentClassName
18 | */
19 | public static void setComponentDefault(Context context, String componentClassName){
20 | PackageManager pm = context.getPackageManager();
21 | ComponentName componentName = new ComponentName(context.getPackageName(), componentClassName);
22 | pm.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, PackageManager.DONT_KILL_APP);
23 | }
24 |
25 | /**
26 | * get the component in our package default
27 | * @param context
28 | * @param componentClassName
29 | */
30 | public static boolean isComponentDefault(Context context, String componentClassName){
31 | PackageManager pm = context.getPackageManager();
32 | ComponentName componentName = new ComponentName(context.getPackageName(), componentClassName);
33 | return pm.getComponentEnabledSetting(componentName) == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/nativ/NativeDaemonAPI20.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.nativ;
2 |
3 | import com.marswin89.marsdaemon.NativeDaemonBase;
4 |
5 | import android.content.Context;
6 |
7 | /**
8 | * native code to watch each other when api under 20 (contains 20)
9 | * @author Mars
10 | *
11 | */
12 | public class NativeDaemonAPI20 extends NativeDaemonBase {
13 |
14 | public NativeDaemonAPI20(Context context) {
15 | super(context);
16 | }
17 |
18 | static{
19 | try {
20 | System.loadLibrary("daemon_api20");
21 | } catch (Exception e) {
22 | e.printStackTrace();
23 | }
24 | }
25 |
26 | public native void doDaemon(String pkgName, String svcName, String daemonPath);
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/nativ/NativeDaemonAPI21.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.nativ;
2 |
3 | import com.marswin89.marsdaemon.NativeDaemonBase;
4 |
5 | import android.content.Context;
6 |
7 | /**
8 | * native code to watch each other when api over 21 (contains 21)
9 | * @author Mars
10 | *
11 | */
12 | public class NativeDaemonAPI21 extends NativeDaemonBase{
13 |
14 | public NativeDaemonAPI21(Context context) {
15 | super(context);
16 | }
17 |
18 | static{
19 | try {
20 | System.loadLibrary("daemon_api21");
21 | } catch (Exception e) {
22 | e.printStackTrace();
23 | }
24 | }
25 |
26 | public native void doDaemon(String indicatorSelfPath, String indicatorDaemonPath, String observerSelfPath, String observerDaemonPath);
27 | }
28 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/strategy/DaemonStrategy21.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.strategy;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 |
6 | import android.app.AlarmManager;
7 | import android.app.PendingIntent;
8 | import android.content.ComponentName;
9 | import android.content.Context;
10 | import android.content.Intent;
11 | import android.os.SystemClock;
12 |
13 | import com.marswin89.marsdaemon.DaemonConfigurations;
14 | import com.marswin89.marsdaemon.IDaemonStrategy;
15 | import com.marswin89.marsdaemon.nativ.NativeDaemonAPI21;
16 | /**
17 | * the strategy in android API 21.
18 | *
19 | * @author Mars
20 | *
21 | */
22 | public class DaemonStrategy21 implements IDaemonStrategy{
23 | private final static String INDICATOR_DIR_NAME = "indicators";
24 | private final static String INDICATOR_PERSISTENT_FILENAME = "indicator_p";
25 | private final static String INDICATOR_DAEMON_ASSISTANT_FILENAME = "indicator_d";
26 | private final static String OBSERVER_PERSISTENT_FILENAME = "observer_p";
27 | private final static String OBSERVER_DAEMON_ASSISTANT_FILENAME = "observer_d";
28 |
29 | private AlarmManager mAlarmManager;
30 | private PendingIntent mPendingIntent;
31 | private DaemonConfigurations mConfigs;
32 |
33 | @Override
34 | public boolean onInitialization(Context context) {
35 | return initIndicators(context);
36 | }
37 |
38 | @Override
39 | public void onPersistentCreate(final Context context, DaemonConfigurations configs) {
40 | Intent intent = new Intent();
41 | ComponentName componentName = new ComponentName(context.getPackageName(), configs.DAEMON_ASSISTANT_CONFIG.SERVICE_NAME);
42 | intent.setComponent(componentName);
43 | context.startService(intent);
44 |
45 | initAlarm(context, configs.PERSISTENT_CONFIG.SERVICE_NAME);
46 |
47 | Thread t = new Thread(){
48 | @Override
49 | public void run() {
50 | File indicatorDir = context.getDir(INDICATOR_DIR_NAME, Context.MODE_PRIVATE);
51 | new NativeDaemonAPI21(context).doDaemon(
52 | new File(indicatorDir, INDICATOR_PERSISTENT_FILENAME).getAbsolutePath(),
53 | new File(indicatorDir, INDICATOR_DAEMON_ASSISTANT_FILENAME).getAbsolutePath(),
54 | new File(indicatorDir, OBSERVER_PERSISTENT_FILENAME).getAbsolutePath(),
55 | new File(indicatorDir, OBSERVER_DAEMON_ASSISTANT_FILENAME).getAbsolutePath());
56 | }
57 | };
58 | t.setPriority(Thread.MAX_PRIORITY);
59 | t.start();
60 |
61 | if(configs != null && configs.LISTENER != null){
62 | this.mConfigs = configs;
63 | configs.LISTENER.onPersistentStart(context);
64 | }
65 | }
66 |
67 | @Override
68 | public void onDaemonAssistantCreate(final Context context, DaemonConfigurations configs) {
69 | Intent intent = new Intent();
70 | ComponentName componentName = new ComponentName(context.getPackageName(), configs.PERSISTENT_CONFIG.SERVICE_NAME);
71 | intent.setComponent(componentName);
72 | context.startService(intent);
73 |
74 | initAlarm(context, configs.PERSISTENT_CONFIG.SERVICE_NAME);
75 |
76 | Thread t = new Thread(){
77 | public void run() {
78 | File indicatorDir = context.getDir(INDICATOR_DIR_NAME, Context.MODE_PRIVATE);
79 | new NativeDaemonAPI21(context).doDaemon(
80 | new File(indicatorDir, INDICATOR_DAEMON_ASSISTANT_FILENAME).getAbsolutePath(),
81 | new File(indicatorDir, INDICATOR_PERSISTENT_FILENAME).getAbsolutePath(),
82 | new File(indicatorDir, OBSERVER_DAEMON_ASSISTANT_FILENAME).getAbsolutePath(),
83 | new File(indicatorDir, OBSERVER_PERSISTENT_FILENAME).getAbsolutePath());
84 | };
85 | };
86 | t.setPriority(Thread.MAX_PRIORITY);
87 | t.start();
88 |
89 | if(configs != null && configs.LISTENER != null){
90 | this.mConfigs = configs;
91 | configs.LISTENER.onDaemonAssistantStart(context);
92 | }
93 | }
94 |
95 | @Override
96 | public void onDaemonDead() {
97 | mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 100, mPendingIntent);
98 |
99 | if(mConfigs != null && mConfigs.LISTENER != null){
100 | mConfigs.LISTENER.onWatchDaemonDaed();
101 | }
102 | android.os.Process.killProcess(android.os.Process.myPid());
103 | }
104 |
105 |
106 | private void initAlarm(Context context, String serviceName){
107 | if(mAlarmManager == null){
108 | mAlarmManager = ((AlarmManager)context.getSystemService(Context.ALARM_SERVICE));
109 | }
110 | if(mPendingIntent == null){
111 | Intent intent = new Intent();
112 | ComponentName component = new ComponentName(context.getPackageName(), serviceName);
113 | intent.setComponent(component);
114 | intent.setFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
115 | mPendingIntent = PendingIntent.getService(context, 0, intent, 0);
116 | }
117 | mAlarmManager.cancel(mPendingIntent);
118 | }
119 |
120 |
121 | private boolean initIndicators(Context context){
122 | File dirFile = context.getDir(INDICATOR_DIR_NAME, Context.MODE_PRIVATE);
123 | if(!dirFile.exists()){
124 | dirFile.mkdirs();
125 | }
126 | try {
127 | createNewFile(dirFile, INDICATOR_PERSISTENT_FILENAME);
128 | createNewFile(dirFile, INDICATOR_DAEMON_ASSISTANT_FILENAME);
129 | return true;
130 | } catch (IOException e) {
131 | e.printStackTrace();
132 | return false;
133 | }
134 | }
135 |
136 |
137 | private void createNewFile(File dirFile, String fileName) throws IOException{
138 | File file = new File(dirFile, fileName);
139 | if(!file.exists()){
140 | file.createNewFile();
141 | }
142 | }
143 |
144 | }
145 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/strategy/DaemonStrategy22.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.strategy;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.lang.reflect.Field;
6 | import java.lang.reflect.InvocationTargetException;
7 |
8 | import android.annotation.SuppressLint;
9 | import android.content.ComponentName;
10 | import android.content.Context;
11 | import android.content.Intent;
12 | import android.os.IBinder;
13 | import android.os.Parcel;
14 | import android.os.RemoteException;
15 | import android.util.Log;
16 |
17 | import com.marswin89.marsdaemon.DaemonConfigurations;
18 | import com.marswin89.marsdaemon.IDaemonStrategy;
19 | import com.marswin89.marsdaemon.nativ.NativeDaemonAPI21;
20 | /**
21 | * the strategy in android API 22.
22 | *
23 | * @author Mars
24 | *
25 | */
26 | public class DaemonStrategy22 implements IDaemonStrategy{
27 | private final static String INDICATOR_DIR_NAME = "indicators";
28 | private final static String INDICATOR_PERSISTENT_FILENAME = "indicator_p";
29 | private final static String INDICATOR_DAEMON_ASSISTANT_FILENAME = "indicator_d";
30 | private final static String OBSERVER_PERSISTENT_FILENAME = "observer_p";
31 | private final static String OBSERVER_DAEMON_ASSISTANT_FILENAME = "observer_d";
32 |
33 | private IBinder mRemote;
34 | private Parcel mServiceData;
35 | private DaemonConfigurations mConfigs;
36 |
37 | @Override
38 | public boolean onInitialization(Context context) {
39 | return initIndicatorFiles(context);
40 | }
41 |
42 | @Override
43 | public void onPersistentCreate(final Context context, DaemonConfigurations configs) {
44 | initAmsBinder();
45 | initServiceParcel(context, configs.DAEMON_ASSISTANT_CONFIG.SERVICE_NAME);
46 | startServiceByAmsBinder();
47 |
48 | Thread t = new Thread(){
49 | public void run() {
50 | File indicatorDir = context.getDir(INDICATOR_DIR_NAME, Context.MODE_PRIVATE);
51 | new NativeDaemonAPI21(context).doDaemon(
52 | new File(indicatorDir, INDICATOR_PERSISTENT_FILENAME).getAbsolutePath(),
53 | new File(indicatorDir, INDICATOR_DAEMON_ASSISTANT_FILENAME).getAbsolutePath(),
54 | new File(indicatorDir, OBSERVER_PERSISTENT_FILENAME).getAbsolutePath(),
55 | new File(indicatorDir, OBSERVER_DAEMON_ASSISTANT_FILENAME).getAbsolutePath());
56 | };
57 | };
58 | t.start();
59 |
60 | if(configs != null && configs.LISTENER != null){
61 | this.mConfigs = configs;
62 | configs.LISTENER.onPersistentStart(context);
63 | }
64 | }
65 |
66 | @Override
67 | public void onDaemonAssistantCreate(final Context context, DaemonConfigurations configs) {
68 | initAmsBinder();
69 | initServiceParcel(context, configs.PERSISTENT_CONFIG.SERVICE_NAME);
70 | startServiceByAmsBinder();
71 |
72 | Thread t = new Thread(){
73 | public void run() {
74 | File indicatorDir = context.getDir(INDICATOR_DIR_NAME, Context.MODE_PRIVATE);
75 | new NativeDaemonAPI21(context).doDaemon(
76 | new File(indicatorDir, INDICATOR_DAEMON_ASSISTANT_FILENAME).getAbsolutePath(),
77 | new File(indicatorDir, INDICATOR_PERSISTENT_FILENAME).getAbsolutePath(),
78 | new File(indicatorDir, OBSERVER_DAEMON_ASSISTANT_FILENAME).getAbsolutePath(),
79 | new File(indicatorDir, OBSERVER_PERSISTENT_FILENAME).getAbsolutePath());
80 | };
81 | };
82 | t.start();
83 |
84 | if(configs != null && configs.LISTENER != null){
85 | this.mConfigs = configs;
86 | configs.LISTENER.onDaemonAssistantStart(context);
87 | }
88 |
89 | }
90 |
91 |
92 | @Override
93 | public void onDaemonDead() {
94 | if(startServiceByAmsBinder()){
95 |
96 | if(mConfigs != null && mConfigs.LISTENER != null){
97 | mConfigs.LISTENER.onWatchDaemonDaed();
98 | }
99 |
100 | android.os.Process.killProcess(android.os.Process.myPid());
101 | }
102 | }
103 |
104 |
105 | private void initAmsBinder(){
106 | Class> activityManagerNative;
107 | try {
108 | activityManagerNative = Class.forName("android.app.ActivityManagerNative");
109 | Object amn = activityManagerNative.getMethod("getDefault").invoke(activityManagerNative);
110 | Field mRemoteField = amn.getClass().getDeclaredField("mRemote");
111 | mRemoteField.setAccessible(true);
112 | mRemote = (IBinder) mRemoteField.get(amn);
113 | } catch (ClassNotFoundException e) {
114 | e.printStackTrace();
115 | } catch (IllegalAccessException e) {
116 | e.printStackTrace();
117 | } catch (IllegalArgumentException e) {
118 | e.printStackTrace();
119 | } catch (InvocationTargetException e) {
120 | e.printStackTrace();
121 | } catch (NoSuchMethodException e) {
122 | e.printStackTrace();
123 | } catch (NoSuchFieldException e) {
124 | e.printStackTrace();
125 | }
126 | }
127 |
128 |
129 | @SuppressLint("Recycle")// when process dead, we should save time to restart and kill self, don`t take a waste of time to recycle
130 | private void initServiceParcel(Context context, String serviceName){
131 | Intent intent = new Intent();
132 | ComponentName component = new ComponentName(context.getPackageName(), serviceName);
133 | intent.setComponent(component);
134 |
135 | /*
136 | //get ContextImpl instance
137 | // Object contextImpl = ((Application)context.getApplicationContext()).getBaseContext();
138 | //this context is ContextImpl, get MainThread instance immediately
139 | Field mainThreadField = context.getClass().getDeclaredField("mMainThread");
140 | mainThreadField.setAccessible(true);
141 | Object mainThread = mainThreadField.get(context);
142 | //get ApplicationThread instance
143 | Object applicationThread = mainThread.getClass().getMethod("getApplicationThread").invoke(mainThread);
144 | //get Binder
145 | Binder callerBinder = (Binder) (applicationThread.getClass().getMethod("asBinder").invoke(applicationThread));
146 | */
147 |
148 | //get handle
149 | // UserHandle userHandle = android.os.Process.myUserHandle();
150 | // int handle = (Integer) userHandle.getClass().getMethod("getIdentifier").invoke(userHandle);
151 |
152 | //write pacel
153 | mServiceData = Parcel.obtain();
154 | mServiceData.writeInterfaceToken("android.app.IActivityManager");
155 | mServiceData.writeStrongBinder(null);
156 | // mServiceData.writeStrongBinder(callerBinder);
157 | intent.writeToParcel(mServiceData, 0);
158 | mServiceData.writeString(null);
159 | // mServiceData.writeString(intent.resolveTypeIfNeeded(context.getContentResolver()));
160 | mServiceData.writeInt(0);
161 | // mServiceData.writeInt(handle);
162 |
163 | }
164 |
165 |
166 | private boolean startServiceByAmsBinder(){
167 | try {
168 | if(mRemote == null || mServiceData == null){
169 | Log.e("Daemon", "REMOTE IS NULL or PARCEL IS NULL !!!");
170 | return false;
171 | }
172 | mRemote.transact(34, mServiceData, null, 0);//START_SERVICE_TRANSACTION = 34
173 | return true;
174 | } catch (RemoteException e) {
175 | e.printStackTrace();
176 | return false;
177 | }
178 | }
179 |
180 |
181 |
182 |
183 | private boolean initIndicatorFiles(Context context){
184 | File dirFile = context.getDir(INDICATOR_DIR_NAME, Context.MODE_PRIVATE);
185 | if(!dirFile.exists()){
186 | dirFile.mkdirs();
187 | }
188 | try {
189 | createNewFile(dirFile, INDICATOR_PERSISTENT_FILENAME);
190 | createNewFile(dirFile, INDICATOR_DAEMON_ASSISTANT_FILENAME);
191 | return true;
192 | } catch (IOException e) {
193 | e.printStackTrace();
194 | return false;
195 | }
196 | }
197 |
198 | private void createNewFile(File dirFile, String fileName) throws IOException{
199 | File file = new File(dirFile, fileName);
200 | if(!file.exists()){
201 | file.createNewFile();
202 | }
203 | }
204 | }
205 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/strategy/DaemonStrategy23.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.strategy;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.lang.reflect.Field;
6 | import java.lang.reflect.InvocationTargetException;
7 |
8 | import android.annotation.SuppressLint;
9 | import android.app.Activity;
10 | import android.content.ComponentName;
11 | import android.content.Context;
12 | import android.content.Intent;
13 | import android.os.IBinder;
14 | import android.os.Parcel;
15 | import android.os.RemoteException;
16 | import android.util.Log;
17 |
18 | import com.marswin89.marsdaemon.DaemonConfigurations;
19 | import com.marswin89.marsdaemon.IDaemonStrategy;
20 | import com.marswin89.marsdaemon.nativ.NativeDaemonAPI21;
21 | /**
22 | * the strategy in android API 23.
23 | *
24 | * @author Mars
25 | *
26 | */
27 | public class DaemonStrategy23 implements IDaemonStrategy{
28 | private final static String INDICATOR_DIR_NAME = "indicators";
29 | private final static String INDICATOR_PERSISTENT_FILENAME = "indicator_p";
30 | private final static String INDICATOR_DAEMON_ASSISTANT_FILENAME = "indicator_d";
31 | private final static String OBSERVER_PERSISTENT_FILENAME = "observer_p";
32 | private final static String OBSERVER_DAEMON_ASSISTANT_FILENAME = "observer_d";
33 |
34 | private IBinder mRemote;
35 | private Parcel mBroadcastData;
36 | private DaemonConfigurations mConfigs;
37 |
38 | @Override
39 | public boolean onInitialization(Context context) {
40 | return initIndicatorFiles(context);
41 | }
42 |
43 | @Override
44 | public void onPersistentCreate(final Context context, DaemonConfigurations configs) {
45 | initAmsBinder();
46 | initBroadcastParcel(context, configs.DAEMON_ASSISTANT_CONFIG.RECEIVER_NAME);
47 | sendBroadcastByAmsBinder();
48 |
49 | Thread t = new Thread(){
50 | public void run() {
51 | File indicatorDir = context.getDir(INDICATOR_DIR_NAME, Context.MODE_PRIVATE);
52 | new NativeDaemonAPI21(context).doDaemon(
53 | new File(indicatorDir, INDICATOR_PERSISTENT_FILENAME).getAbsolutePath(),
54 | new File(indicatorDir, INDICATOR_DAEMON_ASSISTANT_FILENAME).getAbsolutePath(),
55 | new File(indicatorDir, OBSERVER_PERSISTENT_FILENAME).getAbsolutePath(),
56 | new File(indicatorDir, OBSERVER_DAEMON_ASSISTANT_FILENAME).getAbsolutePath());
57 | };
58 | };
59 | t.start();
60 |
61 | ComponentName componentName = new ComponentName(context.getPackageName(), configs.PERSISTENT_CONFIG.SERVICE_NAME);
62 | Intent intent = new Intent();
63 | intent.setComponent(componentName);
64 | context.startService(intent);
65 |
66 | if(configs != null && configs.LISTENER != null){
67 | this.mConfigs = configs;
68 | configs.LISTENER.onPersistentStart(context);
69 | }
70 | }
71 |
72 | @Override
73 | public void onDaemonAssistantCreate(final Context context, DaemonConfigurations configs) {
74 | initAmsBinder();
75 | initBroadcastParcel(context, configs.PERSISTENT_CONFIG.RECEIVER_NAME);
76 | sendBroadcastByAmsBinder();
77 |
78 | Thread t = new Thread(){
79 | public void run() {
80 | File indicatorDir = context.getDir(INDICATOR_DIR_NAME, Context.MODE_PRIVATE);
81 | new NativeDaemonAPI21(context).doDaemon(
82 | new File(indicatorDir, INDICATOR_DAEMON_ASSISTANT_FILENAME).getAbsolutePath(),
83 | new File(indicatorDir, INDICATOR_PERSISTENT_FILENAME).getAbsolutePath(),
84 | new File(indicatorDir, OBSERVER_DAEMON_ASSISTANT_FILENAME).getAbsolutePath(),
85 | new File(indicatorDir, OBSERVER_PERSISTENT_FILENAME).getAbsolutePath());
86 | };
87 | };
88 | t.start();
89 |
90 | ComponentName componentName = new ComponentName(context.getPackageName(), configs.DAEMON_ASSISTANT_CONFIG.SERVICE_NAME);
91 | Intent intent = new Intent();
92 | intent.setComponent(componentName);
93 | context.startService(intent);
94 |
95 | if(configs != null && configs.LISTENER != null){
96 | this.mConfigs = configs;
97 | configs.LISTENER.onDaemonAssistantStart(context);
98 | }
99 | }
100 |
101 |
102 | @Override
103 | public void onDaemonDead() {
104 | if(sendBroadcastByAmsBinder()){
105 |
106 | if(mConfigs != null && mConfigs.LISTENER != null){
107 | mConfigs.LISTENER.onWatchDaemonDaed();
108 | }
109 |
110 | android.os.Process.killProcess(android.os.Process.myPid());
111 | }
112 | }
113 |
114 |
115 | private void initAmsBinder(){
116 | Class> activityManagerNative;
117 | try {
118 | activityManagerNative = Class.forName("android.app.ActivityManagerNative");
119 | Object amn = activityManagerNative.getMethod("getDefault").invoke(activityManagerNative);
120 | Field mRemoteField = amn.getClass().getDeclaredField("mRemote");
121 | mRemoteField.setAccessible(true);
122 | mRemote = (IBinder) mRemoteField.get(amn);
123 | } catch (ClassNotFoundException e) {
124 | e.printStackTrace();
125 | } catch (IllegalAccessException e) {
126 | e.printStackTrace();
127 | } catch (IllegalArgumentException e) {
128 | e.printStackTrace();
129 | } catch (InvocationTargetException e) {
130 | e.printStackTrace();
131 | } catch (NoSuchMethodException e) {
132 | e.printStackTrace();
133 | } catch (NoSuchFieldException e) {
134 | e.printStackTrace();
135 | }
136 | }
137 |
138 |
139 | @SuppressLint("Recycle")// when process dead, we should save time to restart and kill self, don`t take a waste of time to recycle
140 | private void initBroadcastParcel(Context context, String broadcastName){
141 | Intent intent = new Intent();
142 | ComponentName componentName = new ComponentName(context.getPackageName(), broadcastName);
143 | intent.setComponent(componentName);
144 | intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
145 |
146 | /*
147 | // Object contextImpl = ((Application)context.getApplicationContext()).getBaseContext();
148 | //this context is ContextImpl, get MainThread instance immediately
149 | Field mainThreadField = context.getClass().getDeclaredField("mMainThread");
150 | mainThreadField.setAccessible(true);
151 | Object mainThread = mainThreadField.get(context);
152 | //get ApplicationThread instance
153 | Object applicationThread = mainThread.getClass().getMethod("getApplicationThread").invoke(mainThread);
154 | //get Binder
155 | Binder callerBinder = (Binder) (applicationThread.getClass().getMethod("asBinder").invoke(applicationThread));
156 | */
157 |
158 | // UserHandle userHandle = android.os.Process.myUserHandle();
159 | // int handle = (Integer) userHandle.getClass().getMethod("getIdentifier").invoke(userHandle);
160 |
161 | mBroadcastData = Parcel.obtain();
162 | mBroadcastData.writeInterfaceToken("android.app.IActivityManager");
163 | // mBroadcastData.writeStrongBinder(callerBinder);
164 | mBroadcastData.writeStrongBinder(null);
165 | intent.writeToParcel(mBroadcastData, 0);
166 | mBroadcastData.writeString(intent.resolveTypeIfNeeded(context.getContentResolver()));
167 | mBroadcastData.writeStrongBinder(null);
168 | mBroadcastData.writeInt(Activity.RESULT_OK);
169 | mBroadcastData.writeString(null);
170 | mBroadcastData.writeBundle(null);
171 | mBroadcastData.writeString(null);
172 | mBroadcastData.writeInt(-1);
173 | mBroadcastData.writeInt(0);
174 | mBroadcastData.writeInt(0);
175 | // mBroadcastData.writeInt(handle);
176 | mBroadcastData.writeInt(0);
177 | }
178 |
179 |
180 | private boolean sendBroadcastByAmsBinder(){
181 |
182 | try {
183 | if(mRemote == null || mBroadcastData == null){
184 | Log.e("Daemon", "REMOTE IS NULL or PARCEL IS NULL !!!");
185 | return false;
186 | }
187 | mRemote.transact(14, mBroadcastData, null, 0);//BROADCAST_INTENT_TRANSACTION = 0x00000001 + 13
188 | return true;
189 | } catch (RemoteException e) {
190 | e.printStackTrace();
191 | return false;
192 | }
193 | }
194 |
195 |
196 |
197 | private boolean initIndicatorFiles(Context context){
198 | File dirFile = context.getDir(INDICATOR_DIR_NAME, Context.MODE_PRIVATE);
199 | if(!dirFile.exists()){
200 | dirFile.mkdirs();
201 | }
202 | try {
203 | createNewFile(dirFile, INDICATOR_PERSISTENT_FILENAME);
204 | createNewFile(dirFile, INDICATOR_DAEMON_ASSISTANT_FILENAME);
205 | return true;
206 | } catch (IOException e) {
207 | e.printStackTrace();
208 | return false;
209 | }
210 | }
211 |
212 | private void createNewFile(File dirFile, String fileName) throws IOException{
213 | File file = new File(dirFile, fileName);
214 | if(!file.exists()){
215 | file.createNewFile();
216 | }
217 | }
218 | }
219 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/strategy/DaemonStrategyUnder21.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.strategy;
2 |
3 | import java.io.File;
4 | import java.io.FileOutputStream;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 |
8 | import android.app.AlarmManager;
9 | import android.app.PendingIntent;
10 | import android.content.ComponentName;
11 | import android.content.Context;
12 | import android.content.Intent;
13 | import android.content.res.AssetManager;
14 | import android.os.Build;
15 | import android.os.SystemClock;
16 | import android.text.TextUtils;
17 |
18 | import com.marswin89.marsdaemon.DaemonConfigurations;
19 | import com.marswin89.marsdaemon.IDaemonStrategy;
20 | import com.marswin89.marsdaemon.nativ.NativeDaemonAPI20;
21 |
22 | /**
23 | * the strategy in android API below 21.
24 | *
25 | * @author Mars
26 | *
27 | */
28 | public class DaemonStrategyUnder21 implements IDaemonStrategy{
29 | private final String BINARY_DEST_DIR_NAME = "bin";
30 | private final String BINARY_FILE_NAME = "daemon";
31 |
32 | private AlarmManager mAlarmManager;
33 | private PendingIntent mPendingIntent;
34 |
35 | @Override
36 | public boolean onInitialization(Context context) {
37 | return installBinary(context);
38 | }
39 |
40 | @Override
41 | public void onPersistentCreate(final Context context, final DaemonConfigurations configs) {
42 | initAlarm(context, configs.DAEMON_ASSISTANT_CONFIG.SERVICE_NAME);
43 | Thread t = new Thread(){
44 | public void run() {
45 | File binaryFile = new File(context.getDir(BINARY_DEST_DIR_NAME, Context.MODE_PRIVATE), BINARY_FILE_NAME);
46 | new NativeDaemonAPI20(context).doDaemon(
47 | context.getPackageName(),
48 | configs.DAEMON_ASSISTANT_CONFIG.SERVICE_NAME,
49 | binaryFile.getAbsolutePath());
50 | };
51 | };
52 | t.setPriority(Thread.MAX_PRIORITY);
53 | t.start();
54 |
55 | if(configs != null && configs.LISTENER != null){
56 | configs.LISTENER.onPersistentStart(context);
57 | }
58 | }
59 |
60 | @Override
61 | public void onDaemonAssistantCreate(Context context, DaemonConfigurations configs) {
62 | Intent intent = new Intent();
63 | ComponentName component = new ComponentName(context.getPackageName(), configs.PERSISTENT_CONFIG.SERVICE_NAME);
64 | intent.setComponent(component);
65 | context.startService(intent);
66 | if(configs != null && configs.LISTENER != null){
67 | configs.LISTENER.onWatchDaemonDaed();
68 | }
69 | android.os.Process.killProcess(android.os.Process.myPid());
70 | }
71 |
72 |
73 | @Override
74 | public void onDaemonDead() {
75 | mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 100, mPendingIntent);
76 | android.os.Process.killProcess(android.os.Process.myPid());
77 | }
78 |
79 |
80 | private void initAlarm(Context context, String serviceName){
81 | if(mAlarmManager == null){
82 | mAlarmManager = ((AlarmManager)context.getSystemService(Context.ALARM_SERVICE));
83 | }
84 | if(mPendingIntent == null){
85 | Intent intent = new Intent();
86 | ComponentName component = new ComponentName(context.getPackageName(), serviceName);
87 | intent.setComponent(component);
88 | intent.setFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
89 | mPendingIntent = PendingIntent.getService(context, 0, intent, 0);
90 | }
91 | mAlarmManager.cancel(mPendingIntent);
92 | }
93 |
94 |
95 | private boolean installBinary(Context context){
96 | String binaryDirName = null;
97 | String abi = Build.CPU_ABI;
98 | if (abi.startsWith("armeabi-v7a")) {
99 | binaryDirName = "armeabi-v7a";
100 | }else if(abi.startsWith("x86")) {
101 | binaryDirName = "x86";
102 | }else{
103 | binaryDirName = "armeabi";
104 | }
105 | return install(context, BINARY_DEST_DIR_NAME, binaryDirName, BINARY_FILE_NAME);
106 | }
107 |
108 |
109 | private boolean install(Context context, String destDirName, String assetsDirName, String filename) {
110 | File file = new File(context.getDir(destDirName, Context.MODE_PRIVATE), filename);
111 | if (file.exists()) {
112 | return true;
113 | }
114 | try {
115 | copyAssets(context, (TextUtils.isEmpty(assetsDirName) ? "" : (assetsDirName + File.separator)) + filename, file, "700");
116 | return true;
117 | } catch (Exception e) {
118 | return false;
119 | }
120 | }
121 |
122 | private void copyAssets(Context context, String assetsFilename, File file, String mode) throws IOException, InterruptedException {
123 | AssetManager manager = context.getAssets();
124 | final InputStream is = manager.open(assetsFilename);
125 | copyFile(file, is, mode);
126 | }
127 |
128 | private void copyFile(File file, InputStream is, String mode) throws IOException, InterruptedException {
129 | if(!file.getParentFile().exists()){
130 | file.getParentFile().mkdirs();
131 | }
132 | final String abspath = file.getAbsolutePath();
133 | final FileOutputStream out = new FileOutputStream(file);
134 | byte buf[] = new byte[1024];
135 | int len;
136 | while ((len = is.read(buf)) > 0) {
137 | out.write(buf, 0, len);
138 | }
139 | out.close();
140 | is.close();
141 | Runtime.getRuntime().exec("chmod " + mode + " " + abspath).waitFor();
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/java/com/marswin89/marsdaemon/strategy/DaemonStrategyXiaomi.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon.strategy;
2 |
3 | import java.io.File;
4 | import java.io.FileOutputStream;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.lang.reflect.Field;
8 | import java.lang.reflect.InvocationTargetException;
9 |
10 | import android.annotation.SuppressLint;
11 | import android.content.ComponentName;
12 | import android.content.Context;
13 | import android.content.Intent;
14 | import android.content.res.AssetManager;
15 | import android.os.IBinder;
16 | import android.os.Parcel;
17 | import android.os.RemoteException;
18 | import android.text.TextUtils;
19 | import android.util.Log;
20 |
21 | import com.marswin89.marsdaemon.DaemonConfigurations;
22 | import com.marswin89.marsdaemon.IDaemonStrategy;
23 | import com.marswin89.marsdaemon.nativ.NativeDaemonAPI20;
24 |
25 | /**
26 | * the strategy in Mi.
27 | *
28 | * @author Mars
29 | *
30 | */
31 | public class DaemonStrategyXiaomi implements IDaemonStrategy{
32 | private final String BINARY_DEST_DIR_NAME = "bin";
33 | private final String BINARY_FILE_NAME = "daemon";
34 |
35 | private IBinder mRemote;
36 | private Parcel mServiceData;
37 | private DaemonConfigurations mConfigs;
38 |
39 | @Override
40 | public boolean onInitialization(Context context) {
41 | return installBinary(context);
42 | }
43 |
44 | @Override
45 | public void onPersistentCreate(final Context context, final DaemonConfigurations configs) {
46 | initAmsBinder();
47 | initServiceParcel(context, configs.DAEMON_ASSISTANT_CONFIG.SERVICE_NAME);
48 | Thread t = new Thread(){
49 | public void run() {
50 | File binaryFile = new File(context.getDir(BINARY_DEST_DIR_NAME, Context.MODE_PRIVATE), BINARY_FILE_NAME);
51 | new NativeDaemonAPI20(context).doDaemon(
52 | context.getPackageName(),
53 | configs.DAEMON_ASSISTANT_CONFIG.SERVICE_NAME,
54 | binaryFile.getAbsolutePath());
55 | };
56 | };
57 | t.setPriority(Thread.MAX_PRIORITY);
58 | t.start();
59 |
60 | if(configs != null && configs.LISTENER != null){
61 | this.mConfigs = configs;
62 | configs.LISTENER.onPersistentStart(context);
63 | }
64 |
65 | }
66 |
67 |
68 | @Override
69 | public void onDaemonAssistantCreate(Context context, DaemonConfigurations configs) {
70 | Intent intent = new Intent();
71 | ComponentName component = new ComponentName(context.getPackageName(), configs.PERSISTENT_CONFIG.SERVICE_NAME);
72 | intent.setComponent(component);
73 | context.startService(intent);
74 | if(configs != null && configs.LISTENER != null){
75 | configs.LISTENER.onWatchDaemonDaed();
76 | }
77 | android.os.Process.killProcess(android.os.Process.myPid());
78 | }
79 |
80 | @Override
81 | public void onDaemonDead() {
82 | if(startServiceByAmsBinder()){
83 |
84 | if(mConfigs != null && mConfigs.LISTENER != null){
85 | mConfigs.LISTENER.onWatchDaemonDaed();
86 | }
87 |
88 | android.os.Process.killProcess(android.os.Process.myPid());
89 | }
90 | }
91 |
92 | private void initAmsBinder(){
93 | Class> activityManagerNative;
94 | try {
95 | activityManagerNative = Class.forName("android.app.ActivityManagerNative");
96 | Object amn = activityManagerNative.getMethod("getDefault").invoke(activityManagerNative);
97 | Field mRemoteField = amn.getClass().getDeclaredField("mRemote");
98 | mRemoteField.setAccessible(true);
99 | mRemote = (IBinder) mRemoteField.get(amn);
100 | } catch (ClassNotFoundException e) {
101 | e.printStackTrace();
102 | } catch (IllegalAccessException e) {
103 | e.printStackTrace();
104 | } catch (IllegalArgumentException e) {
105 | e.printStackTrace();
106 | } catch (InvocationTargetException e) {
107 | e.printStackTrace();
108 | } catch (NoSuchMethodException e) {
109 | e.printStackTrace();
110 | } catch (NoSuchFieldException e) {
111 | e.printStackTrace();
112 | }
113 | }
114 |
115 |
116 | @SuppressLint("Recycle")// when process dead, we should save time to restart and kill self, don`t take a waste of time to recycle
117 | private void initServiceParcel(Context context, String serviceName){
118 | Intent intent = new Intent();
119 | ComponentName component = new ComponentName(context.getPackageName(), serviceName);
120 | intent.setComponent(component);
121 |
122 | /*
123 | //get ContextImpl instance
124 | // Object contextImpl = ((Application)context.getApplicationContext()).getBaseContext();
125 | //this context is ContextImpl, get MainThread instance immediately
126 | Field mainThreadField = context.getClass().getDeclaredField("mMainThread");
127 | mainThreadField.setAccessible(true);
128 | Object mainThread = mainThreadField.get(context);
129 | //get ApplicationThread instance
130 | Object applicationThread = mainThread.getClass().getMethod("getApplicationThread").invoke(mainThread);
131 | //get Binder
132 | Binder callerBinder = (Binder) (applicationThread.getClass().getMethod("asBinder").invoke(applicationThread));
133 | */
134 |
135 | //get handle
136 | // UserHandle userHandle = android.os.Process.myUserHandle();
137 | // int handle = (Integer) userHandle.getClass().getMethod("getIdentifier").invoke(userHandle);
138 |
139 | //write pacel
140 | mServiceData = Parcel.obtain();
141 | mServiceData.writeInterfaceToken("android.app.IActivityManager");
142 | mServiceData.writeStrongBinder(null);
143 | // mServiceData.writeStrongBinder(callerBinder);
144 | intent.writeToParcel(mServiceData, 0);
145 | mServiceData.writeString(null);
146 | // mServiceData.writeString(intent.resolveTypeIfNeeded(context.getContentResolver()));
147 | mServiceData.writeInt(0);
148 | // mServiceData.writeInt(handle);
149 |
150 | }
151 |
152 | private boolean startServiceByAmsBinder(){
153 | try {
154 | if(mRemote == null || mServiceData == null){
155 | Log.e("Daemon", "REMOTE IS NULL or PARCEL IS NULL !!!");
156 | return false;
157 | }
158 | mRemote.transact(34, mServiceData, null, 0);//START_SERVICE_TRANSACTION = 34
159 | return true;
160 | } catch (RemoteException e) {
161 | e.printStackTrace();
162 | return false;
163 | }
164 | }
165 |
166 | private boolean installBinary(Context context){
167 | String binaryDirName = null;
168 | // String abi = Build.CPU_ABI;
169 | // if (abi.startsWith("armeabi-v7a")) {
170 | // binaryDirName = "armeabi-v7a";
171 | // }else if(abi.startsWith("x86")) {
172 | // binaryDirName = "x86";
173 | // }else{
174 | // binaryDirName = "armeabi";
175 | // }
176 | return install(context, BINARY_DEST_DIR_NAME, binaryDirName, BINARY_FILE_NAME);
177 | }
178 |
179 |
180 | private boolean install(Context context, String destDirName, String assetsDirName, String filename) {
181 | File file = new File(context.getDir(destDirName, Context.MODE_PRIVATE), filename);
182 | if (file.exists()) {
183 | return true;
184 | }
185 | try {
186 | copyAssets(context, (TextUtils.isEmpty(assetsDirName) ? "" : (assetsDirName + File.separator)) + filename, file, "700");
187 | return true;
188 | } catch (Exception e) {
189 | return false;
190 | }
191 | }
192 |
193 | private void copyAssets(Context context, String assetsFilename, File file, String mode) throws IOException, InterruptedException {
194 | AssetManager manager = context.getAssets();
195 | final InputStream is = manager.open(assetsFilename);
196 | copyFile(file, is, mode);
197 | }
198 |
199 | private void copyFile(File file, InputStream is, String mode) throws IOException, InterruptedException {
200 | if(!file.getParentFile().exists()){
201 | file.getParentFile().mkdirs();
202 | }
203 | final String abspath = file.getAbsolutePath();
204 | final FileOutputStream out = new FileOutputStream(file);
205 | byte buf[] = new byte[1024];
206 | int len;
207 | while ((len = is.read(buf)) > 0) {
208 | out.write(buf, 0, len);
209 | }
210 | out.close();
211 | is.close();
212 | Runtime.getRuntime().exec("chmod " + mode + " " + abspath).waitFor();
213 | }
214 |
215 | }
216 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Marsdaemon
3 |
4 |
--------------------------------------------------------------------------------
/LibMarsdaemon/src/test/java/com/marswin89/marsdaemon/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.marswin89.marsdaemon;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/Marsdaemon2.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MarsDaemon
2 |
3 | It is a lite library, you can make your project depend it easily, and your project will be UNDEAD.
4 |
5 | * support to keep alive from Android_API 9 to Android_API 23
6 | * support to keep alive in most of devices(contains Sumsung\Huawei\Meizu\Mi\Nexus..)
7 | * support to keep alive in FORCE_CLOSE from SystemSettings and MEMORY_CLEAN from third-part apps (such like CleanMaster\360 and so on)
8 | * support to keep BOOT_RECEIVER work well simplely
9 |
10 | my Blog in Chinese here:
11 | [http://blog.csdn.net/marswin89/article/details/50917098](http://blog.csdn.net/marswin89/article/details/50917098)
12 |
13 |
14 | ### Version
15 | 1.0
16 |
17 | ## Installation
18 | #### STEP1
19 | make your project depend on LibMarsdaemon, and regist 2 Service and 2 BroadcastReceiver in your manifests in 2 different process.
20 |
21 | ```sh
22 |
23 |
24 |
25 |
26 | ```
27 |
28 | Service1 is the Service which you want to be undead, you can do somethings in it.
29 |
30 | But the others is used by Marsdaemon, so DONNOT do anything inside.
31 |
32 | #### STEP2
33 | make your application extends DaemonApplication and override the method getDaemonConfigurations(). Return back the confugirations.
34 | ```sh
35 | @Override
36 | protected DaemonConfigurations getDaemonConfigurations() {
37 | DaemonConfigurations.DaemonConfiguration configuration1 = new DaemonConfigurations.DaemonConfiguration("com.marswin89.marsdaemon.demo:process1", Service1.class.getCanonicalName(), Receiver1.class.getCanonicalName());
38 | DaemonConfigurations.DaemonConfiguration configuration2 = new DaemonConfigurations.DaemonConfiguration("com.marswin89.marsdaemon.demo:process2", Service2.class.getCanonicalName(), Receiver2.class.getCanonicalName());
39 | DaemonConfigurations.DaemonListener listener = new MyDaemonListener();
40 | //return new DaemonConfigurations(configuration1, configuration2);//listener can be null
41 | return new DaemonConfigurations(configuration1, configuration2, listener);
42 | }
43 | ```
44 | if you want to override attachBaseContext you will find it had been defined final by me. you can override attachBaseContextByDaemon instead it.
45 |
46 | see more details in MyApplication1 in Demo
47 |
48 | ##### if your application has extends another application, you should create a DaemonClient and perfrom it in attachBaseContext(), DONOT forget perform super.attachBaseContext() before!
49 |
50 | ```sh
51 | private DaemonClient mDaemonClient;
52 | @Override
53 | protected void attachBaseContext(Context base) {
54 | super.attachBaseContext(base);
55 | mDaemonClient = new DaemonClient(createDaemonConfigurations());
56 | mDaemonClient.onAttachBaseContext(base);
57 | }
58 | ```
59 | see more details in MyApplication2 in DemoMarsdaemon
60 |
61 | #### STEP3
62 | Launch the Service once, and try to kill it.
63 |
64 | ##
65 | ##
66 | ##
67 | ## Contact me
68 | Email: Marswin89@gmail.com
69 |
70 |
71 | ##
72 | ##
73 | ##
74 |
75 | License
76 | ----
77 |
78 | Copyright (C) 2015, Mars Kwok
79 |
80 | Licensed under the Apache License, Version 2.0 (the "License");
81 | you may not use this file except in compliance with the License.
82 | You may obtain a copy of the License at
83 |
84 | http://www.apache.org/licenses/LICENSE-2.0
85 |
86 | Unless required by applicable law or agreed to in writing, software
87 | distributed under the License is distributed on an "AS IS" BASIS,
88 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
89 | See the License for the specific language governing permissions and
90 | limitations under the License.
91 |
92 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:1.3.0'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/build/intermediates/dex-cache/cache.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | -
9 |
10 |
11 | -
16 |
17 |
18 | -
23 |
24 |
25 | -
30 |
31 |
32 | -
37 |
38 |
39 | -
44 |
45 |
46 | -
51 |
52 |
53 | -
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marswin/MarsDaemon/dd04983a389d5db73e18849d8c48a5610cc1e27a/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Oct 21 11:34:03 PDT 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/local.properties:
--------------------------------------------------------------------------------
1 | ## This file is automatically generated by Android Studio.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file should *NOT* be checked into Version Control Systems,
5 | # as it contains information specific to your local configuration.
6 | #
7 | # Location of the SDK. This is only used by Gradle.
8 | # For customization when using a Version Control System, please read the
9 | # header note.
10 | sdk.dir=/Users/guoyang/Developer/android-sdk-macosx
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':DemoMarsdaemon', ':LibMarsdaemon'
2 |
--------------------------------------------------------------------------------