从服务创建的动态视图未收集垃圾

时间:2015-05-28 12:51:46

标签: android out-of-memory android-service

我正在使用动态视图。我正在运行一项服务。当该服务收到广播时,我将Myview添加到窗口管理器,并在用户执行某些操作后将其删除。但是由于服务一直在运行,我每次播放时都会添加动态视图“myView”。问题是,从窗口管理器中删除它们后,它们不会收集垃圾,而且堆内存分配会不断增加。不知道为什么?因为它里面有位图。在5-6个动作之后,我得到OutOfMemoryException。

   public class Myservice extends Service{                                                        
       private ParentView myView;
       WakeReceiver receiver;

        @Override
        public void onCreate()
        {
          super.onCreate();
          registerBroadCastReceiver();
        }


        //Performed when broadcast recieved
        public void addLayout() {
           WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
           myView = new ParentView(this);
           windowManager.addView(myView, getLayoutParam());

        }

        //Performed when user performs action on ParentView
        public void removeLayout() {
           WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
           windowManager.removeView(myView);

        }

         private void registerBroadCastReceiver() {
             IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);

             receiver = new WakeReceiver();
             registerReceiver(receiver, filter);

        }

         private WindowManager.LayoutParams getLayoutParam() {
                 WindowManager.LayoutParams localLayoutParams = new     WindowManager.LayoutParams();

                 localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                 localLayoutParams.height = (int) (WindowManager.LayoutParams.MATCH_PARENT);
                 return localLayoutParams;

        }


}

//父视图代码

 public class ParentView extends RelativeLayout {


      MyService topService;  

      public ParentView(MyService topService) {
         super(topService);
         this.topService = topService;
         LayoutInflater.from(topService).inflate(R.layout.parent_layout, this);                 

           setBackgroundDrawable(topService.getResources()
              .getDrawable(R.drawable.sample_image));
       }

       @Override
       public boolean onTouchEvent(MotionEvent event) {
         topService.removeLayout();  
      }



}

1 个答案:

答案 0 :(得分:0)

使用system.gc();这有助于我一次。它调用垃圾收集器。尝试一下,如果有效,请回复我。