@Test
  @Feature({"GCore"})
  public void willUseConnectionBackgroundTest() {
    int disconnectionTimeout = 5000;
    int arbitraryNumberOfSeconds = 42;
    GoogleApiClientHelper helper = new GoogleApiClientHelper(mMockClient);
    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
    Activity mockActivity = mock(Activity.class);
    ApplicationStatus.onStateChangeForTesting(mockActivity, ActivityState.CREATED);
    helper.setDisconnectionDelay(disconnectionTimeout);

    // We have a connected client
    when(mMockClient.isConnected()).thenReturn(true);

    // We go in the background and extend the delay
    ApplicationStatus.onStateChangeForTesting(mockActivity, ActivityState.STOPPED);
    ShadowLooper.idleMainLooper(disconnectionTimeout - arbitraryNumberOfSeconds);
    helper.willUseConnection();

    // The client should not have been disconnected.
    ShadowLooper.idleMainLooper(disconnectionTimeout - arbitraryNumberOfSeconds);
    verify(mMockClient, never()).disconnect();

    // After the full timeout it should still disconnect though
    ShadowLooper.idleMainLooper(arbitraryNumberOfSeconds);
    verify(mMockClient).disconnect();

    // The client is now disconnected then
    when(mMockClient.isConnected()).thenReturn(false);

    // The call should reconnect a disconnected client
    helper.willUseConnection();
    verify(mMockClient).connect();
  }
예제 #2
0
 private void syncWalkState() {
   if (!mStarted && mMockWalk != null) {
     mMockWalk.quit();
     mMockWalk = null;
   } else if (!mStarted && mMockWalk == null) {
     // all good
   } else if (mStarted && mMockWalk == null && !mClient.isConnected()) {
     // all good
   } else if (mStarted && mMockWalk == null && mClient.isConnected()) {
     mMockWalk = new MockWalk(mClient);
     mMockWalk.start();
   }
 }
예제 #3
0
 public void desconectar() {
   if (mGoogleApiClient.isConnected()) {
     enviarMensagemSair();
     apagarDados();
     mGoogleApiClient.disconnect();
   }
 }
예제 #4
0
 @Override
 protected void onStop() {
   super.onStop();
   if (mGoogleApiClient.isConnected()) {
     mGoogleApiClient.disconnect();
   }
 }
    @Override
    public void onVisibilityChanged(boolean visible) {
      Log.d(TAG, "onVisibilityChanged: " + visible);

      super.onVisibilityChanged(visible);

      if (visible) {
        mGoogleApiClient.connect();

        registerReceiver();

        // Update time zone and date formats, in case they changed while we weren't visible.
        mCalendar.setTimeZone(TimeZone.getDefault());
      } else {
        unregisterReceiver();

        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
          mGoogleApiClient.disconnect();
        }
      }

      // Whether the timer should be running depends on whether we're visible (as well as
      // whether we're in ambient mode), so we may need to start or stop the timer.
      updateTimer();
    }
예제 #6
0
 @Override
 protected void onResume() {
   super.onResume();
   if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
     TestManager.getInstance().startLocationUpdates();
   }
 }
예제 #7
0
 public void showAchievements() {
   if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
     startActivityForResult(Games.Achievements.getAchievementsIntent(mGoogleApiClient), 2);
   } else if (mGoogleApiClient != null) {
     mGoogleApiClient.connect();
   }
 }
 public boolean isConnected() {
   if (apiClient == null || !apiClient.isConnected()) {
     return false;
   } else {
     return true;
   }
 }
예제 #9
0
 @Override
 protected void onPause() {
   super.onPause();
   if (mGoogleApiClient.isConnected()) {
     stopLocationUpdates();
   }
 }
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    if (!mIsRunning) {
      final Context context = getApplicationContext();
      mIsRunning = true;
      final ContentResolver contentResolver = getContentResolver();
      try {
        mCurrentLocationmode =
            Settings.Secure.getInt(contentResolver, Settings.Secure.LOCATION_MODE);
        if (mCurrentLocationmode != Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) {
          Settings.Secure.putInt(
              contentResolver,
              Settings.Secure.LOCATION_MODE,
              Settings.Secure.LOCATION_MODE_HIGH_ACCURACY);
        }
      } catch (SettingNotFoundException e) {
        Log.e(TAG, "Unable find location settings.", e);
      }
      int state = intent.getIntExtra(SERVICE_PARAM, Config.ANTITHEFT_STATE.NORMAL.getState());
      if (state == Config.ANTITHEFT_STATE.THEFT.getState()) {
        mConstantReporting = true;
      }

      buildGoogleApiClient();
    }

    if (mGoogleApiClient.isConnected()) {
      restartLocationUpdates();
    }

    return START_REDELIVER_INTENT;
  }
