is it bad to use public static fields/variables?

2019-07-21 12:08发布

I started learning about Android Development, and I read about static variables are bad and may leak memory because they are not garbage collectable.

I've used some in certain situations, but I am so concerned it may leak memory.

Can someone please look at my code below and see if they leak memory or not?

MainActivity.java

public class MainActivity extends Activity {

public static boolean IS_ACTIVITY_OPEN;
public static ImageView image;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);        
        IS_ACTIVITY_OPEN = true;

    ....

    ....

    VoiceReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(final Context context, Intent intent) {
       .....
    };
    registerReceiver(VoiceReceiver, new IntentFilter(BroadCastReceivers.VoiceIntent));

@Override
public void onDestroy() {
    super.onDestroy();  
    unregisterReceiver(VoiceReceiver);          
    IS_ACTIVITY_OPEN = false;
    }   
}

Picture.java

MainActivity.image.setImageBitmap(resizedBitmap);

.....

.....

BroadCast.java

if (!MainAcitivty.IS_ACTIVITY_OPEN) {
    //start an activity
    Intent intent2 = new Intent(context, MainAcitivty.class);            
    intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent2); 
    handler=  new Handler();
    MyPostDelay = new Runnable() {

        @Override
        public void run() { 
            context.sendBroadcast(new Intent(VoiceIntent));
        }
    };
    handler.postDelayed(MyPostDelay, 300);
}
else
{
    context.sendBroadcast(new Intent(VoiceleIntent));
}

Thank you very much in advance.

1条回答
smile是对你的礼貌
2楼-- · 2019-07-21 12:25

Take a look at Avoiding memory leaks article on the Android Developers Blog. Keeping a static field holding a Context, or any other class that has a (strong) reference to a Context (such as any View) will mean that the garbage collector will not be able to reclaim the storage allocated by the Context. If the Context is an Application, thats OK because they live for as long as your app does and wouldn't be garbage collected anyway. But in case of Views, Context is likely an Activity which should be garbage collected as soon as possible.

That doesn't mean that all static fields will catastrophically leak memory. If they're primitive types, or simple classes, or even more complex classes with weak references to other classes, they might not prevent the garbage collector from reclaiming a lot of memory. But generally having static and especially public static fields is a code smell and should probably be avoided so the code is easier to maintain later.

查看更多
登录 后发表回答