@Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          /*
          Retrieve the place ID the selected item from the Adapter
          Each Place suggestion is stored as an AutocompletePrediction
          in the Adapter
           */

          final AutocompletePrediction item = mPlaceAdapter.getItem(position);
          final String placeId = item.getPlaceId();
          final CharSequence primaryText = item.getPrimaryText(null);

          Log.i(TAG, "Autocomplete item selected: " + primaryText);

          /*
          Issue a request to the Places Geo Data API to retrieve a Place object with
          additional details about the place
           */
          PendingResult<PlaceBuffer> placeResult =
              Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId);
          placeResult.setResultCallback(mUpdatePlaceDetailsCallback);

          mAutocompleteView.setText(primaryText);

          Log.i(TAG, "Called getPlaceById to get Place details for " + placeId);
        }
  // Called when the Google+ client is connected.
  @Override
  public void onConnected(Bundle bundle) {
    Activity activity = getActivity("onConnected()");
    if (activity == null) {
      return;
    }

    LOGD(TAG, "Helper connected, account " + mAccountName);

    // load user's Google+ profile, if we don't have it yet
    if (!AccountUtils.hasPlusInfo(activity, mAccountName)) {
      LOGD(TAG, "We don't have Google+ info for " + mAccountName + " yet, so loading.");
      PendingResult<People.LoadPeopleResult> result = Plus.PeopleApi.load(mGoogleApiClient, "me");
      result.setResultCallback(this);
    } else {
      LOGD(TAG, "No need for Google+ info, we already have it.");
    }

    // try to authenticate, if we don't have a token yet
    if (!AccountUtils.hasToken(activity, mAccountName)) {
      LOGD(TAG, "We don't have auth token for " + mAccountName + " yet, so getting it.");
      mTokenTask = new GetTokenTask();
      mTokenTask.execute();
    } else {
      LOGD(TAG, "No need for auth token, we already have it.");
      reportAuthSuccess(false);
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main22);
    ed = (EditText) findViewById(R.id.editText2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    googleApiClient = MainActivity.getGoogleApiClient();
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    id = DriveId.decodeFromString(getIntent().getExtras().getString("id"));
    text = "";
    final DriveFile df = id.asDriveFile();
    final Lectura llig = new Lectura();

    llig.execute(df);

    while (!isReaded) {
      if (text == "") {

      } else {
        ed.setText(text);
        isReaded = true;
      }
    }
    final Escritura escriu = new Escritura();

    fab.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Actualitzant...", Toast.LENGTH_SHORT).show();
            escriu.setText(ed.getText().toString());

            escriu.execute(df);

            Toast.makeText(getApplicationContext(), "Actualitzat!", Toast.LENGTH_SHORT).show();
            finishActivity(RESULT_OK);
          }
        });

    ResultCallback<DriveApi.DriveContentsResult> contentsOpenedCallback =
        new ResultCallback<DriveApi.DriveContentsResult>() {
          @Override
          public void onResult(DriveApi.DriveContentsResult result) {
            if (!result.getStatus().isSuccess()) {

              // display an error saying file can't be opened
              return;
            }
            // DriveContents object contains pointers
            // to the actual byte stream
            DriveContents contents = result.getDriveContents();
          }
        };

    PendingResult<DriveApi.DriveContentsResult> opened =
        df.open(googleApiClient, DriveFile.MODE_READ_WRITE, null);
    opened.setResultCallback(contentsOpenedCallback);
  }
  /**
   * Adds DataItem to the Android Wear network. The updated item is synchronized across all devices.
   *
   * @param dataPath The path to the data
   * @param data The data to send
   * @param callBack The callback to receive the response
   * @param isAsynchronous send data asynchronously
   * @param sendImmediately source :
   *     http://android-developers.blogspot.in/2015/11/whats-new-in-google-play-services-83.html
   *     With Google Play services 8.3, we’ve updated the DataApi to allow for urgency in how data
   *     items are synced. Now, a priority can be added to the data item to determine when it should
   *     be synced. For example, if you are building an app that requires immediate syncing, such as
   *     a remote control app, it can still be done immediately by calling setUrgent(), but for
   *     something such as updating your contacts, you could tolerate some delay. Non-urgent
   *     DataItems may be delayed for up to 30 minutes, but you can expect that in most cases they
   *     will be delivered within a few minutes. Low priority is now the default, so setUrgent() is
   *     needed to obtain the previous timing.
   */
  public void sendData(
      String dataPath,
      DataMap data,
      ResultCallback<DataApi.DataItemResult> callBack,
      boolean isAsynchronous,
      boolean sendImmediately) {
    if (!isConnected()) {
      if (mConnectionCallBacks != null) {
        mConnectionCallBacks.onConnectionFailed(WearConnectionCallBacks.NETWORK_ERROR);
      }
      return;
    } else if (dataPath == null) {
      if (mConnectionCallBacks != null) {
        mConnectionCallBacks.onConnectionFailed(WearConnectionCallBacks.PATH_NULL_ERROR);
      }
      return;
    } else if (data == null) {
      Log.d("Send DataMap", "Data cannot be null");
      return;
    }

    PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(dataPath);
    putDataMapRequest.getDataMap().putAll(data);

    /** Current time is also sent with data, just to make it a new data */
    putDataMapRequest
        .getDataMap()
        .putString(
            WearConnectionConstants.KEY.CURRENT_TIME, String.valueOf(System.currentTimeMillis()));

    PutDataRequest request = putDataMapRequest.asPutDataRequest();

    // update from google play service 8.3. refer comments above
    if (sendImmediately) {
      request.setUrgent();
    }

    if (isAsynchronous) {
      /** You will get callback after data is sent use the below code */
      PendingResult<DataApi.DataItemResult> dataResult =
          Wearable.DataApi.putDataItem(mGoogleApiClient, request);
      if (callBack != null) {
        dataResult.setResultCallback(callBack);
      }
    } else {
      if (isRunningOnMainThread()) {
        if (mConnectionCallBacks != null) {
          mConnectionCallBacks.onConnectionFailed(
              WearConnectionCallBacks.METHOD_CALLED_FROM_UI_THREAD);
        }
        return;
      }
      Wearable.DataApi.putDataItem(mGoogleApiClient, request).await();
    }
  }
    private void getTotalDistance() {

      Log.d(TAG, "getTotalDistance()");

      if ((mGoogleApiClient != null) && (mGoogleApiClient.isConnected()) && (!mDistanceRequested)) {

        mDistanceRequested = true;

        PendingResult<DailyTotalResult> distanceResult =
            Fitness.HistoryApi.readDailyTotal(mGoogleApiClient, DataType.TYPE_DISTANCE_DELTA);

        distanceResult.setResultCallback(this);
      }
    }
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          /*
          Retrieve the place ID of the selected item from the Adapter.
          The adapter stores each Place suggestion in a PlaceAutocomplete object from which we
          read the place ID.
          */
          final PlaceAutocompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position);
          final String placeId = String.valueOf(item.placeId);
          Log.i(TAG, "Autocomplete item selected: " + item.description);

          PendingResult<PlaceBuffer> placeResult =
              Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId);

          placeResult.setResultCallback(mPlacePickedChangeMap);
        }
  /*データの種類
  key	     type    備考        format(BluetoothSPP)
  --------------------------------------------------
  scene    string  シーン情報   "scene:ex"
  ready    boolean 準備完了状態 "ready:ex"
  vibrator integer バイブ時間   "vibrator:ex(ms)"
  */
  public void SyncData(
      String key_name, String sync_data) { // HandheldとWear間の各種データの更新をする。データの種類は上記のコメントを参照
    PutDataMapRequest dataMapRequest = PutDataMapRequest.create(globalv.DATA_PATH);
    DataMap dataMap = dataMapRequest.getDataMap();
    // Data set
    dataMap.putString(key_name, sync_data); // ("keyname",data);

    // Data Push
    PutDataRequest request = dataMapRequest.asPutDataRequest();
    PendingResult<DataApi.DataItemResult> pendingResult =
        Wearable.DataApi.putDataItem(mGoogleApiClient, request);
    pendingResult.setResultCallback(
        new ResultCallback<DataApi.DataItemResult>() {
          @Override
          public void onResult(DataApi.DataItemResult dataItemResult) {
            Log.d("TAG", "onResult:" + dataItemResult.getStatus().toString());
          }
        });
  }
