Android service stopSelf (int)

Here is my code -

public class BackgroundService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        new ServiceThread(startId);
        return START_NOT_STICKY;
    }

    class ServiceThread extends Thread {
        private int startId;

        ServiceThread(int startId) {
            this.startId = startId;
        }

        @Override
        public void run() {
            super.run();
            try {
                Thread.sleep((long) Math.random());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            stopSelf(startId);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

According to this “Stop servicelink , I can / should call stopSelf with the received “startId”.

, onStartCommand() , , , ( ). , stopSelf (int), , . , stopSelf (int), (startId onStartCommand()), . , , stopSelf (int), , .

: , stopSelf "startId", - . startId , ? "" ?

"", , , .

+4
3

. , javadoc Service.stopSelfResult(int startId).

(, ), , .

+3

- , - /. , , ThreadPoolService, Service :

  • HashSet<Integer>, startId, onStartCommand()
  • int, mLastStartId, startId, onStartCommand()
  • ExecutorService, newCachedThreadPool(), newFixedThreadPool()
  • beginIntentProcessing(), startId HashSet startId mLastStartId
  • endIntentProcessing(), startId HashSet , HashSet . , HashSet , stopSelf() Service, mLastStartId.

, , . ( ) MOOC Android, http://www.coursera.org/course/posaconcurrency http://www.coursera.org/course/posacommunication.

+1

The solution is to support a boolean hash map with a start identifier as the key. Then, in your worker threads, instead of calling stopSelf(int), a user method is called that performs the following actions:

Set the hash map entry to trueusing the start identifier as the key. Scroll through the keys in ascending order and call stopSelf(key)until you meet the entry false.

0
source

All Articles