Back to project page BtDemo.
The source code is released under:
Apache License
If you think the Android project BtDemo listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package cn.edu.hust.cm.bt.demo; //ww w . j a v a 2s. c om 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.util.Log; public abstract class BaseBinderActivity extends Activity { public static final String TAG = "BaseBinderActivity"; protected boolean mIsBound; protected BaseBinderService mService; protected ServiceConnection mConn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onDestroy() { super.onDestroy(); doUnbind(); } public boolean doBind(Intent service) { if (!mIsBound) { return bindService(service, getServiceConnection0(), Context.BIND_AUTO_CREATE); } return mIsBound; } /** * Already called in onDestroy to prevent ServiceConnection leaked */ public void doUnbind() { if (mIsBound) { Log.i(TAG, "unbind " + mConn); unbindService(getServiceConnection0()); } } /** * We can do something after ServiceConnection established */ protected void postConnected() { } private ServiceConnection getServiceConnection0() { if (null == mConn) { mConn = getServiceConnection(); if (null == mConn) { // if there is no customized ServiceConnection, use the default one instead mConn = getDefaultServiceConnection(); } } return mConn; } /** * Customized ServiceConnection provided here * @return */ protected ServiceConnection getServiceConnection() { return null; } private ServiceConnection getDefaultServiceConnection() { return new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { mService = null; mIsBound = false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { mIsBound = true; mService = ((LocalBinder) service).getService(); postConnected(); } }; } }