Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getApplicationContext() returns null in a Service

I have a Service in it's own process, I've declared it in manifest like that:

   <service
        android:name="com.discountscatcher.util.PointService"
        android:configChanges="orientation"
        android:process=":pointservice" >
    </service>

But onStartCommand I was trying to get an ApplicationContext, but it always returns null, what I can forget?

    public int onStartCommand(Intent intent, int flags, int startId) {
    android.os.Debug.waitForDebugger();
    Context mContext = getApplicationContext();
    return Service.START_STICKY;
}

and I starting it like that:

    startService(new Intent(getApplicationContext(), PointService.class));

in Myactivity OnCreate

any ideas?

like image 609
whizzzkey Avatar asked Dec 19 '13 07:12

whizzzkey


People also ask

When would you call getApplicationContext () and why?

This method is generally used for the application level and can be used to refer to all the activities. For example, if we want to access a variable throughout the android app, one has to use it via getApplicationContext().

Can getContext return null?

getContext can return null when fragment isn't attached to its host.

What is the difference between getApplicationContext and context?

You may wonder now, what is the difference between getContext() and getApplicationContext(). The difference is that Application's Context is not UI related. It means that, we shouldn't use it to Inflate a Layout, Start an Activity nor Show a Dialog.


1 Answers

You are running your Service in a different process so it has no communication with the Actual Application process..

Try to remove this line from your service

android:process=":pointservice"

After your application is finished Application context is becomes null. At most situations there is no need to run the service in a different process. Also it is not recommended.

For more information check here

  1. Service in another process
  2. service reference Example2
like image 100
kalyan pvs Avatar answered Oct 18 '22 09:10

kalyan pvs