android Service组件的基本使用

本文详细介绍了一个基于Android平台的蓝牙服务编程实例。通过一个具体的BluetoothService类,展示了如何创建并实现服务端与客户端的连接,包括服务注册、绑定、启动及断开等关键步骤。同时,也介绍了在Activity中如何调用服务,实现与蓝牙设备的数据交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值