DBMNG数据库管理与应用

书籍是全世界的营养品。生活里没有书籍,就好像没有阳光;智慧里没有书籍,就好像鸟儿没有翅膀。
当前位置:首页 > 移动应用 > Android

Android出现leakedServiceConnection解决办法

see also : http://book.51cto.com/art/201006/206887.htm
在Android界面上调用service绑定方法,退出界面时候报告一堆错误 Activity has leaked ServiceConnection 等,应该重写onDestroy方法,取消绑定,这样就ok了。

package com.jiuqi.testservice01;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Button btn1;
private Button btn2;
private Button btn3;
private Button btn4;
private MyService myservice ;
public ServiceConnection serviceconnection = new ServiceConnection(){
@Override
public void onServiceDisconnected(ComponentName name){
myservice = null;
Toast.makeText(MainActivity.this, "MyService failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onServiceConnected(ComponentName name, IBinder service){
myservice = ((MyService.MyBinder)service).getService();
Toast.makeText(MainActivity.this, "MyService connected", Toast.LENGTH_SHORT).show();
}
};
private OnClickListener btnClickListener = new OnClickListener(){
@Override
public void onClick(View v){
Intent intent = new Intent();
intent.setClass(MainActivity.this,MyService.class);
switch(v.getId()){
case R.id.button1:
startService(intent);
break;
case R.id.button2:
stopService(intent);
break;
case R.id.button3:
bindService(intent, serviceconnection, Context.BIND_AUTO_CREATE);
break;
case R.id.button4:
unbindService(serviceconnection);
break;

default:
break;
}
}
};

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 = (Button)findViewById(R.id.button1);
        btn2 = (Button)findViewById(R.id.button2);
        btn3 = (Button)findViewById(R.id.button3);
        btn4 = (Button)findViewById(R.id.button4);
        btn1.setOnClickListener(btnClickListener);
        btn2.setOnClickListener(btnClickListener);
        btn3.setOnClickListener(btnClickListener);
        btn4.setOnClickListener(btnClickListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
   
    @Override
    protected void onDestroy(){
        super.onDestroy();
        unbindService(serviceconnection);
    }
}

本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号