Android calling IntentService class from a Service Class

后端 未结 1 447
执念已碎
执念已碎 2021-01-29 02:48

Can we call IntentService class from a running Service class .

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


        
相关标签:
1条回答
  • 2021-01-29 03:21

    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.

    0 讨论(0)
提交回复
热议问题