0

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.

Andrei V
  • 1,468
  • 3
  • 17
  • 32

1 Answers1

1

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)

Naresh NK
  • 1,036
  • 1
  • 9
  • 16
  • Thank you. For package name I will do that. I expanded my question – Andrei V Dec 11 '22 at 19:04
  • @AndreiV as I added in my answer using a static variable for Activity will result in Memory leak, So either use application context for non UI related things and directly use Activity context from within the Activity for UI related things like Dialog. Read more here - https://stackoverflow.com/q/44934008/9854554 – Naresh NK Dec 12 '22 at 04:55
  • Also In helper/utils pass the required Context/Activity through constructor or member function argument. – Naresh NK Dec 12 '22 at 05:04
  • But in the Activity lifecycle methods I update singleton to always point to the latest new Activity. If activity always starts first then singleton should be working. Can you please explain where in this logic can leaks happen? – Andrei V Dec 12 '22 at 07:58
  • It's a bad practice that results in memory leaks. You can use lifecycle methods to update it but still it's a bad practice that no Android developer would recommend. You can create other question with your use case to know how to ignore this style of code. – Naresh NK Dec 12 '22 at 12:39