即使在Android中调用onDestroy方法,服务也不会停止

时间:2016-04-13 03:00:19

标签: android android-studio android-service

我还是Android新手。我使用stopService调用onDestroy方法。调用onDestroy方法,因为我可以看到toast消息。但是用于发送位置更新的无限for循环一直在运行。 有什么我需要改变的吗?

class Node {

    public String name;
    public int number;
    public Node next;
}

public class LinkedListTest {

    public static void main(String[] args) {

        LinkedListTest obj = new LinkedListTest();
        Node head = obj.createLinkList();
        Node startPointer = head;
        while (startPointer != null) {

            System.out.println(startPointer.name + " " + startPointer.number);
            startPointer = startPointer.next;
        }
        System.out.println("***********");
        Node newNodeHead = obj.deleteNode(1, head);
        startPointer = newNodeHead;
        while (startPointer != null) {

            System.out.println(startPointer.name + " " + startPointer.number);
            startPointer = startPointer.next;
        }

    }

    public Node deleteNode(int n, Node head) {

        Node current = head;
        Node newNodestartPointer = null;
        Node newNodeCurrent = null;
        while (current != null) {

            if (!(current.number == n)) {

                if (newNodestartPointer == null) {
                    newNodestartPointer = new Node();
                    newNodestartPointer.name = current.name;
                    newNodestartPointer.number = current.number;
                    newNodestartPointer.next = null;
                    newNodeCurrent = newNodestartPointer;
                } else {

                    Node newNode = new Node();
                    newNode.name = current.name;
                    newNode.number = current.number;
                    newNodeCurrent.next = newNode;
                    newNodeCurrent = newNode;
                }
            }
            current = current.next;
        }

        return newNodestartPointer;
    }

    public Node createLinkList() {

        Node head = null;

        Node newNode = new Node();
        newNode.name = "Dog";
        newNode.number = 1;
        newNode.next = null;

        head = newNode;

        newNode = new Node();
        newNode.name = "Cat";
        newNode.number = 1;
        newNode.next = null;
        head.next = newNode;
        Node prevNode = newNode;

        newNode = new Node();
        newNode.name = "Rat";
        newNode.number = 2;
        newNode.next = null;
        prevNode.next = newNode;
        prevNode = newNode;

        newNode = new Node();
        newNode.name = "Donkey";
        newNode.number = 3;
        newNode.next = null;
        prevNode.next = newNode;

        return head;
    }
}

1 个答案:

答案 0 :(得分:5)

你自己不打电话给onDestroy()。永远不要自己调用生命周期方法。 Android会在服务停止时调用它们。

对IntentService进行子类化并不是管理正在进行的工作的最佳选择。您最好自己管理一个线程并管理传递给该服务的启动和停止命令。这不是一件容易的事。

http://tools.android.com/download/studio/builds/2-0