Service2.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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.ActivityManager.RunningServiceInfo;
  6. import android.app.Application;
  7. import android.app.Service;
  8. import android.content.Context;
  9. import android.content.Intent;
  10. import android.os.Handler;
  11. import android.os.IBinder;
  12. import android.os.RemoteException;
  13. import android.util.Log;
  14. import android.widget.Toast;
  15. /**
  16. *
  17. * @author 掌缘生灭
  18. *
  19. */
  20. public class Service2 extends Service {
  21. private String TAG = getClass().getName();
  22. private String Process_Name = "com.example.servicetest2:service1";
  23. /**
  24. *启动Service1
  25. */
  26. private StrongService startS1 = new StrongService.Stub() {
  27. @Override
  28. public void stopService() throws RemoteException {
  29. Intent i = new Intent(getBaseContext(), Service1.class);
  30. getBaseContext().stopService(i);
  31. }
  32. @Override
  33. public void startService() throws RemoteException {
  34. Intent i = new Intent(getBaseContext(), Service1.class);
  35. getBaseContext().startService(i);
  36. }
  37. };
  38. @Override
  39. public void onTrimMemory(int level){
  40. Toast.makeText(getBaseContext(), "Service2 onTrimMemory..."+level, Toast.LENGTH_SHORT)
  41. .show();
  42. keepService1();
  43. }
  44. public void onCreate() {
  45. Toast.makeText(Service2.this, "Service2 onCreate...", Toast.LENGTH_SHORT).show();
  46. keepService1();
  47. }
  48. /**
  49. * 判断Service1是否还在运行,如果不是则启动Service1
  50. */
  51. private void keepService1(){
  52. boolean isRun = Utils.isProessRunning(Service2.this, Process_Name);
  53. if (isRun == false) {
  54. try {
  55. Toast.makeText(getBaseContext(), "重新启动 Service1", Toast.LENGTH_SHORT).show();
  56. startS1.startService();
  57. } catch (RemoteException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. }
  62. @Override
  63. public int onStartCommand(Intent intent, int flags, int startId) {
  64. return START_STICKY;
  65. }
  66. @Override
  67. public IBinder onBind(Intent intent) {
  68. return (IBinder) startS1;
  69. }
  70. }