How to detect the BT headset or wired headset in a

2019-09-09 19:26发布

问题:

In my application i want to detect the BT headset or wired headset in android. I refer http://developer.android.com/guide/topics/connectivity/bluetooth.html code from this link. They mention that only 3.0 and above version of android can support the BluetoothHeadset and BluetoothProfile class. Which is helpful to detect the BT headset. Now i want the same functionality in 2.2(froyo).So please any one can tell me how to do the same?

Thanks in advance.

回答1:

You can use the 3.0 API's in 2.2 via Reflection. But this might cause your app to work incorrectly in certain cases, behave unpredictably for some devices etc.

If you still wanna try, see here:

How to use BluetoothHeadset class via reflection

A brief explanation:

The name reflection is used to describe code which is able to inspect other code in the same system (or itself).

For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething', and then, call it if you want to.

So, to give you a code example of this in Java (imagine the object in question is foo) :

Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);

In the example above, the author is trying to detect whether certain bluetooth classes and methods exist in order for the detection to work. If they exist, then they are used. If not, then your code must handle the situation by notifying the user or by some other appropriate mechanism suitable for your app.