Browse Source

Automatic Commit By liuyuqi

liuyuqi-dellpc 4 years ago
parent
commit
554f94eb01
35 changed files with 1102 additions and 0 deletions
  1. 11 0
      as/.gitignore
  2. 6 0
      as/README.md
  3. 1 0
      as/app/.gitignore
  4. 24 0
      as/app/build.gradle
  5. 17 0
      as/app/proguard-rules.pro
  6. 24 0
      as/app/src/androidTest/java/com/vmloft/develop/daemon/ExampleInstrumentedTest.java
  7. 90 0
      as/app/src/main/AndroidManifest.xml
  8. 81 0
      as/app/src/main/java/com/vmloft/develop/daemon/MainActivity.java
  9. 22 0
      as/app/src/main/java/com/vmloft/develop/daemon/VMApplication.java
  10. 31 0
      as/app/src/main/java/com/vmloft/develop/daemon/VMDaemonActivity.java
  11. 67 0
      as/app/src/main/java/com/vmloft/develop/daemon/VMDaemonManager.java
  12. 37 0
      as/app/src/main/java/com/vmloft/develop/daemon/receiver/VMWakeReceiver.java
  13. 31 0
      as/app/src/main/java/com/vmloft/develop/daemon/services/VMBackgroundService.java
  14. 77 0
      as/app/src/main/java/com/vmloft/develop/daemon/services/VMCoreService.java
  15. 29 0
      as/app/src/main/java/com/vmloft/develop/daemon/services/VMDaemonJobService.java
  16. 102 0
      as/app/src/main/java/com/vmloft/develop/daemon/services/VMDaemonService.java
  17. 60 0
      as/app/src/main/java/com/vmloft/develop/daemon/services/VMForegroundService.java
  18. 47 0
      as/app/src/main/res/layout/activity_main.xml
  19. BIN
      as/app/src/main/res/mipmap-hdpi/ic_launcher.png
  20. BIN
      as/app/src/main/res/mipmap-mdpi/ic_launcher.png
  21. BIN
      as/app/src/main/res/mipmap-xhdpi/ic_launcher.png
  22. BIN
      as/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
  23. BIN
      as/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
  24. 6 0
      as/app/src/main/res/values-w820dp/dimens.xml
  25. 6 0
      as/app/src/main/res/values/colors.xml
  26. 5 0
      as/app/src/main/res/values/dimens.xml
  27. 3 0
      as/app/src/main/res/values/strings.xml
  28. 28 0
      as/app/src/main/res/values/styles.xml
  29. 23 0
      as/build.gradle
  30. 17 0
      as/gradle.properties
  31. BIN
      as/gradle/wrapper/gradle-wrapper.jar
  32. 6 0
      as/gradle/wrapper/gradle-wrapper.properties
  33. 160 0
      as/gradlew
  34. 90 0
      as/gradlew.bat
  35. 1 0
      as/settings.gradle

+ 11 - 0
as/.gitignore

@@ -0,0 +1,11 @@
+*.iml
+.gradle
+/local.properties
+/.idea/workspace.xml
+/.idea/libraries
+.idea
+.DS_Store
+*libs
+/build
+/captures
+.externalNativeBuild

+ 6 - 0
as/README.md

