当我通过Long Pressing Home键清除应用历史记录时,服务将关闭

时间:2014-06-23 10:14:50

标签: android android-intent android-service

我正在从活动中启动服务。然后服务运行倒数计时器以启动广告。

但当有人通过Long Pressing Home键清除我的应用历史记录时,它强制停止应用程序在我检查Intent附加功能的行。

它在该行给出NULL指针异常,如下所示,

public int onStartCommand(Intent intent, int flags, int startId) {  

if (intent.getExtras() != null && intent.hasExtra("type")) // <== NPE at this line 
        type = intent.getExtras().getString("type");
.
.
.
}

正如你所看到的,我甚至试图检查Intent是否为空intent.getExtras() != null但它仍然给NPE和Force关闭app。

为什么在清除历史记录和倒数计时器时调用onStartCommand完成并启动其他活动,然后启动另一项服务。

LogCat是:

java.lang.RuntimeException: Unable to start service com.main.example.AdService with null: java.lang.NullPointerException
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2660)
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at android.app.ActivityThread.access$1900(ActivityThread.java:149)
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1402)
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at android.os.Handler.dispatchMessage(Handler.java:99)
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at android.os.Looper.loop(Looper.java:153)
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at android.app.ActivityThread.main(ActivityThread.java:5000)
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at java.lang.reflect.Method.invokeNative(Native Method)
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at java.lang.reflect.Method.invoke(Method.java:511)
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at dalvik.system.NativeStart.main(Native Method)
        06-23 13:58:05.004: E/AndroidRuntime(12667): Caused by: java.lang.NullPointerException
        06-23 13:58:05.004: E/AndroidRuntime(6295): com.main.example.AdService.onStartCommand(AdService.java:83)
        06-23 13:58:05.004: E/AndroidRuntime(12667):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2643)

1 个答案:

答案 0 :(得分:0)

Intent本身就是null。当Android重新启动您的服务时,这是START_STICKY的预期行为,如the documentation for START_STICKY中所述。