android.content.IntentSender.SendIntentException#com.google.android.gms.common.ConnectionResult源码实例Demo

下面列出了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;
    }
}
 
源代码2 项目: android-job   文件: GcmAvailableHelper.java
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;
    }
}
 
源代码3 项目: vocefiscal-android   文件: MapsActivity.java
/**
 * 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());
}
 
源代码5 项目: FaceFilter   文件: FaceFilterActivity.java
/**
 * 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;
        }
    }
}
 
源代码6 项目: android   文件: DataCastManager.java
/**
 * 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;
}
 
源代码7 项目: gplus-haiku-client-android   文件: MainActivity.java
@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();
        }
    }
}
 
源代码8 项目: UTubeTV   文件: BaseCastManager.java
@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);
  }
}
 
源代码9 项目: android-vision   文件: BarcodeCaptureActivity.java
/**
 * 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();
        }
    });
}
 
源代码11 项目: AndroidChromium   文件: ExternalAuthUtils.java
/**
 * 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;
}
 
源代码12 项目: AndroidWearable-Samples   文件: MainActivity.java
@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();
    }
  }
}
 
源代码14 项目: openlocate-android   文件: OpenLocate.java
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;
    }
 
源代码15 项目: GeoLog   文件: BackgroundService.java
@Override
public void onConnectionFailed(ConnectionResult arg0) {
	Debug.log("ActivityRecognitionClient connection failed");

	activityConnected = false;				
	signalStop();
}
 
源代码16 项目: connectivity-samples   文件: MainActivity.java
@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();
    }
}
 
源代码17 项目: io2014-codelabs   文件: GameHelperUtils.java
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;
    }
}
 
源代码18 项目: GeoLog   文件: BackgroundService.java
@Override
public void onConnectionFailed(ConnectionResult arg0) {
	Debug.log("LocationClient connection failed");

	locationConnected = false;			
	signalStop();
}
 
源代码19 项目: mollyim-android   文件: FcmRefreshJob.java
@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."));
    }
  }
}
 
源代码20 项目: PrivacyStreams   文件: DeviceUtils.java
/**
 * 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;
}
 
源代码21 项目: AndroidChromium   文件: ExternalAuthUtils.java
/**
 * @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());
}
 
源代码24 项目: MuslimMateAndroid   文件: MosquesActivity.java
/**
 * 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;
}
 
源代码25 项目: wear-os-samples   文件: UtilityService.java
/**
 * 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();
    }
}
 
源代码26 项目: Onesearch   文件: ResultsActivity.java
@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);
}
 
源代码27 项目: CalendarQuickStart   文件: MainActivity.java
/**
 * 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;
}
 
源代码28 项目: PowerSwitch_Android   文件: DataApiHandler.java
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));
}
 
源代码30 项目: open-location-code   文件: LocationProvider.java
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;
    }
}