@@ -0,0 +1,6 @@
+VMDaemonServices
+----------------
+
+测试 android 实现守护进程的几种方式
+
+详细介绍可以查看我的博客:【[Android 守护进程的实现方式](http://melove.net/blog/2017/03/android-daemon-service-1488942411000.html)】

+ 1 - 0
as/app/.gitignore

@@ -0,0 +1 @@
+/build

+ 24 - 0
as/app/build.gradle

@@ -0,0 +1,24 @@
+apply plugin: 'com.android.application'
+
+android {
+    compileSdkVersion 25
+    buildToolsVersion "25.0.2"
+    defaultConfig {
+        applicationId "com.vmloft.develop.daemon"
+        minSdkVersion 15
+        targetSdkVersion 23
+        versionCode 1
+        versionName "1.0"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+}
+
+dependencies {
+    compile fileTree(dir: 'libs', include: ['*.jar'])
+    compile 'com.android.support:appcompat-v7:25.1.1'
+}

+ 17 - 0
as/app/proguard-rules.pro

@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /Users/lzan13/develop/android/android-sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}

+ 24 - 0
as/app/src/androidTest/java/com/vmloft/develop/daemon/ExampleInstrumentedTest.java

@@ -0,0 +1,24 @@
+package com.vmloft.develop.daemon;
+
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.*;
+
+/**
+ * Instrumentation test, which will execute on an Android device.
+ *
+ * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
+ */
+@RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest {
+    @Test public void useAppContext() throws Exception {
+        // Context of the app under test.
+        Context appContext = InstrumentationRegistry.getTargetContext();
+
+        assertEquals("com.vmloft.develop.daemonservices", appContext.getPackageName());
+    }
+}

+ 90 - 0
as/app/src/main/AndroidManifest.xml

@@ -0,0 +1,90 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.vmloft.develop.daemon">
+
+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
+
+    <application
+        android:name=".VMApplication"
+        android:allowBackup="true"
+        android:icon="@mipmap/ic_launcher"
+        android:label="@string/app_name"
+        android:supportsRtl="true"
+        android:theme="@style/AppTheme">
+        <activity android:name="com.vmloft.develop.daemon.MainActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
+
+        <!--一像素守护 Activity-->
+        <activity
+            android:name=".VMDaemonActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize|navigation|keyboard"
+            android:excludeFromRecents="true"
+            android:exported="false"
+            android:finishOnTaskLaunch="false"
+            android:launchMode="singleInstance"
+            android:process=":daemon"
+            android:theme="@style/AppTheme.Daemon"/>
+
+        <!--接收守护进程发送广播,用来唤醒核心进程的广播接收器-->
+        <receiver
+            android:name="com.vmloft.develop.daemon.receiver.VMWakeReceiver"
+            android:enabled="true"
+            android:exported="false">
+            <intent-filter>
+                <action android:name="com.vmloft.develop.daemon.wake"/>
+                <action android:name="android.intent.action.SCREEN_OFF"/>
+                <action android:name="android.intent.action.USER_PRESENT"/>
+            </intent-filter>
+        </receiver>
+
+        <!--普通前台进程-->
+        <service
+            android:name="com.vmloft.develop.daemon.services.VMForegroundService"
+            android:enabled="true"
+            android:exported="false"
+            android:process=":foreground"/>
+
+        <!--守护进程-->
+        <service
+            android:name="com.vmloft.develop.daemon.services.VMDaemonService"
+            android:enabled="true"
+            android:exported="false"
+            android:process=":daemon"/>
+        <service
+            android:name="com.vmloft.develop.daemon.services.VMDaemonService$DaemonInnerService"
+            android:enabled="true"
+            android:exported="false"
+            android:process=":daemon"/>
+
+        <!--普通后台进程-->
+        <service
+            android:name="com.vmloft.develop.daemon.services.VMBackgroundService"
+            android:enabled="true"
+            android:exported="false"
+            android:process=":background"/>
+
+        <!--核心进程-->
+        <service
+            android:name="com.vmloft.develop.daemon.services.VMCoreService"
+            android:enabled="true"
+            android:exported="false"/>
+        <service
+            android:name="com.vmloft.develop.daemon.services.VMCoreService$CoreInnerService"
+            android:enabled="true"
+            android:exported="false"/>
+
+        <!--5.x 以上使用 JobService-->
+        <service
+            android:name=".services.VMDaemonJobService"
+            android:enabled="true"
+            android:exported="false"
+            android:permission="android.permission.BIND_JOB_SERVICE"
+            android:process=":daemonjob"/>
+    </application>
+
+</manifest>

+ 81 - 0
as/app/src/main/java/com/vmloft/develop/daemon/MainActivity.java

@@ -0,0 +1,81 @@
+package com.vmloft.develop.daemon;
+
+import android.annotation.TargetApi;
+import android.app.job.JobInfo;
+import android.app.job.JobScheduler;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Build;
+import android.support.v7.app.AppCompatActivity;
+import android.os.Bundle;
+import android.view.View;
+import com.vmloft.develop.daemon.services.VMBackgroundService;
+import com.vmloft.develop.daemon.services.VMCoreService;
+import com.vmloft.develop.daemon.services.VMDaemonJobService;
+import com.vmloft.develop.daemon.services.VMDaemonService;
+import com.vmloft.develop.daemon.services.VMForegroundService;
+
+public class MainActivity extends AppCompatActivity {
+
+    @Override protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
+
+        findViewById(R.id.btn_foreground).setOnClickListener(viewListener);
+        findViewById(R.id.btn_daemon).setOnClickListener(viewListener);
+        findViewById(R.id.btn_background).setOnClickListener(viewListener);
+        findViewById(R.id.btn_job_service).setOnClickListener(viewListener);
+
+        // 启动核心进程
+        startCoreProcess();
+    }
+
+    /**
+     * 点击事件监听
+     */
+    private View.OnClickListener viewListener = new View.OnClickListener() {
+        @Override public void onClick(View v) {
+            switch (v.getId()) {
+                case R.id.btn_foreground:
+                    Intent foregroundIntent =
+                            new Intent(getApplicationContext(), VMForegroundService.class);
+                    startService(foregroundIntent);
+                    break;
+                case R.id.btn_daemon:
+                    Intent daemonIntent =
+                            new Intent(getApplicationContext(), VMDaemonService.class);
+                    startService(daemonIntent);
+                    break;
+                case R.id.btn_background:
+                    Intent backgroundIntent =
+                            new Intent(getApplicationContext(), VMBackgroundService.class);
+                    startService(backgroundIntent);
+                    break;
+                case R.id.btn_job_service:
+                    startJobScheduler();
+                    break;
+            }
+        }
+    };
+
+    /**
+     * 5.x以上系统启用 JobScheduler API 进行实现守护进程的唤醒操作
+     */
+    @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void startJobScheduler() {
+        int jobId = 1;
+        JobInfo.Builder jobInfo =
+                new JobInfo.Builder(jobId, new ComponentName(this, VMDaemonJobService.class));
+        jobInfo.setPeriodic(10000);
+        jobInfo.setPersisted(true);
+        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
+        jobScheduler.schedule(jobInfo.build());
+    }
+
+    /**
+     * 启动核心进程
+     */
+    private void startCoreProcess() {
+        startService(new Intent(getApplicationContext(), VMCoreService.class));
+    }
+}

+ 22 - 0
as/app/src/main/java/com/vmloft/develop/daemon/VMApplication.java

@@ -0,0 +1,22 @@
+package com.vmloft.develop.daemon;
+
+import android.app.Application;
+import android.content.Context;
+
+/**
+ * Created by lzan13 on 2017/3/9.
+ */
+
+public class VMApplication extends Application {
+
+    private static Context context;
+
+    @Override public void onCreate() {
+        super.onCreate();
+        context = this;
+    }
+
+    public static Context getContext() {
+        return context;
+    }
+}

+ 31 - 0
as/app/src/main/java/com/vmloft/develop/daemon/VMDaemonActivity.java

@@ -0,0 +1,31 @@
+package com.vmloft.develop.daemon;
+
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.v7.app.AppCompatActivity;
+import android.util.Log;
+import android.view.Gravity;
+import android.view.Window;
+import android.view.WindowManager;
+
+/**
+ * Created by lzan13 on 2017/3/9.
+ */
+
+public class VMDaemonActivity extends AppCompatActivity {
+
+    @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        Log.d("lzan13", "VMDaemonActivity -> onCreate");
+
+        Window window = getWindow();
+        window.setGravity(Gravity.LEFT | Gravity.TOP);
+        WindowManager.LayoutParams lp = window.getAttributes();
+        lp.width = 1;
+        lp.height = 1;
+
+        window.setAttributes(lp);
+
+        VMDaemonManager.getInstance().setDaemonActivity(this);
+    }
+}

+ 67 - 0
as/app/src/main/java/com/vmloft/develop/daemon/VMDaemonManager.java

@@ -0,0 +1,67 @@
+package com.vmloft.develop.daemon;
+
+import android.content.Intent;
+import android.support.v7.app.AppCompatActivity;
+import android.util.Log;
+import com.vmloft.develop.daemon.services.VMCoreService;
+
+/**
+ * 守护进程管理类
+ * Created by lzan13 on 2017/3/9.
+ */
+public class VMDaemonManager {
+
+    private final static String TAG = VMDaemonManager.class.getSimpleName();
+
+    private static VMDaemonManager instance = null;
+
+    private AppCompatActivity daemonActivity;
+
+    private VMDaemonManager() {
+    }
+
+    /**
+     * 获取单例类实例
+     */
+    public static VMDaemonManager getInstance() {
+        if (instance == null) {
+            instance = new VMDaemonManager();
+        }
+        return instance;
+    }
+
+    /**
+     * 启动守护 Activity,其实就是一像素大小的流氓 activity
+     */
+    public void startDaemonActivity() {
+        Log.i(TAG, "startCoreProcess: 启动流氓 Activity");
+        VMApplication.getContext()
+                .startActivity(new Intent(VMApplication.getContext(), VMDaemonActivity.class));
+    }
+
+    /**
+     * 结束流氓的 activity
+     */
+    public void finishDaemonActivity() {
+        Log.i(TAG, "startCoreProcess: 结束流氓 Activity");
+        if (daemonActivity != null) {
+            daemonActivity.finish();
+        }
+    }
+
+    /**
+     * 启动核心进程
+     */
+    public void startCoreProcess() {
+        Log.i(TAG, "startCoreProcess: 启动核心进程");
+        Intent wakeIntent = new Intent(VMApplication.getContext(), VMCoreService.class);
+        VMApplication.getContext().startService(wakeIntent);
+    }
+
+    /**
+     * 保存当前启动的一像素 Activity
+     */
+    public void setDaemonActivity(AppCompatActivity daemonActivity) {
+        this.daemonActivity = daemonActivity;
+    }
+}

+ 37 - 0
as/app/src/main/java/com/vmloft/develop/daemon/receiver/VMWakeReceiver.java

@@ -0,0 +1,37 @@
+package com.vmloft.develop.daemon.receiver;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+import com.vmloft.develop.daemon.VMDaemonManager;
+
+/**
+ * 接收唤醒应用核心服务的广播接收器,接收守护进程发送过来的广播
+ *
+ * Created by lzan13 on 2017/3/7.
+ */
+public class VMWakeReceiver extends BroadcastReceiver {
+
+    private final static String TAG = VMWakeReceiver.class.getSimpleName();
+
+    // 定义守护进程发送唤醒广播的 Action
+    public final static String DAEMON_WAKE_ACTION = "com.vmloft.develop.daemon.wake";
+
+    @Override public void onReceive(Context context, Intent intent) {
+        String action = intent.getAction();
+        if (action.equals(DAEMON_WAKE_ACTION)) {
+            Log.i(TAG, "onReceive: 起床了!");
+            // 接收到守护进程发送的广播,开始启动核心进程
+            VMDaemonManager.getInstance().startCoreProcess();
+        } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
+            Log.i(TAG, "onReceive: 锁屏了!");
+            // 检测到锁屏,启动一像素的流氓 Activity
+            VMDaemonManager.getInstance().startDaemonActivity();
+        } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
+            Log.i(TAG, "onReceive: 解锁了!");
+            // 解锁后,结束一像素的流氓 Activity
+            VMDaemonManager.getInstance().finishDaemonActivity();
+        }
+    }
+}

+ 31 - 0
as/app/src/main/java/com/vmloft/develop/daemon/services/VMBackgroundService.java

