android - bindservice 执行ondestroy后有没有被销毁

【字号: 日期:2022-12-01浏览:26作者:雯心

问题描述

在mainActivity中我调用了unbindservice,并且在log中看到执行了bindservice的oddestroy函数,这样应该是销毁了service,但是我在mainActivity中再调用binder.getthis还能输出bindservice的this.tostring。这又表明service还存在这是怎么回事

这是bindservice的定义public class BindService extends Service {

private int count=0;private boolean quit=false;private String LOG_TAG='--BindService--';private MyBinder binder=new MyBinder();

public class MyBinder extends Binder{ public int getCount() {return count; } public boolean getQuit() {return quit; } public String getthis() {return test(); }}@Overridepublic IBinder onBind(Intent intent)//?这里的intent 有什么用{ Log.w(LOG_TAG,'onBind'); return binder;}@Overridepublic void onCreate(){ super.onCreate(); Log.w(LOG_TAG,'on Created'); new Thread(){@Overridepublic void run(){ while (!quit) {try { Thread.sleep(1000);}catch (InterruptedException e){}count ++; }} }.start();}@Overridepublic boolean onUnbind(Intent intent){ this.quit=true; Log.w(LOG_TAG,'Unbind'); return true;}@Overridepublic void onDestroy(){ super.onDestroy(); Log.w(LOG_TAG,'Destroy'); this.quit=true;}public String test(){ return this.toString();}

}

activity 代码:

public class BindServiceActivity extends AppCompatActivity {

private String LOG_TAG='--connection--';BindService.MyBinder binder;Intent intent;myConn conn=new myConn();class myConn implements ServiceConnection { private boolean actived=false; @Override public void onServiceConnected(ComponentName name, IBinder service) {actived=true;Log.w(LOG_TAG,'Connected');binder=(BindService.MyBinder)service; } @Override public void onServiceDisconnected(ComponentName name) {actived=false;Log.w(LOG_TAG,'Disconnected'); } public boolean isActived() {return actived; }}@Overridepublic void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.bindservice); intent=new Intent(this,BindService.class);}public void myBind(View view){ Log.w(LOG_TAG,'bind clicked'); bindService(intent,conn, Service.BIND_AUTO_CREATE);}public void myUnBind(View view){ // Log.w(LOG_TAG,binder.toString()); if(conn.isActived()) {if (!binder.getQuit()){ //这里仅仅是解除conn 与 service 之间的关系,binder 并没有被销毁,因此还能调用getcount unbindService(conn);} else{ Toast.makeText(this, 'Conn is already disconnected', Toast.LENGTH_SHORT).show();} }else {Toast.makeText(this, 'Conn ia not connected', Toast.LENGTH_SHORT).show(); }}public void myShowStatus(View view) { if (conn.isActived()) {Log.w(LOG_TAG,binder.getthis());TextView txt=(TextView)findViewById(R.id.txt);txt.setText('Count of service is:' + binder.getCount());//Toast.makeText(this, 'Count of service is:' + binder.getCount(), Toast.LENGTH_SHORT).show(); }else {Toast.makeText(this, 'Conn ia not connected', Toast.LENGTH_SHORT).show(); }}public void myBack(View s){ finish();}

}

问题解答

回答1:

你BindService的内部类MyBinder持有了外部类BindService的实例

相关文章: