MainActivity.java 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package com.vmloft.develop.daemon;
  2. import android.annotation.TargetApi;
  3. import android.app.job.JobInfo;
  4. import android.app.job.JobScheduler;
  5. import android.content.ComponentName;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.os.Build;
  9. import android.support.v7.app.AppCompatActivity;
  10. import android.os.Bundle;
  11. import android.view.View;
  12. import com.vmloft.develop.daemon.services.VMBackgroundService;
  13. import com.vmloft.develop.daemon.services.VMCoreService;
  14. import com.vmloft.develop.daemon.services.VMDaemonJobService;
  15. import com.vmloft.develop.daemon.services.VMDaemonService;
  16. import com.vmloft.develop.daemon.services.VMForegroundService;
  17. public class MainActivity extends AppCompatActivity {
  18. @Override protected void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.activity_main);
  21. findViewById(R.id.btn_foreground).setOnClickListener(viewListener);
  22. findViewById(R.id.btn_daemon).setOnClickListener(viewListener);
  23. findViewById(R.id.btn_background).setOnClickListener(viewListener);
  24. findViewById(R.id.btn_job_service).setOnClickListener(viewListener);
  25. // 启动核心进程
  26. startCoreProcess();
  27. }
  28. /**
  29. * 点击事件监听
  30. */
  31. private View.OnClickListener viewListener = new View.OnClickListener() {
  32. @Override public void onClick(View v) {
  33. switch (v.getId()) {
  34. case R.id.btn_foreground:
  35. Intent foregroundIntent =
  36. new Intent(getApplicationContext(), VMForegroundService.class);
  37. startService(foregroundIntent);
  38. break;
  39. case R.id.btn_daemon:
  40. Intent daemonIntent =
  41. new Intent(getApplicationContext(), VMDaemonService.class);
  42. startService(daemonIntent);
  43. break;
  44. case R.id.btn_background:
  45. Intent backgroundIntent =
  46. new Intent(getApplicationContext(), VMBackgroundService.class);
  47. startService(backgroundIntent);
  48. break;
  49. case R.id.btn_job_service:
  50. startJobScheduler();
  51. break;
  52. }
  53. }
  54. };
  55. /**
  56. * 5.x以上系统启用 JobScheduler API 进行实现守护进程的唤醒操作
  57. */
  58. @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void startJobScheduler() {
  59. int jobId = 1;
  60. JobInfo.Builder jobInfo =
  61. new JobInfo.Builder(jobId, new ComponentName(this, VMDaemonJobService.class));
  62. jobInfo.setPeriodic(10000);
  63. jobInfo.setPersisted(true);
  64. JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
  65. jobScheduler.schedule(jobInfo.build());
  66. }
  67. /**
  68. * 启动核心进程
  69. */
  70. private void startCoreProcess() {
  71. startService(new Intent(getApplicationContext(), VMCoreService.class));
  72. }
  73. }