- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开发一个 Android 库,我需要删除由使用我的库的开发人员添加的播放服务依赖项。我需要用户位置最后一个位置,所以我需要使用反射,因为位置库不会直接包含在我的库中。
但是如何通过反射从构建器创建 googleApiClient 呢?
最佳答案
深入研究反射和 Play 服务会生成以下脚本。它包含用于获取 AdvertisingId 和位置的代码。
private void getLocation(Context context) {
Log.d(LOG_TAG, "getLocation");
if (context.getPackageManager().checkPermission(
Manifest.permission.ACCESS_FINE_LOCATION, context.getPackageName()) == PackageManager.PERMISSION_GRANTED ||
context.getPackageManager().checkPermission(
Manifest.permission.ACCESS_COARSE_LOCATION, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
try {
Class<?> apiClientBuilderClass = Class.forName("com.google.android.gms.common.api.GoogleApiClient$Builder");
Class<?> connectionCallbackClass = Class.forName("com.google.android.gms.common.api.GoogleApiClient$ConnectionCallbacks");
Class<?> connectionFailedCallbackClass = Class.forName("com.google.android.gms.common.api.GoogleApiClient$OnConnectionFailedListener");
Class<?> locationServicesClass = Class.forName("com.google.android.gms.location.LocationServices");
Constructor<?> constructorApiBuilder = apiClientBuilderClass.getConstructor(Context.class);
Object objectApiBuilder = constructorApiBuilder.newInstance(mContext);
// Create intance of listener ConnectionCallbacks
Class<?>[] connectionClassArray = new Class<?>[1];
connectionClassArray[0] = connectionCallbackClass;
sGoogleApiClientListener = Proxy.newProxyInstance(
connectionCallbackClass.getClassLoader(), connectionClassArray, new GoogleApiClientListener());
Method connectionMethodObject = apiClientBuilderClass.getMethod("addConnectionCallbacks", connectionCallbackClass);
connectionMethodObject.invoke(objectApiBuilder, sGoogleApiClientListener);
// Create instance of OnConnectionFailedListener listener
Class<?>[] connectionFailedClassArray = new Class<?>[1];
connectionFailedClassArray[0] = connectionFailedCallbackClass;
sGoogleApiClientFailedListener = Proxy.newProxyInstance(
connectionFailedCallbackClass.getClassLoader(), connectionFailedClassArray, new GoogleApiClientFailedListener());
Method connectionFailedMethodObject = apiClientBuilderClass.getMethod("addOnConnectionFailedListener", connectionFailedCallbackClass);
connectionFailedMethodObject.invoke(objectApiBuilder, sGoogleApiClientFailedListener);
// Add Api
Method addApiMethod = apiClientBuilderClass.getMethod("addApi", Class.forName("com.google.android.gms.common.api.Api"));
addApiMethod.invoke(objectApiBuilder, locationServicesClass.getField("API").get(null));
// Build
Method buildMethod = apiClientBuilderClass.getMethod("build");
sGoogleApiClient = buildMethod.invoke(objectApiBuilder);
// Connect
for (Method method : sGoogleApiClient.getClass().getMethods()) {
if (!"connect".equals(method.getName())) {
continue;
}
method.invoke(sGoogleApiClient);
break;
}
} catch (Exception e) {
// Location is not essential, so it's not an error
Log.v(LOG_TAG, "Exception on getLocation " + Log.getStackTraceString(e));
}
} else {
sLocation = "";
}
}
// GoogleApiClient for Locationsucceded
public void onConnected() {
Location lastLocation = null;
try {
// FusedLocationApi is a field of LocationServices, getting it.
Class<?> locationServicesClass = Class.forName("com.google.android.gms.location.LocationServices");
Class<?> locationProviderClass = Class.forName("com.google.android.gms.location.FusedLocationProviderApi");
for (Method method : locationProviderClass.getMethods()) {
if (!"getLastLocation".equals(method.getName())) {
continue;
}
Object object = locationServicesClass.getField("FusedLocationApi").get(null);
lastLocation = (Location) method.invoke(object, sGoogleApiClient);
break;
}
} catch (Exception e) {
// Location is not essential, so it's not an error
Log.v(LOG_TAG, "Exception on invoke onConnected for getLastLocation" + Log.getStackTraceString(e));
}
// Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(sGoogleApiClient);
if (lastLocation != null) {
sLocation = lastLocation.getLatitude() + "," + lastLocation.getLongitude();
Log.d(LOG_TAG, "Location received : " + sLocation);
} else {
sLocation = "";
}
newResourcesAvailable();
unregisterConnectionCallbacks();
}
// GoogleApiClient for Location failed somewhere
public void onConnectionSuspended() {
sLocation = "";
newResourcesAvailable();
unregisterConnectionCallbacks();
}
// GoogleApiClient for Location failed somewhere
public void onConnectionFailed() {
sLocation = "";
newResourcesAvailable();
unregisterConnectionCallbacks();
}
private void unregisterConnectionCallbacks(){
for (Method method : sGoogleApiClient.getClass().getMethods()) {
if (!"unregisterConnectionCallbacks".equals(method.getName())) {
continue;
}
try {
method.invoke(sGoogleApiClient, sGoogleApiClientListener);
} catch (Exception ignored) {
// Exception always occur here but cannot make it work
}
break;
}
for (Method method : sGoogleApiClient.getClass().getMethods()) {
if (!"unregisterConnectionFailedListener".equals(method.getName())) {
continue;
}
try {
method.invoke(sGoogleApiClient, sGoogleApiClientFailedListener);
} catch (Exception ignored) {
// Exception always occur here but cannot make it work
}
break;
}
}
protected class RetrieveAdvertisingId extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String id = "";
try {
Object AdvertisingInfoObject = getAdvertisingInfoObject(mContext);
id = (String) invokeInstanceMethod(AdvertisingInfoObject, "getId", null);
} catch (Exception e) {
// Catch reflection exception and GooglePlayServicesNotAvailableException |
// GooglePlayServicesRepairableException
Log.e(LOG_TAG, "Exception while getting AdvertisingId", e);
}
return id;
}
@Override
protected void onPostExecute(String advertisingId) {
super.onPostExecute(advertisingId);
if (advertisingId != null && !advertisingId.isEmpty()) {
Log.i(LOG_TAG, "Advertising ID retrieved: " + advertisingId);
sAdvertisingId = advertisingId;
} else {
Log.e(LOG_TAG, "AdversitingId is not available");
sAdvertisingId = "";
}
AsynchronousParameterManager.this.newResourcesAvailable();
}
}
/**
* Returns the AdvertisingIdInfo object
*
* @param context the android context
* @return the advertising id information object
* @throws Exception
*/
private Object getAdvertisingInfoObject(Context context) throws Exception {
return invokeStaticMethod(
"com.google.android.gms.ads.identifier.AdvertisingIdClient",
"getAdvertisingIdInfo",
new Class[]{Context.class},
context
);
}
/**
* Invokes a static method within a class
* if it can be found on the classpath.
*
* @param className The full defined classname
* @param methodName The name of the method to invoke
* @param cArgs The args that the method can take
* @param args The args to pass to the method on invocation
* @return the result of the method invoke
* @throws Exception
*/
private Object invokeStaticMethod(String className, String methodName,
Class[] cArgs, Object... args) throws Exception {
Class classObject = Class.forName(className);
return invokeMethod(classObject, methodName, null, cArgs, args);
}
/**
* Invokes a method on a static instance
* within a class by reflection.
*
* @param instance The instance to invoke a method on
* @param methodName The name of the method to invoke
* @param cArgs The args that the method can take
* @param args The args to pass to the method on invocation
* @return the result of the method invoke
* @throws Exception
*/
private Object invokeInstanceMethod(Object instance, String methodName,
Class[] cArgs, Object... args) throws Exception {
Class classObject = instance.getClass();
return invokeMethod(classObject, methodName, instance, cArgs, args);
}
/**
* Invokes methods of a class via reflection
*
* @param classObject The class to attempt invocation on
* @param methodName The name of the method to invoke
* @param instance The object instance to invoke on
* @param cArgs The args that the method can take
* @param args The args to pass to the method on invocation
* @return the result of the method invoke
* @throws Exception
*/
private Object invokeMethod(Class classObject, String methodName, Object instance,
Class[] cArgs, Object... args) throws Exception {
Method methodObject = classObject.getMethod(methodName, cArgs);
return methodObject.invoke(instance, args);
}
private class GoogleApiClientListener implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (args != null) {
if (method.getName().equals("onConnected")) {
AsynchronousParameterManager.this.onConnected();
} else if (method.getName().equals("onConnectionSuspended") ) {
AsynchronousParameterManager.this.onConnectionSuspended();
}
} else {
return 0;
}
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
}
return null;
}
}
private class GoogleApiClientFailedListener implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
if (method.getName().equals("onConnectionFailed")) {
AsynchronousParameterManager.this.onConnectionFailed();
}
return 0;
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
}
}
}
关于java - getLastLocation 使用反射与 GoogleApiClient 和 LocationServices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31471143/
当我尝试从 GoogleApiClient 注销时,收到以下错误消息 GoogleApiClient.isConnected() on a null object reference 这是我的代码:
所以我发现了一些关于 GoogleApiClient 对我来说不是很清楚的东西。GoogleApiClient 有一个名为 onConnected 的函数,该函数在客户端已连接(肯定)时运行。 我得到
我在这里查看了这个问答:GoogleApiClient is throwing "GoogleApiClient is not connected yet" AFTER onConnected fun
我正在尝试在服务中实现 Fused Location API。我已经完成了以下编码,但出现如下错误: java.lang.RuntimeException: Unable to instantia
我想在android中实现自动完成位置google API。为此,我需要创建一个 GoogleApiClient 对象。我为此使用了以下代码... private GoogleApiClient mG
我创建了一个名为 SendToWear 的类,其中包含一个名为 sendMessage(Context context, String path, @Nullable String data) 的静态
我想获取设备的当前位置,这是我的一段代码 private void displayLocation() { mLastLocation = LocationServices.FusedLoca
我的场景是我希望有一个服务定期获取一些信息(例如用户的位置),将其报告到我的服务器并在该位置与某个 X 位置匹配时接收推送通知。 无论应用程序是否正在运行,我都希望得到一些关于定期检索位置信息的最佳机
我正在将 Google Smart Lock 实现到一个应用程序中,之前我在构建 Api 客户端时没有遇到任何问题。事实上,我正在完成一些语法更改并清理代码(甚至没有触及初始化 Api 客户端的代码)
这是我尝试实例化它的代码: gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
我在我的应用程序上使用 Google+ 登录,并遵循了诸如 Getting Started 之类的引用和 Google+ Sign-in for Android . 所以情况是这样的: 我有一个 Lo
我正在编写一个 Android Wear 应用,我想让可穿戴设备在点击按钮时在手机上启动一个 Intent。 为此,我首先像这样设置与 GoogleApiClient 的连接 googleApiCl
我想使用 FusedLocationProviderApi 获取最后的已知位置。我按照谷歌教程所说的那样做了,但似乎 GoogleApiClient 没有连接,至少它没有触发 onConnected
我正在处理的应用程序有时可以正常工作,但有时会出现此错误 FATAL EXCEPTION: java.lang.RuntimeException: Unable to pause activity {
我正在为我的项目使用 Google App Indexing。 此功能的新手。我只是遵循谷歌指南。 Notify the google using API 在此页面中,要求创建一个 GoogleApi
我通过 GoogleApiClient 为应用设置了 google plus 登录。 每当应用程序首次安装并尝试通过 GoogleApiClient 建立连接时,它永远不会成功,并且总是以 onCon
我正在尝试获取服务中的位置更新信息。为此,我创建了一个服务,并在服务类的 onStartCommand 中创建了 GoogleApiClient,但我没有在服务中收到连接回调。请帮助解决这个问题。 下
更新用户的当前位置我在我的项目中实现了以下方法: GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedList
我正在尝试为我的 Android 游戏使用 Google Games 回合制 Api。我用来连接 GoogleApiClient 的代码来自 Google 的 Api 示例或文档。 在我的 onCon
我尝试学习 android 开发,现在我正在开发一个具有融合位置服务的应用程序。 当我想放置 GoogleMap fragment 、带有经纬度的 Textviews 和其他一些小部件时,我得到了一个
我是一名优秀的程序员,十分优秀!