Android calling IntentService class from a Service Class

人走茶凉 提交于 2019-12-02 09:32:19
varunkr

I have answered another question today which has exactly the same mistake.

ServiceA  obj1 = new ServiceA();
ob1.IntService();

You are trying to create a new object of a service which is a very very bad practice. You cannot simply create an object of service like this. All Services in Android must go through the Service lifecycle so that they have a valid context attached to them. In this case a valid context is not attached to the obj1 instance. So as a result the line

Intent MyIntentService = new Intent(this, MyIntentService.class);

causes a null pointer as 'this' is null. (Why? Because this refers to the context which has not yet been created as the service is not started using startService(intent))

Btw I don't understand why you are starting the intent service from within the service. you can simply do it from the DataProviderObserver class like this

Intent MyIntentService = new Intent(context, MyIntentService.class);
context.startService(MyIntentService);

since context is present in the class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!