@@ -0,0 +1,31 @@
+package com.vmloft.develop.daemon.services;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.util.Log;
+
+/**
+ * 普通的后台 Service 服务,此类只是为了展示正常服务进程的优先级
+ *
+ * Created by lzan13 on 2017/3/7.JobScheduler机制唤醒
+ */
+public class VMBackgroundService extends Service {
+
+    private final static String TAG = VMBackgroundService.class.getSimpleName();
+
+    @Override public void onCreate() {
+        Log.i(TAG, "onCreate");
+        super.onCreate();
+    }
+
+    @Override public IBinder onBind(Intent intent) {
+        // TODO: Return the communication channel to the service.
+        throw new UnsupportedOperationException("onBind 未实现");
+    }
+
+    @Override public void onDestroy() {
+        Log.i(TAG, "onDestroy");
+        super.onDestroy();
+    }
+}

+ 77 - 0
as/app/src/main/java/com/vmloft/develop/daemon/services/VMCoreService.java

@@ -0,0 +1,77 @@
+package com.vmloft.develop.daemon.services;
+
+import android.app.Notification;
+import android.app.Service;
+import android.content.Intent;
+import android.os.Build;
+import android.os.IBinder;
+import android.util.Log;
+
+/**
+ * 用于其他进程来唤醒UI进程用的 Service
+ *
+ * Created by lzan13 on 2017/3/9.
+ */
+
+public class VMCoreService extends Service {
+
+    private final static String TAG = VMCoreService.class.getSimpleName();
+    // 核心进程 Service ID
+    private final static int CORE_SERVICE_ID = -5120;
+
+    @Override public void onCreate() {
+        Log.i(TAG, "VMCoreService -> onCreate");
+        super.onCreate();
+    }
+
+    @Override public int onStartCommand(Intent intent, int flags, int startId) {
+        Log.i(TAG, "VMCoreService -> onStartCommand");
+        // 利用 Android 漏洞提高进程优先级,
+        startForeground(CORE_SERVICE_ID, new Notification());
+        // 当 SDk 版本大于18时,需要通过内部 Service 类启动同样 id 的 Service
+        if (Build.VERSION.SDK_INT >= 18) {
+            Intent innerIntent = new Intent(this, CoreInnerService.class);
+            startService(innerIntent);
+        }
+        return START_STICKY;
+    }
+
+    @Override public IBinder onBind(Intent intent) {
+        // TODO: Return the communication channel to the service.
+        throw new UnsupportedOperationException("Not yet implemented");
+    }
+
+    @Override public void onDestroy() {
+        Log.i(TAG, "VMCoreService -> onDestroy");
+        super.onDestroy();
+    }
+
+    /**
+     * 实现一个内部的 Service,实现让后台服务的优先级提高到前台服务,这里利用了 android 系统的漏洞,
+     * 不保证所有系统可用,测试在7.1.1 之前大部分系统都是可以的,不排除个别厂商优化限制
+     */
+    public static class CoreInnerService extends Service {
+
+        @Override public void onCreate() {
+            Log.i(TAG, "CoreInnerService -> onCreate");
+            super.onCreate();
+        }
+
+        @Override public int onStartCommand(Intent intent, int flags, int startId) {
+            Log.i(TAG, "CoreInnerService -> onStartCommand");
+            startForeground(CORE_SERVICE_ID, new Notification());
+            stopSelf();
+            return super.onStartCommand(intent, flags, startId);
+        }
+
+        @Override public IBinder onBind(Intent intent) {
+            // TODO: Return the communication channel to the service.
+            throw new UnsupportedOperationException("Not yet implemented");
+        }
+
+        @Override public void onDestroy() {
+            Log.i(TAG, "CoreInnerService -> onDestroy");
+            super.onDestroy();
+        }
+    }
+}

+ 29 - 0
as/app/src/main/java/com/vmloft/develop/daemon/services/VMDaemonJobService.java

