Andrei V
Andrei V

Reputation: 1538

Foreground service started before main Activity?

I am running foreground service that uses packageName from MainActivity. Way I implement it is I create static variable instance in the MainActivity. It gets populated with value inside onCreate, onStart and onResume. Then I access MainActivty.instance.packageName from foreground service.

Sometime I see exceptions (when app comes back from background or sleep mode) that complains that MainActivty.instance is null when accessed from my foreground service. In theory it should not happen since Activity should be activated first which in turn will set MainActivty.instance. How is it possible?

UPDATE: I also use singleton MainActivity from other services and helper/utility classes to do following: to open MaterialDialog, getContentResolver(), getPackageManager(), getSystemService(), startActivityForResult(). So its very convenient to have access to my MainActivity from everywhere.

Would love to hear better suggestions.

Upvotes: 0

Views: 168

Answers (1)

Naresh NK
Naresh NK

Reputation: 1066

You can access packageName inside the Service itself, just use the applicationContext in the service to access the packageName -

class YourService : Service() {

  ....
  applicationContext.packageName
  ....
  

}

No need to access the packageName via Activity context and also the way you are doing this is bad practice, it will cause memory leaks in your app (static instance of your activity will remain in MainActivity.instance variable even if your Activity is destroyed, causing memory leak)

Upvotes: 1

Related Questions