Service之“停止Service”

版权声明:本文为博主原创文章,转载请注明原文链接。 https://blog.csdn.net/hao2244/article/details/45175529

    在Service类中,用于停止Service的方法有如下三个:

    1. public final void stopSelf();

    2. public final void stopSelf(int startId);

    3. public final boolean stopSelfResult(int startId);

    先说最好理解的,“public final void stopSelf()”。

    这个方法可以类比于Activity.finish()。作用就是简单停止当前Service。

    然后说一下后两个。

    后两个有着相同的参数 int startId。在讨论它之前,先得说一下onStartCommand(Intent intent, int flags,int startId)方法中的int startId参数,该参数代表当前service中的onStartCommand方法被调用的次数(可知onStartCommand第一次被调用时传入的startId值为1,在当前Service实例没被销毁的情况下,onStartCommand方法每被调用一次,传入的startId便会+1)。注意一下关键语句“当前Service实例没被销毁的情况下”,在当前Service实例被停止之后(例如调用了stopSelf()),Service若被再次启动,那启动的Service将是一个新的实例,startId将会从1开始重新计数。现在我们已经将onStartCommand(Intent intent, int flags, int startId)方法中的int startId参数讨论完了,接下来我们来看stopSelf(int startId)和stopSelfResult(int startId)中的参数。这两个方法中的参数起的作用是相同的。如果我们调用这两个方法中任意一个时,如果传入的值和onStartCommand最后一次被调用时所被传入的startId值相同时,当前Service实例将被停止;如果不相同,则当前Service实例不会被停止。这两个方法的区别就在于其返回值,stopSelfResult(int startId)在传入的值和onStartCommand中的startId相等时返回true,否则返回false;stopSelf(int startId)的返回值为void,自然不必多说。

猜你喜欢

转载自blog.csdn.net/hao2244/article/details/45175529