gpt4 book ai didi

java - IntentService - startService 上的 NullPointerExecption

转载 作者:行者123 更新时间:2023-12-02 03:22:05 25 4
gpt4 key购买 nike

我正在尝试使用 IntentService Android 提供的功能尝试在后台运行一些计算

我从昨天开始就一直在研究这个问题,但似乎找不到任何有效的解决方案。
我已经查看了很多有关 IntentService 的问题,并尝试应用建议的修复程序,但我的似乎无法工作。

我尝试过传递各种不同的 context/ Activity/getApplicationContext()/this/getBaseContext()从我调用该函数的 Activity 中,但我仍然收到 空对象引用 错误

"Attempt to invoke virtual method 'android.content.ComponentName android.content.Context.startService(android.content.Intent)' on a null object reference"

应用程序在函数的第 3 行崩溃,其中 startService()被调用(请参阅下面的代码)

//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 list 中声明了该服务以链接到 MyCurrentClass 并尝试 bindService()从 Activity 中:它被调用了,但它也不起作用。

以下是我查看并尝试过但失败的一些问题/解决方案:

我实际上看过很多其他帖子,但太多了。

希望我提供的信息足够。如果不是,请告诉我可能缺少什么,我将使用所需的信息更新问题。

最佳答案

使用context,就像您在从 Activity 中收到的评论中提到的那样,因为在这种情况下,您当前的类没有上下文。 read for further details

context.startService(inputIntent); 

而不是

this.startService(inputIntent); 

关于java - IntentService - startService 上的 NullPointerExecption,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39483658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com