@@ -0,0 +1,29 @@
+package com.vmloft.develop.daemon.services;
+
+import android.annotation.TargetApi;
+import android.app.job.JobParameters;
+import android.app.job.JobService;
+import android.os.Build;
+import android.util.Log;
+import com.vmloft.develop.daemon.VMDaemonManager;
+
+/**
+ * 5.x 以上使用 JobService 实现守护进程,这个守护进程要做的工作很简单,就是启动应用的核心进程
+ * Created by lzan13 on 2017/3/8.
+ */
+@TargetApi(Build.VERSION_CODES.LOLLIPOP) public class VMDaemonJobService extends JobService {
+
+    private final static String TAG = VMDaemonJobService.class.getSimpleName();
+
+    @Override public boolean onStartJob(JobParameters params) {
+        Log.d(TAG, "onStartJob");
+        // 这里为了演示,这里直接启动核心进程,没有做其他判断操作
+        VMDaemonManager.getInstance().startCoreProcess();
+        return false;
+    }
+
+    @Override public boolean onStopJob(JobParameters params) {
+        Log.d(TAG, "onStopJob");
+        return false;
+    }
+}

+ 102 - 0
as/app/src/main/java/com/vmloft/develop/daemon/services/VMDaemonService.java

@@ -0,0 +1,102 @@
+package com.vmloft.develop.daemon.services;
+
+import android.app.AlarmManager;
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Build;
+import android.os.IBinder;
+import android.util.Log;
+import com.vmloft.develop.daemon.receiver.VMWakeReceiver;
+
+/**
+ * 以实现内部 Service 类的方式实现守护进程,这里是利用 android 漏洞提高当前进程优先级
+ *
+ * Created by lzan13 on 2017/3/7.
+ */
+public class VMDaemonService extends Service {
+
+    private final static String TAG = VMDaemonService.class.getSimpleName();
+
+    // 定时唤醒的时间间隔,这里为了自己测试方边设置了一分钟
+    private final static int ALARM_INTERVAL = 1 * 60 * 1000;
+    // 发送唤醒广播请求码
+    private final static int WAKE_REQUEST_CODE = 5121;
+    // 守护进程 Service ID
+    private final static int DAEMON_SERVICE_ID = -5121;
+
+    @Override public void onCreate() {
+        Log.i(TAG, "VMDaemonService->onCreate");
+        super.onCreate();
+    }
+
+    @Override public int onStartCommand(Intent intent, int flags, int startId) {
+        Log.i(TAG, "VMDaemonService->onStartCommand");
+        // 利用 Android 漏洞提高进程优先级,
+        startForeground(DAEMON_SERVICE_ID, new Notification());
+        // 当 SDk 版本大于18时,需要通过内部 Service 类启动同样 id 的 Service
+        if (Build.VERSION.SDK_INT >= 18) {
+            Intent innerIntent = new Intent(this, DaemonInnerService.class);
+            startService(innerIntent);
+        }
+
+        // 发送唤醒广播来促使挂掉的UI进程重新启动起来
+        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
+        Intent alarmIntent = new Intent();
+        alarmIntent.setAction(VMWakeReceiver.DAEMON_WAKE_ACTION);
+
+        PendingIntent operation = PendingIntent.getBroadcast(this, WAKE_REQUEST_CODE, alarmIntent,
+                PendingIntent.FLAG_UPDATE_CURRENT);
+
+        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
+                ALARM_INTERVAL, operation);
+
+        /**
+         * 这里返回值是使用系统 Service 的机制自动重新启动,不过这种方式以下两种方式不适用:
+         * 1.Service 第一次被异常杀死后会在5秒内重启,第二次被杀死会在10秒内重启,第三次会在20秒内重启,一旦在短时间内 Service 被杀死达到5次,则系统不再拉起。
+         * 2.进程被取得 Root 权限的管理工具或系统工具通过 forestop 停止掉,无法重启。
+         */
+        return START_STICKY;
+    }
+
+    @Override public IBinder onBind(Intent intent) {
+        // TODO: Return the communication channel to the service.
+        throw new UnsupportedOperationException("onBind 未实现");
+    }
+
+    @Override public void onDestroy() {
+        Log.i(TAG, "VMDaemonService->onDestroy");
+        super.onDestroy();
+    }
+
+    /**
+     * 实现一个内部的 Service,实现让后台服务的优先级提高到前台服务,这里利用了 android 系统的漏洞,
+     * 不保证所有系统可用,测试在7.1.1 之前大部分系统都是可以的,不排除个别厂商优化限制
+     */
+    public static class DaemonInnerService extends Service {
+
+        @Override public void onCreate() {
+            Log.i(TAG, "DaemonInnerService -> onCreate");
+            super.onCreate();
+        }
+
+        @Override public int onStartCommand(Intent intent, int flags, int startId) {
+            Log.i(TAG, "DaemonInnerService -> onStartCommand");
+            startForeground(DAEMON_SERVICE_ID, new Notification());
+            stopSelf();
+            return super.onStartCommand(intent, flags, startId);
+        }
+
+        @Override public IBinder onBind(Intent intent) {
+            // TODO: Return the communication channel to the service.
+            throw new UnsupportedOperationException("onBind 未实现");
+        }
+
+        @Override public void onDestroy() {
+            Log.i(TAG, "DaemonInnerService -> onDestroy");
+            super.onDestroy();
+        }
+    }
+}

+ 60 - 0
as/app/src/main/java/com/vmloft/develop/daemon/services/VMForegroundService.java

@@ -0,0 +1,60 @@
+package com.vmloft.develop.daemon.services;
+
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.support.v7.app.NotificationCompat;
+import android.util.Log;
+import com.vmloft.develop.daemon.MainActivity;
+import com.vmloft.develop.daemon.R;
+
+/**
+ * 正常的系统前台进程,会在系统通知栏显示一个Notification通知图标,因为这个通知的关系,应用的进程优先级是比较高的,
+ * 一般系统的内存回收是无法杀死的
+ *
+ * Created by lzan13 on 2017/3/7.
+ */
+public class VMForegroundService extends Service {
+
+    private final static String TAG = VMForegroundService.class.getSimpleName();
+
+    // 通知栏发送的通知 id
+    private final static int NOTIFY_ID = 1000;
+
+    @Override public void onCreate() {
+        Log.i(TAG, "VMForegroundService->onCreate");
+        super.onCreate();
+    }
+
+    @Override public int onStartCommand(Intent intent, int flags, int startId) {
+        Log.i(TAG, "VMForegroundService->onStartCommand");
+
+        // 创建个通知,这样可以提高服务的优先级
+        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
+        builder.setSmallIcon(R.mipmap.ic_launcher);
+        builder.setContentTitle("这是一条前台通知");
+        builder.setContentText("这是一条前台通知,表示当前程序有一个前台服务在运行");
+        builder.setContentInfo("前台服务");
+        builder.setWhen(System.currentTimeMillis());
+        Intent activityIntent = new Intent(this, MainActivity.class);
+        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, activityIntent,
+                PendingIntent.FLAG_UPDATE_CURRENT);
+        builder.setContentIntent(pendingIntent);
+        Notification notification = builder.build();
+        // 开启前台通知
+        startForeground(NOTIFY_ID, notification);
+        return super.onStartCommand(intent, flags, startId);
+    }
+
+    @Override public IBinder onBind(Intent intent) {
+        // TODO: Return the communication channel to the service.
+        throw new UnsupportedOperationException("onBind 未实现");
+    }
+
+    @Override public void onDestroy() {
+        Log.i(TAG, "VMForegroundService->onDestroy");
+        super.onDestroy();
+    }
+}

+ 47 - 0
as/app/src/main/res/layout/activity_main.xml

@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:id="@+id/activity_main"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:paddingBottom="@dimen/activity_vertical_margin"
+    android:paddingLeft="@dimen/activity_horizontal_margin"
+    android:paddingRight="@dimen/activity_horizontal_margin"
+    android:paddingTop="@dimen/activity_vertical_margin"
+    tools:context="com.vmloft.develop.daemon.MainActivity"
+    >
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:orientation="vertical"
+        >
+        <Button
+            android:id="@+id/btn_foreground"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:text="putong 前台 Service"
+            />
+
+        <Button
+            android:id="@+id/btn_daemon"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:text="Service 内部类方式实现守护进程"
+            />
+
+        <Button
+            android:id="@+id/btn_background"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:text="普通后台 Service 进程"
+            />
+
+        <Button
+            android:id="@+id/btn_job_service"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:text="5.x使用 JobService 来实现守护进程"
+            />
+    </LinearLayout>
+</RelativeLayout>

