如何在应用重新启动后使服务继续工作

huangapple go评论101阅读模式
英文:

How to make service continues to work after the app is restarted

问题

我有一个通过按按钮工作的服务。
内部有一个每秒工作一次的计数器。
我测试过它,它在工作。
即使在应用程序关闭后它也在工作。
问题出现在应用程序关闭后,
然后我执行一个运行
测试该服务,它不工作。
我如何在从Android Studio内部运行后使它工作?

// MainActivity

public class MainActivity extends AppCompatActivity {

  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. if (!isMyServiceRunning(SensorService.class)) {
  5. Log.i("isServiceRunning", "Not");
  6. } else {
  7. Log.i("isServiceRunning", "Don");
  8. }
  9. }
  10. public void Test(View view) {
  11. startService(new Intent(this, SensorService.class));
  12. }
  13. private boolean isMyServiceRunning(Class<?> serviceClass) {
  14. ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
  15. for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
  16. if (serviceClass.getName().equals(service.service.getClassName())) {
  17. return true;
  18. }
  19. }
  20. return false;
  21. }

}

/// Service

public class SensorService extends Service {

  1. public int counter = 0;
  2. public SensorService() {
  3. super();
  4. Log.i("HERE", "here I am!");
  5. }
  6. @Override
  7. public int onStartCommand(Intent intent, int flags, int startId) {
  8. super.onStartCommand(intent, flags, startId);
  9. startTimer();
  10. return START_STICKY;
  11. }
  12. @Override
  13. public void onDestroy() {
  14. super.onDestroy();
  15. Log.i("EXIT", "ondestroy!");
  16. // Intent broadcastIntent = new Intent(this, SensorRestarterBroadcastReceiver.class);
  17. stoptimertask();
  18. }
  19. private Timer timer;
  20. private TimerTask timerTask;
  21. long oldTime = 0;
  22. public void startTimer() {
  23. // set a new Timer
  24. Log.i("startTimer", "Don");
  25. timer = new Timer();
  26. // initialize the TimerTask's job
  27. initializeTimerTask();
  28. // schedule the timer, to wake up every 1 second
  29. timer.schedule(timerTask, 1000, 1000); //
  30. }
  31. /**
  32. * it sets the timer to print the counter every x seconds
  33. */
  34. public void initializeTimerTask() {
  35. Log.i("initializeTimerTask", "Don");
  36. timerTask = new TimerTask() {
  37. public void run() {
  38. Log.i("in_timer", "in timer ++++ " + (counter++));
  39. }
  40. };
  41. }
  42. /**
  43. * not needed
  44. */
  45. public void stoptimertask() {
  46. // stop the timer, if it's not already null
  47. if (timer != null) {
  48. timer.cancel();
  49. timer = null;
  50. }
  51. }
  52. @Nullable
  53. @Override
  54. public IBinder onBind(Intent intent) {
  55. return null;
  56. }

}

英文:

I have a service works by pressing a button.
There's a counter that works every second inside it.
I tested it and it's working.
It also works after the application is shut down.
The problem after the application is closed
Then I'm doing a run
test the service it doesn't work.
How do I make it works after i do run from inside Android studio ?

//MainActivity

  1. public class MainActivity extends AppCompatActivity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. if(!isMyServiceRunning(SensorService.class)){
  6. Log.i(&quot;isServiceRunning&quot;,&quot;Not&quot;);
  7. }else {
  8. Log.i(&quot;isServiceRunning&quot;,&quot;Don&quot;);
  9. }
  10. }
  11. public void Test(View view){
  12. startService(new Intent(this, SensorService.class));
  13. }
  14. private boolean isMyServiceRunning(Class&lt;?&gt; serviceClass) {
  15. ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
  16. for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
  17. if (serviceClass.getName().equals(service.service.getClassName())) {
  18. return true;
  19. }
  20. }
  21. return false;
  22. }
  23. }
  24. /// Service
  25. public class SensorService extends Service {
  26. public int counter=0;
  27. public SensorService() {
  28. super();
  29. Log.i(&quot;HERE&quot;, &quot;here I am!&quot;);
  30. }
  31. @Override
  32. public int onStartCommand(Intent intent, int flags, int startId) {
  33. super.onStartCommand(intent, flags, startId);
  34. startTimer();
  35. return START_STICKY;
  36. }
  37. @Override
  38. public void onDestroy() {
  39. super.onDestroy();
  40. Log.i(&quot;EXIT&quot;, &quot;ondestroy!&quot;);
  41. // Intent broadcastIntent = new Intent(this, SensorRestarterBroadcastReceiver.class);
  42. stoptimertask();
  43. }
  44. private Timer timer;
  45. private TimerTask timerTask;
  46. long oldTime=0;
  47. public void startTimer() {
  48. //set a new Timer
  49. Log.i(&quot;startTimer&quot;, &quot;Don&quot;);
  50. timer = new Timer();
  51. //initialize the TimerTask&#39;s job
  52. initializeTimerTask();
  53. //schedule the timer, to wake up every 1 second
  54. timer.schedule(timerTask, 1000, 1000); //
  55. }
  56. /**
  57. * it sets the timer to print the counter every x seconds
  58. */
  59. public void initializeTimerTask() {
  60. Log.i(&quot;initializeTimerTask&quot;, &quot;Don&quot;);
  61. timerTask = new TimerTask() {
  62. public void run() {
  63. Log.i(&quot;in_timer&quot;, &quot;in timer ++++ &quot;+ (counter++));
  64. }
  65. };
  66. }
  67. /**
  68. * not needed
  69. */
  70. public void stoptimertask() {
  71. //stop the timer, if it&#39;s not already null
  72. if (timer != null) {
  73. timer.cancel();
  74. timer = null;
  75. }
  76. }
  77. @Nullable
  78. @Override
  79. public IBinder onBind(Intent intent){
  80. return null;
  81. }
  82. }

答案1

得分: 0

如果您在Android Studio中使用“Run”(无论是测试还是应用程序),由于整个应用程序总会首先停止,所以服务也会始终停止。如果您手动从设备上启动应用程序,则服务将不会停止。

对此无法绕过,实际上这是一个很好的功能。它确保每次运行时始终以清洁的状态启动应用程序。如果您想分享为什么想要这样做的原因,可能有一种替代方法来解决您的问题。

英文:

If you use "Run" from Android Studio (regardless if it's tests or the app) the service will always stop first since the whole application will always stop first. The service will not stop if you start the App manually from the device.

There is no way around this and is actually a good feature. It ensures that the App is always started cleanly on every run. If you want to share the reason of why you want to do this, there might be an alternate way of solving your problem.

huangapple
  • 本文由 发表于 2020年4月10日 19:24:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/61139280.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定