Android developer.

艺术之旅

出现leaked ServiceConnection 的解决办法

欢迎转载,但请附上出处~~
http://blog.csdn.net/as02446418/article/details/46790843

出现leaked ServiceConnection 的解决办法

Activity com.skyace.service.MainActivity has leaked ServiceConnection com.phicomm.hu.MainActivity that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.skyace.service.MainActivity has leaked ServiceConnection com.skyace.service.MainActivity$1@41cd81f0 that was originally bound here
  • 起因

    最近在做项目时,用到了关于service与actvity绑定的知识,但是在调试过程中无意中出现了上述的bug,后来经分析,当清理后台activity时就会报这个错误,我们来看一下代码:


public class MainActivity extends Activity 
{
    //定义浮动窗口布局
    LinearLayout mFloatLayout;
    //创建浮动窗口设置布局参数的对象
    WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
    WindowManager mWindowManager;
    //定义对getInformation的引用
    GetInformation getInformation;
    //** Called when the activity is first created. 

    FxService.MyBinder myBinder;


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button start = (Button)findViewById(R.id.start_id);

        Button remove = (Button)findViewById(R.id.remove_id);

        GetInformation.createGetInformation(this);
        getInformation = GetInformation.getGetInformation();

        start.setOnClickListener(new OnClickListener() 
        {

            @Override
            public void onClick(View v) 
            {

                bindService();
            }
        });

        remove.setOnClickListener(new OnClickListener() 
        {

            @Override
            public void onClick(View v) 
            {
                unbindService(conn);
            }
        });

    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("--Service Disconnected--");

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("--Service Connected--");
            myBinder = (FxService.MyBinder) service;
            FxService fxService = myBinder.getService();
        }
    };

    private void bindService(){
        Intent intent = new Intent(MainActivity.this, FxService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);
    }

后来在之后加上了重写的onDestroy的回调方法中加入了对服务的解绑操作即 unbindService就成功解决了,如下:

@Override
    protected void onDestroy() {
        // TODO 自动生成的方法存根
        super.onDestroy();
        unbindService(conn);
    }

其实这个错误有点类似于dialog中如果activity已经finish()掉但dialog还没dissmiss()时也会报类似的溢出错误,希望大家引以为戒,多多注意自己的代码习惯,做好防护的措施。

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/as02446418/article/details/46790843
个人分类: Android
上一篇Android 内存溢出问题分析
下一篇快速排序算法之JAVA实现
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