Skip to content

Instantly share code, notes, and snippets.

@stremetskyi-o
Created September 4, 2015 10:39
Show Gist options
  • Save stremetskyi-o/7d1b3e271c4b3a991954 to your computer and use it in GitHub Desktop.
Save stremetskyi-o/7d1b3e271c4b3a991954 to your computer and use it in GitHub Desktop.
Helper for showing Google Play services dialog with material style on versions prior to Lollipop
package com.android.example;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import com.google.android.gms.common.GoogleApiAvailability;
import java.lang.reflect.Field;
public class GooglePlayDialogHelper {
private static Dialog getErrorDialog(Activity activity, int errorCode, int requestCode) {
Dialog defaultDialog = GoogleApiAvailability.getInstance().getErrorDialog(activity, errorCode, requestCode);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) // Remove this check if custom dialog theme is used
return defaultDialog;
try {
Field mAlert = getAccessibleField(android.app.AlertDialog.class, "mAlert");
Object alertController = mAlert.get(defaultDialog);
Class alertControllerClass = alertController.getClass();
Field mTitle = getAccessibleField(alertControllerClass, "mTitle");
Field mMessage = getAccessibleField(alertControllerClass, "mMessage");
Field mButtonPositiveText = getAccessibleField(alertControllerClass, "mButtonPositiveText");
Field mButtonPositiveMessage = getAccessibleField(alertControllerClass, "mButtonPositiveMessage");
CharSequence title = (CharSequence) mTitle.get(alertController);
CharSequence message = (CharSequence) mMessage.get(alertController);
CharSequence buttonPositiveText = (CharSequence) mButtonPositiveText.get(alertController);
DialogInterface.OnClickListener onClickListener = (DialogInterface.OnClickListener) ((Message) mButtonPositiveMessage.get(alertController)).obj;
return new AlertDialog.Builder(activity) // You can apply your own dialog theme here, or change whatever you want
.setTitle(title)
.setMessage(message)
.setPositiveButton(buttonPositiveText, onClickListener).create();
} catch (Throwable t) {
// Something happened, returning default dialog
return defaultDialog;
}
}
private static Field getAccessibleField(Class clazz, String fieldName) throws NoSuchFieldException {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment