1. service程序编写
public class BluetoothService extends Service {
private ICallBack iCallBack;
private IBinder binder = new BluetoothService.LocalBinder();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return binder;
}
public class LocalBinder extends Binder {
public BluetoothService getService() {
return BluetoothService.this;
}
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
2. activity中调用
public BluetoothService mBluetoothService;
2.1 service的连接与断开
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mBluetoothService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBluetoothService = ((BluetoothService.LocalBinder) service).getService();
Log.i("huzh", "onServiceConnected");
}
};
2.2 启动service
Intent intent = new Intent(this, BluetoothService.class);
startService(intent);
getApplicationContext().bindService(intent, connection, Context.BIND_AUTO_CREATE);