由于Android 12对与非SDK接口的限制,导致应用程序无法直接使用MqttAndroidClient。解决方法是使用反射来调用MqttAndroidClient中的方法。
以下是示例代码:
private MqttAndroidClient createMqttAndroidClient(Context context, String serverUri, String clientId) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
MqttAndroidClient client = null;
try {
Class> clazz = Class.forName("org.eclipse.paho.android.service.MqttAndroidClient");
Constructor> constructor = clazz.getConstructor(Context.class, String.class, String.class);
client = (MqttAndroidClient) constructor.newInstance(context, serverUri, clientId);
} catch (ClassNotFoundException | InstantiationException e) {
e.printStackTrace();
}
return client;
}
这个代码段通过反射创建了一个新的MqttAndroidClient对象,避免了应用程序直接访问非SDK接口的问题。