2013-03-23 40 views
0

我一直在寻找一个答案,但还没有找到一种方法来做到这一点但我希望有人可以点我在正确的方向的Android Suporting旧的SDK,其中方法不可用

我想支持sdk8和起来,有这种方法createInsecureRfcommSocketToServiceRecordandroid.bluetooth.BluetoothDevice库 支撑在SDk10最多只有

快速和肮脏的是使minSDK = 10,但我不想离开我的用户旧设备出冷

我见过很多涉及(或者我应该说古怪)的尝试方法,反思?但他们都失败了我,我认为将是最简单的方法:

if(Build.VERSION.SDK_INT>=10) 
{ 
    BluetoothDevice device; 
    Class myC = ClassforName("android.bluetooth.BluetoothDevice") 
    Method myM = myC.getDeclaredMethod("createInsecureRfcommSocketToServiceRecord"); 
    BluetoothSocket bb = (BluetoothSocket)myM.invoke(device, MYUUID); 
} 

但它抛出一个NoSuchExceptionMethod,所以看起来也许库必须有其他的名字????或者你会如何处理?

在此先感谢

+0

看来你似乎缺少方法的参数... UUID.class – TacB0sS 2013-03-23 22:26:56

回答

0

如果你不想增加你的minSDK版本,你要么换行与反思你的电话......

BluetoothDevice device; 

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) { 
    Class myC = ClassforName("android.bluetooth.BluetoothDevice") 
    Method myM = myC.getDeclaredMethod("createInsecureRfcommSocketToServiceRecord", 
             new Class[] { UUID.class }); 
    BluetoothSocket bb = (BluetoothSocket)myM.invoke(device, MYUUID); 
} 

...或者您提供只有一些空方法存根的(摘要)类android.bluetooth.BluetoothDevice。这使您可以毫无错误地编译源代码。在运行期间,虚拟机将尝试从系统加载该类。

public abstract class BluetoothDevice { 

    BluetoothDevice() { 
    } 

    public void createInsecureRfcommSocketToServiceRecord(UUID uuid) { 
    } 
} 

的类必须发生在根源 /机器人/蓝牙。无论如何,限制任何呼叫到正确的操作系统版本是很重要的(参见上面的代码),否则你可能会得到一个异常。

最后:不要忘记方法的签名(参数)(在getDeclaredMethod())。

干杯!

+0

谢谢!!!抽象类听起来很酷,但它没有奏效。另一种方法不会给语法错误了,但BT不起作用可能我应该去那边 – becker 2013-03-24 00:00:51

+0

实现抽象类可能非常棘手,因为通常你不能直接实例化它,并且存在不能工作的情况好。 – Trinimon 2013-03-24 11:04:15

0

你也必须通过声明参数

Class myC = ClassforName("android.bluetooth.BluetoothDevice") 
Method myM = myC.getDeclaredMethod("createInsecureRfcommSocketToServiceRecord",UUID.class); 
相关问题