因项目需求的需要,需要实现android TV 机顶盒连接成功的蓝牙遥控器的低电量提醒。根据需求,要先获得已连接的蓝牙设备的电量,再根据电量的值做判断提醒用户。
下面直接看代码,本项目中一共有三个类,初始MainActivity,MyBroadcastReceiver,MyService.其中,MainActivity不做任何修改,MyBroadcastReceiver监听开机完成广播,启动服务MyService,读取电量以及提醒的功能全都在服务中实现。
MyBroadcastReceiver类:
public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("aaa" , "Boot Completeed ."); Intent service = new Intent(context,MyService.class); context.startService(service); } }
MyService类:
public class MyService extends Service { private static final boolean DEBUG = false; private static final String TAG = "aaa"; public static Context context; BluetoothDevice mDevice; BluetoothGatt mBluetoothGatt; IntentFilter filter ; private static final UUID GATT_BATTERY_SERVICE_UUID = UUID.fromString("0000180f-0000-1000-8000-00805f9b34fb"); private static final UUID GATT_BATTERY_LEVEL_CHARACTERISTIC_UUID = UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb"); private static final String KEY_BATTERY = "battery"; private Handler handler; @Override public void onCreate() { Log.d("aaa" , "service created."); handler = new Handler(); context = getApplicationContext(); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int start