【发布时间】:2016-11-04 11:54:50
【问题描述】:
我正在尝试在设备上安装的其他应用中启动服务。使用 startService 时出现 NullPointerException
public void notConnected(){
Log.i(TAG,"no connection... reconnecting.");
Intent reset = new Intent("com.famoco.intent.action.TOGGLE_DATA");
Log.i(TAG,"calling " + reset.getAction());
if(reset.getAction().equals("com.famoco.intent.action.TOGGLE_DATA"))
{
startService(reset);
}
else
{
Log.i(TAG,"couldn't start service");
}
}
这是错误日志
E/AndroidRuntime: FATAL EXCEPTION: IntentService[MyAppCommService]
Process: com.myapppackage.MyApp, PID: 8583
java.lang.NullPointerException
at android.content.ContextWrapper.startService(ContextWrapper.java:494)
at com.myapppackage.MyApplocation.activity.MyAppActivity.notConnected(MyAppActivity.java:591)
at com.myapppackage.MyApplocation.api.MyAppApi.submitClock(MyAppApi.java:228)
at com.myapppackage.MyApplocation.service.MyAppCommService.submitTags(MyAppCommService.java:52)
at com.myapppackage.MyApplocation.service.MyAppCommService.onHandleIntent(MyAppCommService.java:98)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.os.HandlerThread.run(HandlerThread.java:61)
原来我的上下文返回 null,我通过在 onCreate 中获取上下文并调用 myContext.startservice 来修复它。
【问题讨论】:
-
你能分享更多代码吗?
-
你需要什么代码?
-
我不知道。也许您需要像这样指定您的服务:
startService(new Intent(this, MyService.class));
标签: android android-intent service