예제 #11
0
 protected void onStop() {
   super.onStop();
   if (mGoogleApiClient.isConnected()) {
     Log.i(TAG, "disconnected");
     mGoogleApiClient.disconnect();
   }
 }
예제 #12
0
 @Override
 protected void onStop() {
   if (googleApiClient != null && googleApiClient.isConnected()) {
     googleApiClient.disconnect();
   }
   super.onStop();
 }
예제 #13
0
 private void googlePlusLogout() {
   if (mGoogleApiClient.isConnected()) {
     Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
     mGoogleApiClient.disconnect();
     mGoogleApiClient.connect();
   }
 }
예제 #14
0
  /**
   * Submits an autocomplete query to the Places Geo Data Autocomplete API. Results are returned as
   * frozen AutocompletePrediction objects, ready to be cached. objects to store the Place ID and
   * description that the API returns. Returns an empty list if no results were found. Returns null
   * if the API client is not available or the query did not complete successfully. This method MUST
   * be called off the main UI thread, as it will block until data is returned from the API, which
   * may include a network request.
   *
   * @param constraint Autocomplete query string
   * @return Results from the autocomplete API or null if the query was not successful.
   * @see Places#GEO_DATA_API#getAutocomplete(CharSequence)
   * @see AutocompletePrediction#freeze()
   */
  private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
    if (mGoogleApiClient.isConnected()) {
      Log.i(TAG, "Starting autocomplete query for: " + constraint);

      // Submit the query to the autocomplete API and retrieve a PendingResult that will
      // contain the results when the query completes.
      PendingResult<AutocompletePredictionBuffer> results =
          Places.GeoDataApi.getAutocompletePredictions(
              mGoogleApiClient, constraint.toString(), mBounds, mPlaceFilter);

      // This method should have been called off the main UI thread. Block and wait for at most 60s
      // for a result from the API.
      AutocompletePredictionBuffer autocompletePredictions = results.await(60, TimeUnit.SECONDS);

      // Confirm that the query completed successfully, otherwise return null
      final Status status = autocompletePredictions.getStatus();
      if (!status.isSuccess()) {
        Toast.makeText(
                getContext(), "Error contacting API: " + status.toString(), Toast.LENGTH_SHORT)
            .show();
        Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
        autocompletePredictions.release();
        return null;
      }

      Log.i(
          TAG, "Query completed. Received " + autocompletePredictions.getCount() + " predictions.");

      // Freeze the results immutable representation that can be stored safely.
      return DataBufferUtils.freezeAndClose(autocompletePredictions);
    }
    Log.e(TAG, "Google API client is not connected for autocomplete query.");
    return null;
  }
예제 #15
0
  public void atualizarDados(final int position) {
    if (mTask != null) {
      mTask.cancel(true);
    }
    if (!mGoogleApiClient.isConnected()) return; // Se não estiver conectado, saia...
    mTask =
        new AsyncTask<Void, Void, PutDataMapRequest>() {
          @Override
          protected PutDataMapRequest doInBackground(Void... voids) {
            PutDataMapRequest putDataMapRequest =
                PutDataMapRequest.create(Constantes.CAMINHO_DADOS);
            mUriDados = putDataMapRequest.getUri();
            DataMap map = putDataMapRequest.getDataMap();
            map.putInt(Constantes.EXTRA_POSICAO_ATUAL, position);
            map.putInt(Constantes.EXTRA_TOTAL_IMAGENS, Constantes.TOTAL_IMAGENS);
            Bitmap miniatura =
                ImagemUtil.imagem(mContext, "foto" + (position + 1) + ".jpg", 160, 160);
            if (miniatura != null) {
              final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
              miniatura.compress(Bitmap.CompressFormat.JPEG, 80, byteStream);
              Asset asset = Asset.createFromBytes(byteStream.toByteArray());
              map.putAsset(Constantes.EXTRA_IMAGEM, asset);
            }
            return putDataMapRequest;
          }

          @Override
          protected void onPostExecute(PutDataMapRequest dataMapRequest) {
            super.onPostExecute(dataMapRequest);
            Wearable.DataApi.putDataItem(mGoogleApiClient, dataMapRequest.asPutDataRequest());
          }
        }.execute();
  }
 @Override
 public void onDestroy() {
   super.onDestroy();
   if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
     mGoogleApiClient.disconnect();
   }
 }
 @Override
 protected void onStart() {
   super.onStart();
   if (mGoogleApiClient != null && !mGoogleApiClient.isConnected()) {
     mGoogleApiClient.connect();
   }
 }
 private void attachRecorder() {
   if (locationClientAPI == null) {
     connectToPlayAPI();
   } else if (locationClientAPI.isConnected()) {
     Integer priority = translateDesiredAccuracy(config.getDesiredAccuracy());
     LocationRequest locationRequest =
         LocationRequest.create()
             .setPriority(priority) // this.accuracy
             .setFastestInterval(config.getFastestInterval())
             .setInterval(config.getInterval());
     // .setSmallestDisplacement(config.getStationaryRadius());
     LocationServices.FusedLocationApi.requestLocationUpdates(
         locationClientAPI, locationRequest, this);
     Log.d(
         TAG,
         "- locationUpdateReceiver NOW RECORDING!!!!!!!!!! with priority: "
             + priority
             + ", fastestInterval: "
             + config.getFastestInterval()
             + ", interval: "
             + config.getInterval()
             + ", smallestDisplacement: "
             + config.getStationaryRadius());
   } else {
     locationClientAPI.connect();
   }
 }
