空指针异常启动意向服务
2022-09-02 02:30:00
我有一个意向服务,我正在尝试启动。当我这样做时,它会吐出这个:
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)
}
});
}
My IntentService是以谷歌文档为蓝本的。只是一个具有 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