service里:
// 初始化广播接收器
private MyBroadcastReceiver receviver = null;
private void initBroadcastReceiver() {
// 创建一个IntentFilter对象,将其action指定为BluetoothDevice.ACTION_FOUND
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Constant.RELOAD_DATA);
intentFilter.addAction(Constant.RELOAD_OPEN_DOORS_DISTANCE);
receviver = new MyBroadcastReceiver();
// 注册广播接收器
registerReceiver(receviver, intentFilter);
}
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Constant.RELOAD_DATA)) {
// 重新加载数据库
System.out.println("get RELOAD_DATA");
getDoorInfFromDB();
return;
} else if (action.equals(Constant.RELOAD_OPEN_DOORS_DISTANCE)) {
// 这里得到实际距离,要将实际距离进行转化
/**
* 0========-5
* 10=======-85
*/
openDistance = getSharedPreferences(Constant.NAME_CONFIG, Context.MODE_PRIVATE).getInt(Constant.KEY_DOOR_DISTANCE, -85);
if (openDistance > -50) {
openDistance = -50;
}
return;
} else if (action.equals(Constant.RELOAD_OPEN_DOORS_DISTANCE_DEF)) {
SharedPreferences preferences = getSharedPreferences(Constant.NAME_CONFIG, Context.MODE_PRIVATE);
openDistance = preferences.getInt(Constant.KEY_DOOR_DISTANCE_DEFAULT, -75);
return;
}
}
}
在activity里:
// 发送广播去重新加载数据
broadcastUpdate(Constant.RELOAD_DATA);
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
在onDestroy方法里要解除注册:
if (receviver != null) {
unregisterReceiver(receviver);
}