VMCoreService.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package com.vmloft.develop.daemon.services;
  2. import android.app.Notification;
  3. import android.app.Service;
  4. import android.content.Intent;
  5. import android.os.Build;
  6. import android.os.IBinder;
  7. import android.util.Log;
  8. /**
  9. * 用于其他进程来唤醒UI进程用的 Service
  10. *
  11. * Created by lzan13 on 2017/3/9.
  12. */
  13. public class VMCoreService extends Service {
  14. private final static String TAG = VMCoreService.class.getSimpleName();
  15. // 核心进程 Service ID
  16. private final static int CORE_SERVICE_ID = -5120;
  17. @Override public void onCreate() {
  18. Log.i(TAG, "VMCoreService -> onCreate");
  19. super.onCreate();
  20. }
  21. @Override public int onStartCommand(Intent intent, int flags, int startId) {
  22. Log.i(TAG, "VMCoreService -> onStartCommand");
  23. // 利用 Android 漏洞提高进程优先级,
  24. startForeground(CORE_SERVICE_ID, new Notification());
  25. // 当 SDk 版本大于18时,需要通过内部 Service 类启动同样 id 的 Service
  26. if (Build.VERSION.SDK_INT >= 18) {
  27. Intent innerIntent = new Intent(this, CoreInnerService.class);
  28. startService(innerIntent);
  29. }
  30. return START_STICKY;
  31. }
  32. @Override public IBinder onBind(Intent intent) {
  33. // TODO: Return the communication channel to the service.
  34. throw new UnsupportedOperationException("Not yet implemented");
  35. }
  36. @Override public void onDestroy() {
  37. Log.i(TAG, "VMCoreService -> onDestroy");
  38. super.onDestroy();
  39. }
  40. /**
  41. * 实现一个内部的 Service,实现让后台服务的优先级提高到前台服务,这里利用了 android 系统的漏洞,
  42. * 不保证所有系统可用,测试在7.1.1 之前大部分系统都是可以的,不排除个别厂商优化限制
  43. */
  44. public static class CoreInnerService extends Service {
  45. @Override public void onCreate() {
  46. Log.i(TAG, "CoreInnerService -> onCreate");
  47. super.onCreate();
  48. }
  49. @Override public int onStartCommand(Intent intent, int flags, int startId) {
  50. Log.i(TAG, "CoreInnerService -> onStartCommand");
  51. startForeground(CORE_SERVICE_ID, new Notification());
  52. stopSelf();
  53. return super.onStartCommand(intent, flags, startId);
  54. }
  55. @Override public IBinder onBind(Intent intent) {
  56. // TODO: Return the communication channel to the service.
  57. throw new UnsupportedOperationException("Not yet implemented");
  58. }
  59. @Override public void onDestroy() {
  60. Log.i(TAG, "CoreInnerService -> onDestroy");
  61. super.onDestroy();
  62. }
  63. }
  64. }