【发布时间】:2016-09-14 06:18:20
【问题描述】:
我正在尝试使用 Android 提供的IntentService 功能尝试在后台运行一些计算。
我从昨天开始一直在研究这个问题,但我似乎找不到任何有效的解决方案。
我已经查看了很多关于 IntentService 的 SO 问题,并尝试应用建议的修复程序,但我的似乎无法正常工作。
我尝试从调用函数的 Activity 中传入各种不同的 context / Activies / getApplicationContext() / this / getBaseContext(),但我仍然得到一个 null 对象引用错误
"尝试调用虚拟方法'android.content.ComponentName android.content.Context.startService(android.content.Intent)' 在一个 空对象引用”
应用程序在调用 startService() 的函数的第 3 行崩溃(请参阅下面的代码)
//This function is from MyCurrentClass.class - it is a Singleton and its being called from another activity where it passes in its context
public void notify (Context context, JSONObject responseFromDb){
Intent inputIntent = new Intent(context, MyCurrentClass.class);
inputIntent.putExtra("responseFromDB", responseFromDb.toString());
this.startService(inputIntent); //crashes here!
}
P.S.:我看过的大多数解决方案似乎只有 1 个 Activity,但我的应用正在不同的 Activity 之间切换。 (不确定这是否重要)但最重要的是我正在处理的类是一个扩展 IntentService 的普通 Java 类,它不是一个 Activity 类。
我还在我的 Android 清单中声明了该服务以链接到 MyCurrentClass,并从 Activity 中尝试了bindService():它被调用了,但它也不起作用。
以下是我查看并尝试但失败的一些问题/解决方案:
- 'java.lang.String android.content.Context.getPackageName()' on a null object reference
- Trying to start a service on android and get a null object
- Starting Android IntentService with explicit intent NullPointerException
- How to get Context in an Intent Service
其实我看过很多其他的帖子,但是太多了。
希望我提供的信息已经足够。如果不是,请让我知道可能缺少什么,我将使用所需信息更新问题。
【问题讨论】:
-
请显示minimal reproducible example。
this是什么?同时显示清单 -
在您传递给方法的
Context上调用startService()。此外,如果您将Context传递给MyCurrentClass,则可能不应该是Context本身,而您的方法可能是static。 -
@MikeM。问题...为什么
this.startService会为Context.startService抛出NPE?那不是说this为空,这真的不可能吗? -
@cricket_007 无论
MyCurrentClass是什么类型,我都假设它最终是一个ContextWrapper,它保留了一个Context字段,实际上调用了startService()和startActivity()之类的方法。当系统没有正确实例化这样的类时,该字段为空,因此为 NPE。 -
@PavneetSingh yupp :) 我也从他/她的 POV 中理解,但这实际上是因为我在 24 小时内一直在寻找问题本身并且一直无法解决它,这就是我决定来这里寻求帮助>
标签: java android android-intent nullpointerexception android-intentservice