Service1.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package com.service.demo;
  2. import java.util.List;
  3. import android.app.ActivityManager;
  4. import android.app.ActivityManager.RunningAppProcessInfo;
  5. import android.app.Service;
  6. import android.app.ActivityManager.RunningServiceInfo;
  7. import android.content.ComponentCallbacks;
  8. import android.content.ComponentName;
  9. import android.content.Context;
  10. import android.content.Intent;
  11. import android.content.ServiceConnection;
  12. import android.content.res.Configuration;
  13. import android.os.Handler;
  14. import android.os.IBinder;
  15. import android.os.RemoteException;
  16. import android.util.Log;
  17. import android.widget.Toast;
  18. /**
  19. *
  20. * @author hellogv
  21. *
  22. */
  23. public class Service1 extends Service {
  24. private String TAG = getClass().getName();
  25. // 用于判断进程是否运行
  26. private String Process_Name = "com.example.servicetest2:service2";
  27. /**
  28. *启动Service2
  29. */
  30. private StrongService startS2 = new StrongService.Stub() {
  31. @Override
  32. public void stopService() throws RemoteException {
  33. Intent i = new Intent(getBaseContext(), Service2.class);
  34. getBaseContext().stopService(i);
  35. }
  36. @Override
  37. public void startService() throws RemoteException {
  38. Intent i = new Intent(getBaseContext(), Service2.class);
  39. getBaseContext().startService(i);
  40. }
  41. };
  42. @Override
  43. public void onTrimMemory(int level){
  44. Toast.makeText(getBaseContext(), "Service1 onTrimMemory..."+level, Toast.LENGTH_SHORT)
  45. .show();
  46. keepService2();//保持Service2一直运行
  47. }
  48. @Override
  49. public void onCreate() {
  50. Toast.makeText(Service1.this, "Service1 onCreate...", Toast.LENGTH_SHORT)
  51. .show();
  52. keepService2();
  53. }
  54. /**
  55. * 判断Service2是否还在运行,如果不是则启动Service2
  56. */
  57. private void keepService2(){
  58. boolean isRun = Utils.isProessRunning(Service1.this, Process_Name);
  59. if (isRun == false) {
  60. try {
  61. Toast.makeText(getBaseContext(), "重新启动 Service2", Toast.LENGTH_SHORT).show();
  62. startS2.startService();
  63. } catch (RemoteException e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. }
  68. @Override
  69. public int onStartCommand(Intent intent, int flags, int startId) {
  70. return START_STICKY;
  71. }
  72. @Override
  73. public IBinder onBind(Intent intent) {
  74. return (IBinder) startS2;
  75. }
  76. }