├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ └── styles.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-w820dp
│ │ │ │ └── dimens.xml
│ │ │ └── layout
│ │ │ │ └── activity_main.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── vmloft
│ │ │ │ └── develop
│ │ │ │ └── daemon
│ │ │ │ ├── VMApplication.java
│ │ │ │ ├── services
│ │ │ │ ├── VMBackgroundService.java
│ │ │ │ ├── VMDaemonJobService.java
│ │ │ │ ├── VMForegroundService.java
│ │ │ │ ├── VMCoreService.java
│ │ │ │ └── VMDaemonService.java
│ │ │ │ ├── VMDaemonActivity.java
│ │ │ │ ├── receiver
│ │ │ │ └── VMWakeReceiver.java
│ │ │ │ ├── VMDaemonManager.java
│ │ │ │ └── MainActivity.java
│ │ └── AndroidManifest.xml
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── vmloft
│ │ └── develop
│ │ └── daemon
│ │ └── ExampleInstrumentedTest.java
├── build.gradle
└── proguard-rules.pro
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── README.md
├── gradle.properties
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | VMDaemonServices
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lzan13/VMDaemonServices/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lzan13/VMDaemonServices/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lzan13/VMDaemonServices/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lzan13/VMDaemonServices/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lzan13/VMDaemonServices/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lzan13/VMDaemonServices/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .idea
7 | .DS_Store
8 | *libs
9 | /build
10 | /captures
11 | .externalNativeBuild
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | VMDaemonServices
2 | ----------------
3 |
4 | 测试 android 实现守护进程的几种方式
5 |
6 | 详细介绍可以查看我的博客:【[Android 守护进程的实现方式](http://melove.net/blog/2017/03/android-daemon-service-1488942411000.html)】
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 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.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vmloft/develop/daemon/VMApplication.java:
--------------------------------------------------------------------------------
1 | package com.vmloft.develop.daemon;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 | /**
7 | * Created by lzan13 on 2017/3/9.
8 | */
9 |
10 | public class VMApplication extends Application {
11 |
12 | private static Context context;
13 |
14 | @Override public void onCreate() {
15 | super.onCreate();
16 | context = this;
17 | }
18 |
19 | public static Context getContext() {
20 | return context;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.2"
6 | defaultConfig {
7 | applicationId "com.vmloft.develop.daemon"
8 | minSdkVersion 15
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 | }
20 |
21 | dependencies {
22 | compile fileTree(dir: 'libs', include: ['*.jar'])
23 | compile 'com.android.support:appcompat-v7:25.1.1'
24 | }
25 |
--------------------------------------------------------------------------------
/app/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/lzan13/develop/android/android-sdk/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 |
--------------------------------------------------------------------------------
/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 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/vmloft/develop/daemon/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.vmloft.develop.daemon;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest {
18 | @Test public void useAppContext() throws Exception {
19 | // Context of the app under test.
20 | Context appContext = InstrumentationRegistry.getTargetContext();
21 |
22 | assertEquals("com.vmloft.develop.daemonservices", appContext.getPackageName());
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vmloft/develop/daemon/services/VMBackgroundService.java:
--------------------------------------------------------------------------------
1 | package com.vmloft.develop.daemon.services;
2 |
3 | import android.app.Service;
4 | import android.content.Intent;
5 | import android.os.IBinder;
6 | import android.util.Log;
7 |
8 | /**
9 | * 普通的后台 Service 服务,此类只是为了展示正常服务进程的优先级
10 | *
11 | * Created by lzan13 on 2017/3/7.JobScheduler机制唤醒
12 | */
13 | public class VMBackgroundService extends Service {
14 |
15 | private final static String TAG = VMBackgroundService.class.getSimpleName();
16 |
17 | @Override public void onCreate() {
18 | Log.i(TAG, "onCreate");
19 | super.onCreate();
20 | }
21 |
22 | @Override public IBinder onBind(Intent intent) {
23 | // TODO: Return the communication channel to the service.
24 | throw new UnsupportedOperationException("onBind 未实现");
25 | }
26 |
27 | @Override public void onDestroy() {
28 | Log.i(TAG, "onDestroy");
29 | super.onDestroy();
30 | }
31 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/vmloft/develop/daemon/VMDaemonActivity.java:
--------------------------------------------------------------------------------
1 | package com.vmloft.develop.daemon;
2 |
3 | import android.os.Bundle;
4 | import android.support.annotation.Nullable;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.util.Log;
7 | import android.view.Gravity;
8 | import android.view.Window;
9 | import android.view.WindowManager;
10 |
11 | /**
12 | * Created by lzan13 on 2017/3/9.
13 | */
14 |
15 | public class VMDaemonActivity extends AppCompatActivity {
16 |
17 | @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
18 | super.onCreate(savedInstanceState);
19 | Log.d("lzan13", "VMDaemonActivity -> onCreate");
20 |
21 | Window window = getWindow();
22 | window.setGravity(Gravity.LEFT | Gravity.TOP);
23 | WindowManager.LayoutParams lp = window.getAttributes();
24 | lp.width = 1;
25 | lp.height = 1;
26 |
27 | window.setAttributes(lp);
28 |
29 | VMDaemonManager.getInstance().setDaemonActivity(this);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vmloft/develop/daemon/services/VMDaemonJobService.java:
--------------------------------------------------------------------------------
1 | package com.vmloft.develop.daemon.services;
2 |
3 | import android.annotation.TargetApi;
4 | import android.app.job.JobParameters;
5 | import android.app.job.JobService;
6 | import android.os.Build;
7 | import android.util.Log;
8 | import com.vmloft.develop.daemon.VMDaemonManager;
9 |
10 | /**
11 | * 5.x 以上使用 JobService 实现守护进程,这个守护进程要做的工作很简单,就是启动应用的核心进程
12 | * Created by lzan13 on 2017/3/8.
13 | */
14 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) public class VMDaemonJobService extends JobService {
15 |
16 | private final static String TAG = VMDaemonJobService.class.getSimpleName();
17 |
18 | @Override public boolean onStartJob(JobParameters params) {
19 | Log.d(TAG, "onStartJob");
20 | // 这里为了演示,这里直接启动核心进程,没有做其他判断操作
21 | VMDaemonManager.getInstance().startCoreProcess();
22 | return false;
23 | }
24 |
25 | @Override public boolean onStopJob(JobParameters params) {
26 | Log.d(TAG, "onStopJob");
27 | return false;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vmloft/develop/daemon/receiver/VMWakeReceiver.java:
--------------------------------------------------------------------------------
1 | package com.vmloft.develop.daemon.receiver;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.util.Log;
7 | import com.vmloft.develop.daemon.VMDaemonManager;
8 |
9 | /**
10 | * 接收唤醒应用核心服务的广播接收器,接收守护进程发送过来的广播
11 | *
12 | * Created by lzan13 on 2017/3/7.
13 | */
14 | public class VMWakeReceiver extends BroadcastReceiver {
15 |
16 | private final static String TAG = VMWakeReceiver.class.getSimpleName();
17 |
18 | // 定义守护进程发送唤醒广播的 Action
19 | public final static String DAEMON_WAKE_ACTION = "com.vmloft.develop.daemon.wake";
20 |
21 | @Override public void onReceive(Context context, Intent intent) {
22 | String action = intent.getAction();
23 | if (action.equals(DAEMON_WAKE_ACTION)) {
24 | Log.i(TAG, "onReceive: 起床了!");
25 | // 接收到守护进程发送的广播,开始启动核心进程
26 | VMDaemonManager.getInstance().startCoreProcess();
27 | } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
28 | Log.i(TAG, "onReceive: 锁屏了!");
29 | // 检测到锁屏,启动一像素的流氓 Activity
30 | VMDaemonManager.getInstance().startDaemonActivity();
31 | } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
32 | Log.i(TAG, "onReceive: 解锁了!");
33 | // 解锁后,结束一像素的流氓 Activity
34 | VMDaemonManager.getInstance().finishDaemonActivity();
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
14 |
19 |
25 |
26 |
32 |
33 |
39 |
40 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vmloft/develop/daemon/VMDaemonManager.java:
--------------------------------------------------------------------------------
1 | package com.vmloft.develop.daemon;
2 |
3 | import android.content.Intent;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.util.Log;
6 | import com.vmloft.develop.daemon.services.VMCoreService;
7 |
8 | /**
9 | * 守护进程管理类
10 | * Created by lzan13 on 2017/3/9.
11 | */
12 | public class VMDaemonManager {
13 |
14 | private final static String TAG = VMDaemonManager.class.getSimpleName();
15 |
16 | private static VMDaemonManager instance = null;
17 |
18 | private AppCompatActivity daemonActivity;
19 |
20 | private VMDaemonManager() {
21 | }
22 |
23 | /**
24 | * 获取单例类实例
25 | */
26 | public static VMDaemonManager getInstance() {
27 | if (instance == null) {
28 | instance = new VMDaemonManager();
29 | }
30 | return instance;
31 | }
32 |
33 | /**
34 | * 启动守护 Activity,其实就是一像素大小的流氓 activity
35 | */
36 | public void startDaemonActivity() {
37 | Log.i(TAG, "startCoreProcess: 启动流氓 Activity");
38 | VMApplication.getContext()
39 | .startActivity(new Intent(VMApplication.getContext(), VMDaemonActivity.class));
40 | }
41 |
42 | /**
43 | * 结束流氓的 activity
44 | */
45 | public void finishDaemonActivity() {
46 | Log.i(TAG, "startCoreProcess: 结束流氓 Activity");
47 | if (daemonActivity != null) {
48 | daemonActivity.finish();
49 | }
50 | }
51 |
52 | /**
53 | * 启动核心进程
54 | */
55 | public void startCoreProcess() {
56 | Log.i(TAG, "startCoreProcess: 启动核心进程");
57 | Intent wakeIntent = new Intent(VMApplication.getContext(), VMCoreService.class);
58 | VMApplication.getContext().startService(wakeIntent);
59 | }
60 |
61 | /**
62 | * 保存当前启动的一像素 Activity
63 | */
64 | public void setDaemonActivity(AppCompatActivity daemonActivity) {
65 | this.daemonActivity = daemonActivity;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vmloft/develop/daemon/services/VMForegroundService.java:
--------------------------------------------------------------------------------
1 | package com.vmloft.develop.daemon.services;
2 |
3 | import android.app.Notification;
4 | import android.app.PendingIntent;
5 | import android.app.Service;
6 | import android.content.Intent;
7 | import android.os.IBinder;
8 | import android.support.v7.app.NotificationCompat;
9 | import android.util.Log;
10 | import com.vmloft.develop.daemon.MainActivity;
11 | import com.vmloft.develop.daemon.R;
12 |
13 | /**
14 | * 正常的系统前台进程,会在系统通知栏显示一个Notification通知图标,因为这个通知的关系,应用的进程优先级是比较高的,
15 | * 一般系统的内存回收是无法杀死的
16 | *
17 | * Created by lzan13 on 2017/3/7.
18 | */
19 | public class VMForegroundService extends Service {
20 |
21 | private final static String TAG = VMForegroundService.class.getSimpleName();
22 |
23 | // 通知栏发送的通知 id
24 | private final static int NOTIFY_ID = 1000;
25 |
26 | @Override public void onCreate() {
27 | Log.i(TAG, "VMForegroundService->onCreate");
28 | super.onCreate();
29 | }
30 |
31 | @Override public int onStartCommand(Intent intent, int flags, int startId) {
32 | Log.i(TAG, "VMForegroundService->onStartCommand");
33 |
34 | // 创建个通知,这样可以提高服务的优先级
35 | NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
36 | builder.setSmallIcon(R.mipmap.ic_launcher);
37 | builder.setContentTitle("这是一条前台通知");
38 | builder.setContentText("这是一条前台通知,表示当前程序有一个前台服务在运行");
39 | builder.setContentInfo("前台服务");
40 | builder.setWhen(System.currentTimeMillis());
41 | Intent activityIntent = new Intent(this, MainActivity.class);
42 | PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, activityIntent,
43 | PendingIntent.FLAG_UPDATE_CURRENT);
44 | builder.setContentIntent(pendingIntent);
45 | Notification notification = builder.build();
46 | // 开启前台通知
47 | startForeground(NOTIFY_ID, notification);
48 | return super.onStartCommand(intent, flags, startId);
49 | }
50 |
51 | @Override public IBinder onBind(Intent intent) {
52 | // TODO: Return the communication channel to the service.
53 | throw new UnsupportedOperationException("onBind 未实现");
54 | }
55 |
56 | @Override public void onDestroy() {
57 | Log.i(TAG, "VMForegroundService->onDestroy");
58 | super.onDestroy();
59 | }
60 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vmloft/develop/daemon/services/VMCoreService.java:
--------------------------------------------------------------------------------
1 | package com.vmloft.develop.daemon.services;
2 |
3 | import android.app.Notification;
4 | import android.app.Service;
5 | import android.content.Intent;
6 | import android.os.Build;
7 | import android.os.IBinder;
8 | import android.util.Log;
9 |
10 | /**
11 | * 用于其他进程来唤醒UI进程用的 Service
12 | *
13 | * Created by lzan13 on 2017/3/9.
14 | */
15 |
16 | public class VMCoreService extends Service {
17 |
18 | private final static String TAG = VMCoreService.class.getSimpleName();
19 | // 核心进程 Service ID
20 | private final static int CORE_SERVICE_ID = -5120;
21 |
22 | @Override public void onCreate() {
23 | Log.i(TAG, "VMCoreService -> onCreate");
24 | super.onCreate();
25 | }
26 |
27 | @Override public int onStartCommand(Intent intent, int flags, int startId) {
28 | Log.i(TAG, "VMCoreService -> onStartCommand");
29 | // 利用 Android 漏洞提高进程优先级,
30 | startForeground(CORE_SERVICE_ID, new Notification());
31 | // 当 SDk 版本大于18时,需要通过内部 Service 类启动同样 id 的 Service
32 | if (Build.VERSION.SDK_INT >= 18) {
33 | Intent innerIntent = new Intent(this, CoreInnerService.class);
34 | startService(innerIntent);
35 | }
36 | return START_STICKY;
37 | }
38 |
39 | @Override public IBinder onBind(Intent intent) {
40 | // TODO: Return the communication channel to the service.
41 | throw new UnsupportedOperationException("Not yet implemented");
42 | }
43 |
44 | @Override public void onDestroy() {
45 | Log.i(TAG, "VMCoreService -> onDestroy");
46 | super.onDestroy();
47 | }
48 |
49 | /**
50 | * 实现一个内部的 Service,实现让后台服务的优先级提高到前台服务,这里利用了 android 系统的漏洞,
51 | * 不保证所有系统可用,测试在7.1.1 之前大部分系统都是可以的,不排除个别厂商优化限制
52 | */
53 | public static class CoreInnerService extends Service {
54 |
55 | @Override public void onCreate() {
56 | Log.i(TAG, "CoreInnerService -> onCreate");
57 | super.onCreate();
58 | }
59 |
60 | @Override public int onStartCommand(Intent intent, int flags, int startId) {
61 | Log.i(TAG, "CoreInnerService -> onStartCommand");
62 | startForeground(CORE_SERVICE_ID, new Notification());
63 | stopSelf();
64 | return super.onStartCommand(intent, flags, startId);
65 | }
66 |
67 | @Override public IBinder onBind(Intent intent) {
68 | // TODO: Return the communication channel to the service.
69 | throw new UnsupportedOperationException("Not yet implemented");
70 | }
71 |
72 | @Override public void onDestroy() {
73 | Log.i(TAG, "CoreInnerService -> onDestroy");
74 | super.onDestroy();
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vmloft/develop/daemon/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.vmloft.develop.daemon;
2 |
3 | import android.annotation.TargetApi;
4 | import android.app.job.JobInfo;
5 | import android.app.job.JobScheduler;
6 | import android.content.ComponentName;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.os.Build;
10 | import android.support.v7.app.AppCompatActivity;
11 | import android.os.Bundle;
12 | import android.view.View;
13 | import com.vmloft.develop.daemon.services.VMBackgroundService;
14 | import com.vmloft.develop.daemon.services.VMCoreService;
15 | import com.vmloft.develop.daemon.services.VMDaemonJobService;
16 | import com.vmloft.develop.daemon.services.VMDaemonService;
17 | import com.vmloft.develop.daemon.services.VMForegroundService;
18 |
19 | public class MainActivity extends AppCompatActivity {
20 |
21 | @Override protected void onCreate(Bundle savedInstanceState) {
22 | super.onCreate(savedInstanceState);
23 | setContentView(R.layout.activity_main);
24 |
25 | findViewById(R.id.btn_foreground).setOnClickListener(viewListener);
26 | findViewById(R.id.btn_daemon).setOnClickListener(viewListener);
27 | findViewById(R.id.btn_background).setOnClickListener(viewListener);
28 | findViewById(R.id.btn_job_service).setOnClickListener(viewListener);
29 |
30 | // 启动核心进程
31 | startCoreProcess();
32 | }
33 |
34 | /**
35 | * 点击事件监听
36 | */
37 | private View.OnClickListener viewListener = new View.OnClickListener() {
38 | @Override public void onClick(View v) {
39 | switch (v.getId()) {
40 | case R.id.btn_foreground:
41 | Intent foregroundIntent =
42 | new Intent(getApplicationContext(), VMForegroundService.class);
43 | startService(foregroundIntent);
44 | break;
45 | case R.id.btn_daemon:
46 | Intent daemonIntent =
47 | new Intent(getApplicationContext(), VMDaemonService.class);
48 | startService(daemonIntent);
49 | break;
50 | case R.id.btn_background:
51 | Intent backgroundIntent =
52 | new Intent(getApplicationContext(), VMBackgroundService.class);
53 | startService(backgroundIntent);
54 | break;
55 | case R.id.btn_job_service:
56 | startJobScheduler();
57 | break;
58 | }
59 | }
60 | };
61 |
62 | /**
63 | * 5.x以上系统启用 JobScheduler API 进行实现守护进程的唤醒操作
64 | */
65 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void startJobScheduler() {
66 | int jobId = 1;
67 | JobInfo.Builder jobInfo =
68 | new JobInfo.Builder(jobId, new ComponentName(this, VMDaemonJobService.class));
69 | jobInfo.setPeriodic(10000);
70 | jobInfo.setPersisted(true);
71 | JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
72 | jobScheduler.schedule(jobInfo.build());
73 | }
74 |
75 | /**
76 | * 启动核心进程
77 | */
78 | private void startCoreProcess() {
79 | startService(new Intent(getApplicationContext(), VMCoreService.class));
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
32 |
33 |
34 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
51 |
52 |
53 |
58 |
63 |
64 |
65 |
70 |
71 |
72 |
76 |
80 |
81 |
82 |
88 |
89 |
90 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vmloft/develop/daemon/services/VMDaemonService.java:
--------------------------------------------------------------------------------
1 | package com.vmloft.develop.daemon.services;
2 |
3 | import android.app.AlarmManager;
4 | import android.app.Notification;
5 | import android.app.PendingIntent;
6 | import android.app.Service;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.os.Build;
10 | import android.os.IBinder;
11 | import android.util.Log;
12 | import com.vmloft.develop.daemon.receiver.VMWakeReceiver;
13 |
14 | /**
15 | * 以实现内部 Service 类的方式实现守护进程,这里是利用 android 漏洞提高当前进程优先级
16 | *
17 | * Created by lzan13 on 2017/3/7.
18 | */
19 | public class VMDaemonService extends Service {
20 |
21 | private final static String TAG = VMDaemonService.class.getSimpleName();
22 |
23 | // 定时唤醒的时间间隔,这里为了自己测试方边设置了一分钟
24 | private final static int ALARM_INTERVAL = 1 * 60 * 1000;
25 | // 发送唤醒广播请求码
26 | private final static int WAKE_REQUEST_CODE = 5121;
27 | // 守护进程 Service ID
28 | private final static int DAEMON_SERVICE_ID = -5121;
29 |
30 | @Override public void onCreate() {
31 | Log.i(TAG, "VMDaemonService->onCreate");
32 | super.onCreate();
33 | }
34 |
35 | @Override public int onStartCommand(Intent intent, int flags, int startId) {
36 | Log.i(TAG, "VMDaemonService->onStartCommand");
37 | // 利用 Android 漏洞提高进程优先级,
38 | startForeground(DAEMON_SERVICE_ID, new Notification());
39 | // 当 SDk 版本大于18时,需要通过内部 Service 类启动同样 id 的 Service
40 | if (Build.VERSION.SDK_INT >= 18) {
41 | Intent innerIntent = new Intent(this, DaemonInnerService.class);
42 | startService(innerIntent);
43 | }
44 |
45 | // 发送唤醒广播来促使挂掉的UI进程重新启动起来
46 | AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
47 | Intent alarmIntent = new Intent();
48 | alarmIntent.setAction(VMWakeReceiver.DAEMON_WAKE_ACTION);
49 |
50 | PendingIntent operation = PendingIntent.getBroadcast(this, WAKE_REQUEST_CODE, alarmIntent,
51 | PendingIntent.FLAG_UPDATE_CURRENT);
52 |
53 | alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
54 | ALARM_INTERVAL, operation);
55 |
56 | /**
57 | * 这里返回值是使用系统 Service 的机制自动重新启动,不过这种方式以下两种方式不适用:
58 | * 1.Service 第一次被异常杀死后会在5秒内重启,第二次被杀死会在10秒内重启,第三次会在20秒内重启,一旦在短时间内 Service 被杀死达到5次,则系统不再拉起。
59 | * 2.进程被取得 Root 权限的管理工具或系统工具通过 forestop 停止掉,无法重启。
60 | */
61 | return START_STICKY;
62 | }
63 |
64 | @Override public IBinder onBind(Intent intent) {
65 | // TODO: Return the communication channel to the service.
66 | throw new UnsupportedOperationException("onBind 未实现");
67 | }
68 |
69 | @Override public void onDestroy() {
70 | Log.i(TAG, "VMDaemonService->onDestroy");
71 | super.onDestroy();
72 | }
73 |
74 | /**
75 | * 实现一个内部的 Service,实现让后台服务的优先级提高到前台服务,这里利用了 android 系统的漏洞,
76 | * 不保证所有系统可用,测试在7.1.1 之前大部分系统都是可以的,不排除个别厂商优化限制
77 | */
78 | public static class DaemonInnerService extends Service {
79 |
80 | @Override public void onCreate() {
81 | Log.i(TAG, "DaemonInnerService -> onCreate");
82 | super.onCreate();
83 | }
84 |
85 | @Override public int onStartCommand(Intent intent, int flags, int startId) {
86 | Log.i(TAG, "DaemonInnerService -> onStartCommand");
87 | startForeground(DAEMON_SERVICE_ID, new Notification());
88 | stopSelf();
89 | return super.onStartCommand(intent, flags, startId);
90 | }
91 |
92 | @Override public IBinder onBind(Intent intent) {
93 | // TODO: Return the communication channel to the service.
94 | throw new UnsupportedOperationException("onBind 未实现");
95 | }
96 |
97 | @Override public void onDestroy() {
98 | Log.i(TAG, "DaemonInnerService -> onDestroy");
99 | super.onDestroy();
100 | }
101 | }
102 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------