下面列出了android.content.IntentSender.SendIntentException#com.google.android.gms.common.ConnectionResult 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_open: {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if(status != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(status, this, status);
showToast("Cannot run without Google Play, please check!");
} else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
break;
}
default:
break;
}
}
public static boolean isGcmApiSupported(Context context) {
try {
if (!checkedServiceEnabled) {
checkedServiceEnabled = true;
setServiceEnabled(context, GCM_IN_CLASSPATH);
}
return GCM_IN_CLASSPATH
&& GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS
&& isGcmServiceRegistered(context) == ConnectionResult.SUCCESS;
} catch (Throwable t) {
// seeing sometimes a DeadObjectException, return false, we can't do anything in this case
// still sometimes seeing a NoClassDefFoundError here
if (BuildConfig.DEBUG) {
CAT.w(t.getMessage());
}
return false;
}
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices()
{
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS)
{
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else
{
finish();
}
return false;
}
return true;
}
@SmallTest
public void testOnConnectionFailedPostsEvent() throws Exception {
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(),1, new Intent("MOCK"),0);
ConnectionResult result = new ConnectionResult(0,pendingIntent);
_command.execute(_app);
_bus.post(new GoogleFitChangeState(BaseChangeState.State.START));
_stateLatch.await(1000, TimeUnit.MILLISECONDS);
_stateLatch = new CountDownLatch(1);
_command.onConnectionFailed(result);
_stateLatch.await(2000,TimeUnit.MILLISECONDS);
assertEquals(BaseStatus.Status.UNABLE_TO_START, _state.getStatus());
}
/**
* Starts or restarts the camera source, if it exists. If the camera source doesn't exist yet
* (e.g., because onResume was called before the camera source was created), this will be called
* again when the camera source is created.
*/
private void startCameraSource() {
// check that the device has play services available.
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
Dialog dlg =
GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
dlg.show();
}
if (mCameraSource != null) {
try {
mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source.", e);
mCameraSource.release();
mCameraSource = null;
}
}
}
/**
* Initializes the DataCastManager for clients. Before clients can use DataCastManager, they
* need to initialize it by calling this static method. Then clients can obtain an instance of
* this singleton class by calling {@link DataCastManager#getInstance()}. Failing to initialize
* this class before requesting an instance will result in a {@link CastException} exception.
*
* @param context
* @param applicationId the unique ID for your application
* @param namespaces to be set up for this class.
* @return
*/
public static DataCastManager initialize(Context context,
String applicationId, String... namespaces) {
if (null == sInstance) {
LOGD(TAG, "New instance of DataCastManager is created");
if (ConnectionResult.SUCCESS != GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context)) {
String msg = "Couldn't find the appropriate version of Google Play Services";
LOGE(TAG, msg);
throw new RuntimeException(msg);
}
sInstance = new DataCastManager(context, applicationId, namespaces);
mCastManager = sInstance;
}
return sInstance;
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed");
if (mIsResolving) {
Log.d(TAG, "Already resolving.");
return;
}
// Attempt to resolve the ConnectionResult
if (connectionResult.hasResolution() && mSignInClicked) {
mIsResolving = true;
mSignInClicked = false;
try {
connectionResult.startResolutionForResult(this, REQ_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Could not resolve.", e);
mIsResolving = false;
mGoogleApiClient.connect();
}
}
}
@Override
public void onConnectionFailed(ConnectionResult result) {
CastUtils.LOGD(TAG, "onConnectionFailed() reached, error code: " + result.getErrorCode() + ", reason: " + result
.toString());
mSelectedCastDevice = null;
if (null != mMediaRouter) {
mMediaRouter.selectRoute(mMediaRouter.getDefaultRoute());
}
boolean showError = false;
if (null != mBaseCastConsumers) {
for (IBaseCastConsumer consumer : mBaseCastConsumers) {
try {
consumer.onConnectionFailed(result);
} catch (Exception e) {
CastUtils.LOGE(TAG, "onConnectionFailed(): Failed to inform " + consumer, e);
}
}
}
if (showError) {
CastUtils.showErrorDialog(mContext, R.string.failed_to_connect);
}
}
/**
* Starts or restarts the camera source, if it exists. If the camera source doesn't exist yet
* (e.g., because onResume was called before the camera source was created), this will be called
* again when the camera source is created.
*/
private void startCameraSource() throws SecurityException {
// check that the device has play services available.
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
Dialog dlg =
GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
dlg.show();
}
if (mCameraSource != null) {
try {
mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source.", e);
mCameraSource.release();
mCameraSource = null;
}
}
}
public void check() {
final GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
final int result = googleApiAvailability.isGooglePlayServicesAvailable(getActivity());
if (result == ConnectionResult.SUCCESS) {
done();
return;
}
// IMPORTANT: We can't be sure that this code is
// running on main-ui-thread, it depends where the
// method was called from. For example React Native
// responds to native bridge methods off main-ui-thread.
// If a dialog is dispatched from a non-ui-thread thread,
// when it is dismissed on main-ui-thread the app will crash.
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
googleApiAvailability.showErrorDialogFragment(getActivity(), result, ID);
done();
}
});
}
/**
* Same as {@link #canUseGooglePlayServices(Context, UserRecoverableErrorHandler)}.
* @param context The current context.
* @param errorHandler How to handle user-recoverable errors; must be non-null.
* @return the result code specifying Google Play Services availability.
*/
public int canUseGooglePlayServicesResultCode(
final Context context, final UserRecoverableErrorHandler errorHandler) {
final int resultCode = checkGooglePlayServicesAvailable(context);
recordConnectionResult(resultCode);
if (resultCode != ConnectionResult.SUCCESS) {
// resultCode is some kind of error.
Log.v(TAG, "Unable to use Google Play Services: %s", describeError(resultCode));
if (isUserRecoverableError(resultCode)) {
Runnable errorHandlerTask = new Runnable() {
@Override
public void run() {
errorHandler.handleError(context, resultCode);
}
};
ThreadUtils.runOnUiThread(errorHandlerTask);
}
}
return resultCode;
}
@Override
public void onConnectionFailed(ConnectionResult result) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Disconnected from Google Api Service");
}
if (null != Wearable.NodeApi) {
Wearable.NodeApi.removeListener(mGoogleApiClient, this);
}
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
mResolvingError = false;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_where_am_i);
mTextView = findViewById(R.id.myLocationText);
GoogleApiAvailability availability = GoogleApiAvailability.getInstance();
int result = availability.isGooglePlayServicesAvailable(this);
if (result != ConnectionResult.SUCCESS) {
if (!availability.isUserResolvableError(result)) {
Toast.makeText(this, ERROR_MSG, Toast.LENGTH_LONG).show();
}
}
}
public static OpenLocate initialize(Configuration configuration) {
saveConfiguration(configuration);
if (sharedInstance == null) {
sharedInstance = new OpenLocate(configuration);
}
boolean trackingEnabled = SharedPreferenceUtils.getInstance(configuration.context).getBoolanValue(Constants.TRACKING_STATUS, false);
if (trackingEnabled && hasLocationPermission(configuration.context) &&
sharedInstance.isGooglePlayServicesAvailable() == ConnectionResult.SUCCESS) {
sharedInstance.onPermissionsGranted();
}
return sharedInstance;
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
Debug.log("ActivityRecognitionClient connection failed");
activityConnected = false;
signalStop();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
if (mContainer != null) {
Snackbar.make(mContainer, "Exception while connecting to Google Play services: " +
connectionResult.getErrorMessage(),
Snackbar.LENGTH_INDEFINITE).show();
}
}
static String errorCodeToString(int errorCode) {
switch (errorCode) {
case ConnectionResult.DEVELOPER_ERROR:
return "DEVELOPER_ERROR(" + errorCode + ")";
case ConnectionResult.INTERNAL_ERROR:
return "INTERNAL_ERROR(" + errorCode + ")";
case ConnectionResult.INVALID_ACCOUNT:
return "INVALID_ACCOUNT(" + errorCode + ")";
case ConnectionResult.LICENSE_CHECK_FAILED:
return "LICENSE_CHECK_FAILED(" + errorCode + ")";
case ConnectionResult.NETWORK_ERROR:
return "NETWORK_ERROR(" + errorCode + ")";
case ConnectionResult.RESOLUTION_REQUIRED:
return "RESOLUTION_REQUIRED(" + errorCode + ")";
case ConnectionResult.SERVICE_DISABLED:
return "SERVICE_DISABLED(" + errorCode + ")";
case ConnectionResult.SERVICE_INVALID:
return "SERVICE_INVALID(" + errorCode + ")";
case ConnectionResult.SERVICE_MISSING:
return "SERVICE_MISSING(" + errorCode + ")";
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
return "SERVICE_VERSION_UPDATE_REQUIRED(" + errorCode + ")";
case ConnectionResult.SIGN_IN_REQUIRED:
return "SIGN_IN_REQUIRED(" + errorCode + ")";
case ConnectionResult.SUCCESS:
return "SUCCESS(" + errorCode + ")";
default:
return "Unknown error code " + errorCode;
}
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
Debug.log("LocationClient connection failed");
locationConnected = false;
signalStop();
}
@Override
public void onRun() throws Exception {
if (TextSecurePreferences.isFcmDisabled(context)) return;
Log.i(TAG, "Reregistering FCM...");
int result = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
if (result != ConnectionResult.SUCCESS) {
notifyFcmFailure();
} else {
Optional<String> token = FcmUtil.getToken();
if (token.isPresent()) {
String oldToken = TextSecurePreferences.getFcmToken(context);
if (!token.get().equals(oldToken)) {
int oldLength = oldToken != null ? oldToken.length() : -1;
Log.i(TAG, "Token changed. oldLength: " + oldLength + " newLength: " + token.get().length());
} else {
Log.i(TAG, "Token didn't change.");
}
ApplicationDependencies.getSignalServiceAccountManager().setGcmId(token);
TextSecurePreferences.setFcmToken(context, token.get());
TextSecurePreferences.setFcmTokenLastSetTime(context, System.currentTimeMillis());
TextSecurePreferences.setWebsocketRegistered(context, true);
} else {
throw new RetryLaterException(new IOException("Failed to retrieve a token."));
}
}
}
/**
* Check that Google Play services APK is installed and up to date.
* @return true if Google Play Services is available and up to date on this device, false otherwise.
*/
public static boolean isGooglePlayServicesAvailable(Context context) {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(context);
return connectionStatusCode == ConnectionResult.SUCCESS;
}
/**
* @param errorCode returned by {@link #checkGooglePlayServicesAvailable(Context)}.
* @return true if the error code indicates that an invalid version of Google Play Services is
* installed.
*/
public boolean isGooglePlayServicesUpdateRequiredError(int errorCode) {
return errorCode == ConnectionResult.SERVICE_UPDATING
|| errorCode == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED
|| errorCode == ConnectionResult.SERVICE_DISABLED
|| errorCode == ConnectionResult.SERVICE_MISSING;
}
@Override public void showConnectionError(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
showResolution(connectionResult);
} else {
showConnectionErrorMessage(connectionResult.getErrorCode());
}
}
@SmallTest
public void testGooglePlayDisableMessageReceived() throws Exception {
when(_playServices.isGooglePlayServicesAvailable(any(Context.class))).thenReturn(ConnectionResult.API_UNAVAILABLE);
_command.execute(_app);
_command.onChangeState(new ActivityRecognitionChangeState(BaseChangeState.State.START));
ArgumentCaptor<ActivityRecognitionStatus> captor = ArgumentCaptor.forClass(ActivityRecognitionStatus.class);
verify(_bus,timeout(1000).times(1)).post(captor.capture());
assertEquals(BaseStatus.Status.UNABLE_TO_START, captor.getValue().getStatus());
assertFalse(captor.getValue().playServicesAvailable());
}
/**
* Function to check google play services
*
* @return Found or not
*/
private boolean checkPlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if (result != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
1).show();
}
return false;
}
return true;
}
/**
* Sends the actual message to ask other devices that are capable of showing "details" to start
* the appropriate activity
*
* @param path the path to pass to the wearable message API
* @param extraInfo extra info that varies based on the path being sent
*/
private void startDeviceActivityInternal(String path, String extraInfo) {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
ConnectionResult connectionResult = googleApiClient.blockingConnect(
Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);
if (connectionResult.isSuccess() && googleApiClient.isConnected()) {
CapabilityApi.GetCapabilityResult result = Wearable.CapabilityApi.getCapability(
googleApiClient,
getApplicationContext().getString(R.string.show_detail_capability_name),
CapabilityApi.FILTER_REACHABLE)
.await(GET_CAPABILITY_TIMEOUT_S, TimeUnit.SECONDS);
if (result.getStatus().isSuccess()) {
Set<Node> nodes = result.getCapability().getNodes();
for (Node node : nodes) {
Wearable.MessageApi.sendMessage(
googleApiClient, node.getId(), path, extraInfo.getBytes());
}
} else {
Log.e(TAG, "startDeviceActivityInternal() Failed to get capabilities, status: "
+ result.getStatus().getStatusMessage());
}
googleApiClient.disconnect();
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
super.onConnectionFailed(connectionResult);
findViewById(R.id.bResultSignIn).setVisibility(View.VISIBLE);
findViewById(R.id.bShowLeaderBoards).setVisibility(View.GONE);
findViewById(R.id.bShowAchievements).setVisibility(View.GONE);
findViewById(R.id.bResultSignIn).setOnClickListener(this);
}
/**
* Check that Google Play services APK is installed and up to date. Will
* launch an error dialog for the user to update Google Play Services if
* possible.
* @return true if Google Play Services is available and up to
* date on this device; false otherwise.
*/
private boolean isGooglePlayServicesAvailable() {
final int connectionStatusCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
return false;
} else if (connectionStatusCode != ConnectionResult.SUCCESS ) {
return false;
}
return true;
}
public boolean blockingConnect() {
ConnectionResult connectionResult = googleApiClient.blockingConnect(SettingsConstants.GOOGLE_API_CLIENT_TIMEOUT, TimeUnit
.SECONDS);
if (!connectionResult.isSuccess() || !googleApiClient.isConnected()) {
Log.e("FetchDataAsyncTask", String.format("Failed to connect to GoogleApiClient (error code = %d)",
connectionResult.getErrorCode()));
return false;
}
Log.e("FetchDataAsyncTask", "GoogleApiClient connected using blocking connect method");
return true;
}
@SmallTest
public void testRegistersActivityRecogntionConnectedEvent() throws Exception {
when(_playServices.isGooglePlayServicesAvailable(any(Context.class))).thenReturn(ConnectionResult.SUCCESS);
_command.execute(_app);
_command.onChangeState(new ActivityRecognitionChangeState(BaseChangeState.State.START));
verify(_googleApiClient,timeout(1000).times(1)).registerConnectionCallbacks(any(ActivityRecognitionServiceCommand.class));
}
private void determineIfUsingGms() {
// Possible returned status codes can be found at
// https://developers.google.com/android/reference/com/google/android/gms/common/GoogleApiAvailability
int statusCode = mGoogleApiAvailability.isGooglePlayServicesAvailable(mContext);
if (statusCode == ConnectionResult.SUCCESS
|| statusCode == ConnectionResult.SERVICE_UPDATING) {
mUsingGms = true;
}
}