Beispiel #8
0
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          /*
          Retrieve the place ID of the selected item from the Adapter.
          The adapter stores each Place suggestion in a PlaceAutocomplete object from which we
          read the place ID.
           */
          final PlaceAutocompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position);
          final String placeId = String.valueOf(item.placeId);
          Log.i("Input place", "Autocomplete item selected: " + item.description);

          /*
          Issue a request to the Places Geo Data API to retrieve a Place object with additional
           details about the place.
           */
          PendingResult<PlaceBuffer> placeResult =
              Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId);
          placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
          Log.i("Input place", "Called getPlaceById to get Place details for " + item.placeId);
        }
Beispiel #9
0
  public void getRequestedLocations(String query) {
    mQueryLocationRequested = true;
    mRequest = query;
    Log.i(LOG_TAG, "Define query places");
    final PendingResult<AutocompletePredictionBuffer> predictions =
        Places.GeoDataApi.getAutocompletePredictions(mApiClient, query, null, null);
    predictions.setResultCallback(
        new ResultCallback<AutocompletePredictionBuffer>() {
          @Override
          public void onResult(AutocompletePredictionBuffer autocompletePredictions) {
            boolean resultSuccess = autocompletePredictions.getStatus().isSuccess();
            Log.i(LOG_TAG, "Requested places result success: " + resultSuccess);
            if (resultSuccess) {
              mPlacesList.clear();

              List<String> placesIdList = new ArrayList<>();
              for (AutocompletePrediction prediction : autocompletePredictions) {
                Log.d(LOG_TAG, "Place: " + prediction.toString());
                placesIdList.add(prediction.getPlaceId());
              }
              String[] placesIdArray = new String[placesIdList.size()];
              PendingResult<PlaceBuffer> place =
                  Places.GeoDataApi.getPlaceById(mApiClient, placesIdList.toArray(placesIdArray));
              ResultCallback<PlaceBuffer> callback =
                  new ResultCallback<PlaceBuffer>() {
                    @Override
                    public void onResult(PlaceBuffer places) {
                      for (Place place : places) {
                        addPlaceData(place);
                      }
                      ((OnDataReceivedListener) getActivity()).onDataReceived(mPlacesList);
                    }
                  };
              place.setResultCallback(callback);
            }
            mQueryLocationRequested = false;
            mRequest = null;
            autocompletePredictions.release();
          }
        });
  }
 private void save(
     final FormTemplate formToSave,
     final GoogleApiClient googleClient,
     final DriveId dirDriveId,
     final String fileName) {
   PendingResult<DriveApi.DriveContentsResult> driveContentsResults =
       Drive.DriveApi.newDriveContents(googleClient);
   driveContentsResults.setResultCallback(
       new ResultCallback<DriveApi.DriveContentsResult>() {
         public void onResult(DriveApi.DriveContentsResult result) {
           DriveFolder ptFolder = Drive.DriveApi.getFolder(googleClient, dirDriveId);
           DriveContents driveContents = result.getDriveContents();
           Persister persister = new Persister();
           try {
             persister.write(formToSave, driveContents.getOutputStream());
           } catch (Exception ex) {
             Log.e(MainActivity.PT_APP_INFO, "Cannot save for to google drive because " + ex);
           }
           MetadataChangeSet.Builder builder = new MetadataChangeSet.Builder();
           builder.setTitle(fileName);
           ptFolder.createFile(googleClient, builder.build(), driveContents);
         }
       });
 }
  /**
   * Intents come in when the service is started & through the broadcast receiver. This processes
   * them just the same, setting up warning booleans and managing the countdown timer.
   *
   * @param intent The intent to process
   */
  private void processIntent(Intent intent) {
    /* If the intent is null, don't bother */
    if (intent == null) {
      return;
    }

    Bundle extras = intent.getExtras();

    /* If keys exist, process them */
    if (extras.containsKey(FamiliarConstants.KEY_FIVE_MINUTE_WARNING)) {
      mFiveMinuteWarning = extras.getBoolean(FamiliarConstants.KEY_FIVE_MINUTE_WARNING);
    }
    if (extras.containsKey(FamiliarConstants.KEY_TEN_MINUTE_WARNING)) {
      mTenMinuteWarning = extras.getBoolean(FamiliarConstants.KEY_TEN_MINUTE_WARNING);
    }
    if (extras.containsKey(FamiliarConstants.KEY_FIFTEEN_MINUTE_WARNING)) {
      mFifteenMinuteWarning = extras.getBoolean(FamiliarConstants.KEY_FIFTEEN_MINUTE_WARNING);
    }
    if (extras.containsKey(FamiliarConstants.KEY_END_TIME)) {

      /* Stop any current countdowns and remove the notification */
      if (mCountDownTimer != null) {
        mCountDownTimer.cancel();
      }
      mNotificationManager.cancel(NOTIFICATION_ID);

      long endTime = extras.getLong(FamiliarConstants.KEY_END_TIME);
      if (endTime == FamiliarConstants.CANCEL_FROM_MOBILE
          || endTime == FamiliarConstants.CANCEL_FROM_WEAR) {
        /* an end time of 0 means kill the notification */
        unregisterReceiver(mBroadcastReceiver);
        CountdownService.this.stopSelfResult(mStartId);
        /* And tell the app in case this was canceled on the app */
        if (endTime == FamiliarConstants.CANCEL_FROM_WEAR) {
          Log.v("MTG", "cancel button");
          /* This came from the cancel button, so tell the mobile */
          if (mGoogleApiClient.isConnected()) {
            PutDataMapRequest putDataMapReq = PutDataMapRequest.create(FamiliarConstants.PATH);
            putDataMapReq
                .getDataMap()
                .putLong(FamiliarConstants.KEY_END_TIME, FamiliarConstants.CANCEL_FROM_WEAR);
            PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
            PendingResult<DataApi.DataItemResult> pendingResult =
                Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
            pendingResult.setResultCallback(
                new ResultCallback<DataApi.DataItemResult>() {
                  @Override
                  public void onResult(DataApi.DataItemResult dataItemResult) {
                    Log.v("MTG", "onResult: " + dataItemResult.getStatus().getStatusMessage());
                  }
                });

            Log.v("MTG", "message sent");
          }
        }
      } else {
        /* Display the notification */
        mNotificationManager.notify(NOTIFICATION_ID, mNotificationBuilder.build());

        /* Figure out how far we are away from the end time.
         * Assume mobile and wear clocks are in sync */
        long millisInFuture = endTime - System.currentTimeMillis();
        mCountDownTimer =
            new CountDownTimer(millisInFuture, 1000) {
              /**
               * This should tick once every second. It updates the notification
               *
               * @param millisUntilFinished The time until the countdown finishes
               */
              @Override
              public void onTick(long millisUntilFinished) {

                /* Build the string */
                long secondsLeft = (millisUntilFinished / 1000) % 60;
                long minutesLeft = (millisUntilFinished / (1000 * 60)) % 60;
                long hoursLeft = (millisUntilFinished / (1000 * 60 * 60));
                String messageText =
                    String.format("%02d:%02d:%02d", hoursLeft, minutesLeft, secondsLeft);

                /* Because the ID remains unchanged,
                 * the existing notification is updated. */
                mNotificationBuilder.setContentTitle(messageText);
                mNotificationManager.notify(NOTIFICATION_ID, mNotificationBuilder.build());

                /* Vibrate a pattern if the warnings are set up */
                if (mFifteenMinuteWarning
                    && hoursLeft == 0
                    && minutesLeft == 15
                    && secondsLeft == 0) {
                  /* Buzz */
                  mVibrator.vibrate(200);
                  mFifteenMinuteWarning = false;
                } else if (mTenMinuteWarning
                    && hoursLeft == 0
                    && minutesLeft == 10
                    && secondsLeft == 0) {
                  /* Buzz Buzz */
                  mVibrator.vibrate(new long[] {0, 200, 200, 200}, -1);
                  mTenMinuteWarning = false;
                } else if (mFiveMinuteWarning
                    && hoursLeft == 0
                    && minutesLeft == 5
                    && secondsLeft == 0) {
                  /* Buzz Buzz Buzz*/
                  mVibrator.vibrate(new long[] {0, 200, 200, 200, 200, 200}, -1);
                  mFiveMinuteWarning = false;
                }
              }

              /**
               * The countdown finished. Give one good vibration, remove the notification, clean up
               * the service, and call it a day.
               */
              @Override
              public void onFinish() {
                /* BUZZ */
                mVibrator.vibrate(600);
                /* Cleanup */
                mNotificationManager.cancel(NOTIFICATION_ID);
                unregisterReceiver(mBroadcastReceiver);
                CountdownService.this.stopSelfResult(mStartId);
              }
            };

        /* Start the countdown */
        mCountDownTimer.start();
      }
    }
  }