以明确的意图NullPointerException启动Android IntentService

我正在尝试从主活动中的clickhandler启动IntentService 。 我现在正在研究Intents但还没有完全掌握它。 我不确定我应该如何在这里实例化我的意图并将其传递给startService 。 我不知道为什么我要做这样的事情,在我的服务中不会使用Intent ,我知道。 我不知道如何调试这个问题。

从点击回调:

  this.commute = new Commute(); locationService = new LocationService(); locationService.setCommute(commute); // com.orm.SugarApp@8b2e18f is this.getApplicationContext() ... Context context = this.getBaseContext(); System.out.println("!!!!!!!!!!!!!!!!!!!!!"); System.out.println(context); Intent intent = new Intent(context, LocationService.class); System.out.println(locationService); System.out.println(intent); locationService.startService(intent); // <---- OFFENDING LINE System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@"); chronometer.setBase(SystemClock.elapsedRealtime()); chronometer.start(); commute.start(); 

回溯之前的logcat,没有任何对象为null …:

 01-27 09:53:44.465 2718-2718/org.skyl.commutetracker I/System.out﹕ !!!!!!!!!!!!!!!!!!!!! 01-27 09:53:44.466 2718-2718/org.skyl.commutetracker I/System.out﹕ android.app.ContextImpl@8b2e18f 01-27 09:53:44.466 2718-2718/org.skyl.commutetracker I/System.out﹕ org.skyl.commutetracker.services.LocationService@387dcc1c 01-27 09:53:44.466 2718-2718/org.skyl.commutetracker I/System.out﹕ Intent { cmp=org.skyl.commutetracker/.services.LocationService } 01-27 09:53:44.466 2718-2718/org.skyl.commutetracker D/AndroidRuntime﹕ Shutting down VM 01-27 09:53:44.481 2718-2718/org.skyl.commutetracker E/AndroidRuntime﹕ FATAL EXCEPTION: main 

这会导致以下回溯:

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ComponentName android.content.Context.startService(android.content.Intent)' on a null object reference at android.content.ContextWrapper.startService(ContextWrapper.java:515) at org.skyl.commutetracker.MainActivity.startCommute(MainActivity.java:86) at org.skyl.commutetracker.MainActivity.toggleClick(MainActivity.java:67)            at java.lang.reflect.Method.invoke(Native Method)            at java.lang.reflect.Method.invoke(Method.java:372) 

您不希望在第二行实例化LocationService。

您可能希望使用以下之一:

 context.bindService(intent, serviceConnection, boolean); 

要么

 context.startService(intent); 

对于您的IntentService,您可能希望使用startService。 绑定服务与意向服务不同。

此外,如果您想将通勤传递到意向服务,您可能希望将其作为额外服务传递给意图。

 intent.putExtra(String key, Parcelable item) 

putExtra被重载,因此只要Commute对象实现了一个必需的接口,它就可以正常工作。 有关Intent对象的更多信息,请访问http://developer.android.com/reference/android/content/Intent.html

您可以在http://developer.android.com/guide/components/services.html找到有关服务的更多信息

你没有创建服务的对象来启动它只需使用context来启动它

 Intent intent = new Intent(context, LocationService.class); context.startService(intent);