java - 启动 IntentService 的空指针异常

标签 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 文档建模的。只是一个带有 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

最佳答案

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

关于java - 启动 IntentService 的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7165215/

相关文章:

java - 生成一个没有某些字符的随机字母数字字符串

java - Spring data rest - 处理实体验证

c# - 使用 C# 启动服务

Java环境路径设置

java - 从构建器返回 A<List<Foo>>

java - 错误:不兼容的类型:org.opencv.core.Point无法转换为android.graphics.Point

android - 如何以编程方式将 android 的默认应用程序集成到我们的应用程序中

android - 如何使用 Android AudioRecord 和 MediaCodec 作为音频编码器正确处理 PTS?

python - 如何将 Flask/gunicorn 应用程序作为 systemd 服务运行

android - 在 Android 后台保持蓝牙连接?