我正在尝试将API 21+的功能添加到支持18的应用程序中。我有检查以确保运行应用程序的手机在API 21上用于各种方法,但我需要声明一个我的活动顶部的对象,这阻止了应用程序在旧的API手机上工作。是否有任何用于包装该对象的模式,以便它只为运行API 21+的设备创建,并为低于此值的任何内容返回null?对于上下文,这适用于蓝牙广告客户,我需要此对象来创建/停止广告:
private AdvertiseCallback mAdvertisingCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
}
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
}
};
而我的广告数据是一种方法:
private void advertise( String stufftoadvertise ) {
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && BluetoothAdapter.getDefaultAdapter().isMultipleAdvertisementSupported() ) {
BluetoothLeAdvertiser advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
AdvertiseSettings settings = new AdvertiseSettings.Builder()
.setAdvertiseMode( AdvertiseSettings.ADVERTISE_MODE_LOW_POWER )
.setTxPowerLevel( AdvertiseSettings.ADVERTISE_TX_POWER_LOW )
.setConnectable( false )
.build();
UUID uuid = UUID.fromString( getString( R.string.uuid_advertise ));
ParcelUuid pUuid = new ParcelUuid( uuid );
AdvertiseData data = new AdvertiseData.Builder()
.setIncludeDeviceName( true )
.addServiceUuid( pUuid )
.addServiceData( pUuid, stufftoadvertise.getBytes( Charset.forName("UTF-8") ) )
.build();
advertiser.startAdvertising(settings, data, mAdvertisingCallback);
}
}
答案 0 :(得分:0)
不确定这是否是最好的解决方案,但我确实找到了一种方法来实现这一目标。我刚刚创建了一个静态类,它返回一个回调的单例,并且只在API为21或更高时才调用该类
@TargetApi(21)
public class AdvertiseCallbackCreator {
private static final AdvertiseCallback mAdvertisingCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
}
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
}
};
public static AdvertiseCallback getAdvertiseCallback() {
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && BluetoothAdapter.getDefaultAdapter().isMultipleAdvertisementSupported() ) {
return mAdvertisingCallback;
} else return null;
}
}
答案 1 :(得分:0)
除非你是API 21+,否则不要实例化对象。例如,不要这样做:
android.*
但是,请执行此操作:
private AdvertiseCallback mAdvertisingCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
}
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
}
};
然后当你需要使用它时,只需在那里初始化它:
private class CustomAdvertiseCallback implements AdvertiseCallback {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
}
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
}
}