启动IntentService的空指针异常

时间:2011-08-23 17:38:31

标签: java android service nullpointerexception android-context

我有一个我想要启动的IntentService。当我这样做时,它会吐出这个:

java.lang.RuntimeException: Unable to start service com.pec.testapp.service.NewsService@406bd940 with Intent { cmp=com.pec.testapp/.service.NewsService }: java.lang.NullPointerException
    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2173)
    ... (omitted for brevity)
Caused by: java.lang.NullPointerException
    at android.app.IntentService.onStart(IntentService.java:110)
    at android.app.IntentService.onStartCommand(IntentService.java:118)
    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2160)
    ... 10 more

我已经搜索了这个并查看了尽可能多的类似StackOverflow问题。然而,有一些微妙的差异,我无法解决。首先,异常中没有引用任何类。其次,通过更改上下文或双重检查来确定类似的问题,以确保它不为空。

我有代码检查是不是这样:

public Context context;
@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    context = getApplicationContext();

    if(context == null)
        Log.d("PECAPP","Context is null");

    setContentView(R.layout.news_layout);

    ...Omit button code...
    button.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View view){
            Intent i = new Intent(context, NewsService.class); // also tried NewsActivity.this
            if( i != null) // I know that this should never happen but I'm at a loss...
                startService(i); // I've also tried this with context.startService(i)
        }
    });

}

我的IntentService是在google docs之后建模的。只是一个带有onHandleIntent方法的构造函数。

public NewsService() {
    super("NewsService");
}

...omit onCreate() and onDestroy() since they haven't been implemented yet...

@Override
protected void onHandleIntent(Intent intent) throws IllegalArgumentException {
    Log.d("PECAPP","Got here..."); // I never actually got here...
    if(intent == null) Log.d("PECAPP","INTENT IS NULL");
    ...omit rest of code...
}

所以我的问题是这样的:这个例外是从哪里来的,有什么我可以做的不同以避免它吗?我的google-fu过去并没有让我失望,所以希望这个不是那些痛苦明显的答案之一。此外,如果有些事情可以做得更好或者只是丑陋,那么建设性的批评总是受到赞赏。

我将完整的异常,NewsActivity和NewsService放在pastebin上,以防我遗漏了一些东西。 http://pastebin.com/mR9Sykrq

2 个答案:

答案 0 :(得分:51)

如果您要覆盖onCreate()中的IntentService,请务必在其中调用super.onCreate()。这似乎很可能是你的问题。

答案 1 :(得分:8)

不确定是否是同样的问题,但我也使用了intentService,而我在使用时遇到了麻烦

context = getApplicationContext();

或     context = getBaseContext(); 我并没有凌驾于创造之上,所以之前的解决方案可能是您的解决方案, 我在“onHandleIntent”里面工作

我会在第一个时获得一个立即异常,稍后当我尝试使用第二个时会出现异常。

我最终意识到Intentservice本身就是Context的子类, 所以我在需要“上下文”实例的地方替换了“this”。

这解决了我的问题。