Вопрос

I'm trying to track down an issue where some users have started getting out of memory errors in KitKat. I've not seen them in previous versions but I know memory usage has sometimes got much higher than I'd expect.

I'm trying to go through the app identifying things that are stored in static variables at the moment within the app and there's a few that I was wondering if they would cause issues.

They are:

Notification   //as in when a notification is raise
PendingIntents   
BroadcastReceiver //as in the object passed to: context.registerReceiver     
SharedPreferences 

From what I can tell I don't think these hold the context objects, but I'm not sure.

I try to make sure when using context objects I'm only using Activity contexts when the scope is only applicable for the activity and when that context is needed. For other situations I use the application context.

Это было полезно?

Решение

I would suggest you to run your app and use all activities your app contains of and also switching orientation several times, then exit the app and trigger a GC (there's buttons for all of this) after that dump a hprof (this asumes you are using Eclipse) and fire the leak suspects report, use the histogram button to view what allocations have been done and sort of #objects (try to filter on your package name since String / byte[] etc tend to dominate such a leak suspect report even though the don't have to be leaks). A guide to: debugging memory in Android.

As for your questions to those specific classes (when i say, "could leak a context" i mean activty context, since application is singleton):

  • Notifications are preferably handled by the Notification.Builder, that one takes a context so holding on to notification in a static variable could leak a context

  • PendingIntents are obtained from helper methods where context are sent in see PendingIntent could leak context as well

  • BroadcastReceivers can be registered in manifest (not leaking context here) or at run time, if you are not unregistering in onPause (registering in onResume) you could leak the BroadcastReceiver which in turn leaks the current activity context (this)

  • SharedPreferences are fetched from the current activity if your activity gets recreated there might be a leak as well

This is a hard topic, that's why i suggest you to profile your are app i suggest in the top of this answer. Other than that i don't quite get the point of holding on to several of the asked classes as static instnace variables, what do you want to achieve with that? Especially if you are not sure if you leak contexts or not.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top