BIN
as/app/src/main/res/mipmap-hdpi/ic_launcher.png


BIN
as/app/src/main/res/mipmap-mdpi/ic_launcher.png


BIN
as/app/src/main/res/mipmap-xhdpi/ic_launcher.png


BIN
as/app/src/main/res/mipmap-xxhdpi/ic_launcher.png


BIN
as/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png


+ 6 - 0
as/app/src/main/res/values-w820dp/dimens.xml

@@ -0,0 +1,6 @@
+<resources>
+    <!-- Example customization of dimensions originally defined in res/values/dimens.xml
+         (such as screen margins) for screens with more than 820dp of available width. This
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
+    <dimen name="activity_horizontal_margin">64dp</dimen>
+</resources>

+ 6 - 0
as/app/src/main/res/values/colors.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <color name="colorPrimary">#3F51B5</color>
+    <color name="colorPrimaryDark">#303F9F</color>
+    <color name="colorAccent">#FF4081</color>
+</resources>

+ 5 - 0
as/app/src/main/res/values/dimens.xml

@@ -0,0 +1,5 @@
+<resources>
+    <!-- Default screen margins, per the Android Design guidelines. -->
+    <dimen name="activity_horizontal_margin">16dp</dimen>
+    <dimen name="activity_vertical_margin">16dp</dimen>
+</resources>

+ 3 - 0
as/app/src/main/res/values/strings.xml

@@ -0,0 +1,3 @@
+<resources>
+    <string name="app_name">VMDaemonServices</string>
+</resources>

+ 28 - 0
as/app/src/main/res/values/styles.xml

@@ -0,0 +1,28 @@
+<resources>
+
+    <!-- Base application theme. -->
+    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
+        <!-- Customize your theme here. -->
+        <item name="colorPrimary">@color/colorPrimary</item>
+        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
+        <item name="colorAccent">@color/colorAccent</item>
+    </style>
+
+    <style name="AppTheme.Daemon">
+        <!--设置背景透明-->
+        <item name="android:windowBackground">@android:color/transparent</item>
+        <item name="android:windowIsTranslucent">true</item>
+        <!--设置窗口框架为空-->
+        <item name="android:windowFrame">@null</item>
+        <!--设置没有 title-->
+        <item name="android:windowNoTitle">true</item>
+        <!--设置浮动-->
+        <item name="android:windowIsFloating">true</item>
+        <!--窗口动画为空-->
+        <item name="android:windowAnimationStyle">@null</item>
+        <!--不可预览-->
+        <item name="android:windowDisablePreview">true</item>
+        <item name="android:windowNoDisplay">false</item>
+    </style>
+
+</resources>

+ 23 - 0
as/build.gradle

@@ -0,0 +1,23 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+
+buildscript {
+    repositories {
+        jcenter()
+    }
+    dependencies {
+        classpath 'com.android.tools.build:gradle:2.2.3'
+
+        // NOTE: Do not place your application dependencies here; they belong
+        // in the individual module build.gradle files
+    }
+}
+
+allprojects {
+    repositories {
+        jcenter()
+    }
+}
+
+task clean(type: Delete) {
+    delete rootProject.buildDir
+}

+ 17 - 0
as/gradle.properties

@@ -0,0 +1,17 @@
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx1536m
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true

BIN
as/gradle/wrapper/gradle-wrapper.jar


+ 6 - 0
as/gradle/wrapper/gradle-wrapper.properties

@@ -0,0 +1,6 @@
+#Mon Dec 28 10:00:20 PST 2015
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

+ 160 - 0
as/gradlew

@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+    JAVACMD=`cygpath --unix "$JAVACMD"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+    JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

+ 90 - 0
as/gradlew.bat

@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem  Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega

+ 1 - 0
as/settings.gradle

@@ -0,0 +1 @@
+include ':app'