예제 #19
0
 @Override
 public void onResume() {
   super.onResume();
   if (mGoogleApiClient.isConnected() && !mRequestingLocationUpdates) {
     startLocationUpdates();
   }
 }
  /** Call this method from your Activity's onStart(). */
  public void onStart(Activity act) {
    mActivity = act;
    mAppContext = act.getApplicationContext();

    debugLog("onStart");
    assertConfigured("onStart");

    if (mConnectOnStart) {
      if (mGoogleApiClient.isConnected()) {
        Log.w(TAG, "GameHelper: client was already connected on onStart()");
      } else {
        debugLog("Connecting client.");
        mConnecting = true;
        mGoogleApiClient.connect();
      }
    } else {
      debugLog("Not attempting to connect becase mConnectOnStart=false");
      debugLog("Instead, reporting a sign-in failure.");
      mHandler.postDelayed(
          new Runnable() {
            @Override
            public void run() {
              notifyListener(false);
            }
          },
          1000);
    }
  }
예제 #21
0
 private void sendMessageToWearable(String message, String type) {
   // Log.d(TAG, "sendMessageToWearable: " + type + ": " + message);
   if (mGoogleApiClient.isConnected()) {
     PutDataMapRequest putDataMapRequest =
         PutDataMapRequest.create(Constants.MESSAGE_MOBILE_TO_WEARABLE_PATH);
     putDataMapRequest.getDataMap().putString(Constants.KEY_TEXT_FROM_SERVER, message);
     putDataMapRequest.getDataMap().putLong(Constants.KEY_TIMESTAMP, new Date().getTime());
     putDataMapRequest.getDataMap().putString(Constants.KEY_MESSAGE_TYPE, type);
     PutDataRequest request = putDataMapRequest.asPutDataRequest();
     Wearable.DataApi.putDataItem(mGoogleApiClient, request)
         .setResultCallback(
             new ResultCallback<DataApi.DataItemResult>() {
               @Override
               public void onResult(DataApi.DataItemResult dataItemResult) {
                 if (!dataItemResult.getStatus().isSuccess()) {
                   Log.e(
                       TAG,
                       "buildWatchOnlyNotification(): Failed to set the data, "
                           + "status: "
                           + dataItemResult.getStatus().getStatusCode());
                 } else {
                   // Log.d(TAG, "message sent successfully!");
                 }
               }
             });
   } else {
     Log.e(TAG, "sendMessageToWearable(): no Google API Client connection");
   }
 }
  /** Sign out and disconnect from the APIs. */
  public void signOut() {
    if (!mGoogleApiClient.isConnected()) {
      // nothing to do
      debugLog("signOut: was already disconnected, ignoring.");
      return;
    }

    // for Plus, "signing out" means clearing the default account and
    // then disconnecting
    if (0 != (mRequestedClients & CLIENT_PLUS)) {
      debugLog("Clearing default account on PlusClient.");
      Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
    }

    // For the games client, signing out means calling signOut and
    // disconnecting
    if (0 != (mRequestedClients & CLIENT_GAMES)) {
      debugLog("Signing out from the Google API Client.");
      Games.signOut(mGoogleApiClient);
    }

    // Ready to disconnect
    debugLog("Disconnecting client.");
    mConnectOnStart = false;
    mConnecting = false;
    mGoogleApiClient.disconnect();
  }
