Stop service in an activity

后端 未结 3 741
独厮守ぢ
独厮守ぢ 2021-01-23 01:25

I\'m using following code to stop my service

Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
stopService(intent);

An

3条回答
  •  难免孤独
    2021-01-23 01:30

    This code would work

    public class UsageRecorderService extends IntentService {
    
        private boolean mStop = false;
    
        public UsageRecorderService() {
            super("UsageRecorder");
        }
    
        public final Object sLock = new Object();
    
        public void onDestroy() {
            synchronized (sLock) {
                mStop = true;
            }
        }
    
    
        @Override
        protected void onHandleIntent(Intent intent) {
            while (true) {
                synchronized (sLock) {
                    if (mStop) break;
                }
                UsageRecorder.recordUsages(this, false);
                SystemClock.sleep(10000);
            }
        }
    
    }
    

    You can use stopService

    Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
    stopService(intent);
    

    Also I recommend to read Services guide to understand what is going there.

提交回复
热议问题