我試圖使用Android提供的IntentService
功能嘗試在後臺中運行一些計算。IntentService - startService上的NullPointerExecption
我從昨天開始就一直在努力,但我似乎無法找到任何有效的解決方案。
我已經看過不少有關IntentService的SO問題,並嘗試應用建議的修復,但我的工作似乎無法完成。
我試圖通過各種不同的context
/活動比較/ getApplicationContext()
/this
/getBaseContext()
從那裏我調用函數的活動,但我仍然得到一個空對象引用錯誤
「嘗試調用虛擬方法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!
}
PS:大部分我已經看過了解決方案,似乎只有1個活動,但我的應用程序在不同的活動之間切換。 (不知道這是否重要)但最重要的是我正在處理的類是一個普通的Java類,它擴展了IntentService並且它不是一個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
我已經實際上看了很多其他帖子,但是太多了。
希望我提供的信息就足夠了。如果不是,請讓我知道可能會丟失什麼,然後用所需的信息更新問題。
請顯示[MCVE。什麼是'這個'?同時顯示清單 –
在傳入方法的'Context'上調用'startService()'。另外,如果你將'Context'交給'MyCurrentClass',如果可能本身不應該是'Context',並且你的方法可能是'static'。 –
@MikeM。問題...爲什麼'this.startService'爲'Context.startService'引發一個NPE?那不是說'這個'是空的,這是不可能的? –