예제 #23
0
 @Override
 protected void onPause() {
   super.onPause();
   if (mGoogleApiClient.isConnected()) {
     TestManager.getInstance().stopLocationUpdates();
   }
 }
예제 #24
0
  @Test
  @Feature({"GCore"})
  public void lifecycleManagementDelayTest() {
    GoogleApiClientHelper helper = new GoogleApiClientHelper(mMockClient);
    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
    Activity mockActivity = mock(Activity.class);
    ApplicationStatus.onStateChangeForTesting(mockActivity, ActivityState.CREATED);
    helper.setDisconnectionDelay(5000);

    // We have a connected client
    when(mMockClient.isConnected()).thenReturn(true);

    // Should not be disconnected when we go in the background
    ApplicationStatus.onStateChangeForTesting(mockActivity, ActivityState.STOPPED);
    ShadowLooper.runUiThreadTasks();
    verify(mMockClient, times(0)).disconnect();

    // Should be disconnected when we wait.
    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
    verify(mMockClient, times(1)).disconnect();

    // Should be reconnected when we come in the foreground
    ApplicationStatus.onStateChangeForTesting(mockActivity, ActivityState.STARTED);
    verify(mMockClient).connect();

    // Should not disconnect when we became visible during the delay
    ApplicationStatus.onStateChangeForTesting(mockActivity, ActivityState.STOPPED);
    ShadowLooper.runUiThreadTasks();
    verify(mMockClient, times(1)).disconnect();
    ApplicationStatus.onStateChangeForTesting(mockActivity, ActivityState.STARTED);
    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
    verify(mMockClient, times(1)).disconnect();
  }
  @Override
  public void onResume() {
    super.onResume();

    if (getActivity() instanceof BraintreeListener) {
      addListener((BraintreeListener) getActivity());
    }

    flushCallbacks();

    if (mGoogleApiClient != null
        && !mGoogleApiClient.isConnected()
        && !mGoogleApiClient.isConnecting()) {
      mGoogleApiClient.connect();
    }

    if (mIsBrowserSwitching) {
      onActivityResult(
          PayPal.PAYPAL_REQUEST_CODE,
          Activity.RESULT_FIRST_USER,
          BraintreeBrowserSwitchActivity.sLastBrowserSwitchResponse);

      BraintreeBrowserSwitchActivity.sLastBrowserSwitchResponse = null;
      mIsBrowserSwitching = false;
    }
  }
 @Override
 public void onPause() {
   super.onPause();
   if (mGoogleApiClient.isConnected()) {
     mGoogleApiClient.disconnect();
   }
 }
예제 #27
0
 @Override
 public void onStop() {
   super.onStop();
   Log.d("TAG", "onStop LocationActivity");
   mGoogleApiClient.disconnect();
   Log.d("TAG", "isConnected ...............: " + mGoogleApiClient.isConnected());
 }
 @Override
 protected void onDestroy() {
   if (client.isConnected()) {
     client.disconnect();
   }
   super.onDestroy();
 }
예제 #29
0
    @Override
    public void run() {
      // check for STORAGE permission
      if (!canWriteToStorage()) return;

      SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(mActivity);
      String driveAccount =
          SP.getString(
              mActivity.getResources().getString(R.string.PROPERTY_googledrive_account),
              "<Not Set>");

      if (driveAccount.equals("<Not Set>")) return;
      GoogleApiClient googleApiClient =
          new GoogleApiClient.Builder(mActivity)
              .addApi(Drive.API)
              .addScope(Drive.SCOPE_FILE)
              .setAccountName(driveAccount)
              .addConnectionCallbacks(m_me)
              .addOnConnectionFailedListener(m_me)
              .build();

      googleApiClient.blockingConnect();
      if (!googleApiClient.isConnected()) return;

      if (mTeamNumber >= 0) {
        syncPhotosForTeam(googleApiClient, mTeamNumber);
      } else {
        mRequester = null;

        // TODO: loop over all folders in the photos dir
      }
    }
예제 #30
0
 private void enviarMensagemSair() {
   if (mNodes != null && mGoogleApiClient.isConnected()) {
     for (Node node : mNodes) {
       Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), Constantes.MSG_SAIR, null);
     }
   }
 }