应用程序强制关闭时会触发Android Service onStartCommand()

时间:2013-07-16 13:02:06

标签: android service android-activity nullpointerexception

我从Service开始Activity,然后将活动绑定到它。 如果我尝试从任务管理器强制关闭应用程序,则调用Service onStartCommand()方法并调用NullPointerException。我不明白为什么调用onStartCommand()。

服务现在刚刚onStartCommand()覆盖:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Bundle bundle = intent.getExtras();  //This is line 24
    //some stuff to get strings from bundle
    return super.onStartCommand(intent, flags, startId);
}

例外:

07-16 14:49:02.190: E/AndroidRuntime(24607): FATAL EXCEPTION: main
07-16 14:49:02.190: E/AndroidRuntime(24607): java.lang.RuntimeException: Unable to start service com.app.GameService@420edf78 with null: java.lang.NullPointerException
07-16 14:49:02.190: E/AndroidRuntime(24607):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2782)
07-16 14:49:02.190: E/AndroidRuntime(24607):    at android.app.ActivityThread.access$2000(ActivityThread.java:152)
07-16 14:49:02.190: E/AndroidRuntime(24607):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1385)
07-16 14:49:02.190: E/AndroidRuntime(24607):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-16 14:49:02.190: E/AndroidRuntime(24607):    at android.os.Looper.loop(Looper.java:137)
07-16 14:49:02.190: E/AndroidRuntime(24607):    at android.app.ActivityThread.main(ActivityThread.java:5328)
07-16 14:49:02.190: E/AndroidRuntime(24607):    at java.lang.reflect.Method.invokeNative(Native Method)
07-16 14:49:02.190: E/AndroidRuntime(24607):    at java.lang.reflect.Method.invoke(Method.java:511)
07-16 14:49:02.190: E/AndroidRuntime(24607):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
07-16 14:49:02.190: E/AndroidRuntime(24607):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
07-16 14:49:02.190: E/AndroidRuntime(24607):    at dalvik.system.NativeStart.main(Native Method)
07-16 14:49:02.190: E/AndroidRuntime(24607): Caused by: java.lang.NullPointerException
07-16 14:49:02.190: E/AndroidRuntime(24607):    at com.app.GameService.onStartCommand(GameService.java:24)
07-16 14:49:02.190: E/AndroidRuntime(24607):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2765)
07-16 14:49:02.190: E/AndroidRuntime(24607):    ... 10 more

2 个答案:

答案 0 :(得分:0)

你可以像这样使用......

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Bundle bundle = getIntent.getExtras();
    if (bundle!=null) {
        Bundle bundle = intent.getExtras(); 
        }
    } else {
        Log.i("Log", "Bundle is null");

    }
}

答案 1 :(得分:0)

可能会从onStartCommand()返回Service.Start_not_sticky。我不知道你的情况,只是试一试。

这有助于更好地理解完成/重启服务的不同模式 - http://developer.android.com/reference/android/app/Service.html#START_NOT_STICKY