Google SpreadSheets Api设置

时间:2018-01-10 06:53:56

标签: android google-drive-api spreadsheet google-spreadsheet-api google-authentication

我正在创建一个Android应用程序,它将数据存储在电子表格中,我已经使用了Drive和SpreadSheet API,并且正如他们的快速入门部分所建议的那样集成现在问题是我是否必须完成所有授权并获得权限和每次我想与api交互时检查谷歌播放服务的东西或有没有办法避免这种情况。以下是我到目前为止所做的代码片段。

public class SpreadSheetActivity extends Activity implements EasyPermissions.PermissionCallbacks {
    Button setup;
    EditText name;
    String name_var;
    GoogleAccountCredential mCredential;
    static ProgressDialog mProgress;
    static final int REQUEST_ACCOUNT_PICKER = 1000;
    static final int REQUEST_AUTHORIZATION = 1001;
    static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
    static final int REQUEST_PERMISSION_GET_ACCOUNTS = 1003;
    private static final String PREF_ACCOUNT_NAME = "accountName";
    private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS, 
                  DriveScopes.DRIVE};


        @Override
      public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_backend_google);
    setup=findViewById(R.id.setup_btn);
    name=findViewById(R.id.url);
    LinearLayout activityLayout = new LinearLayout(this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    activityLayout.setLayoutParams(lp);
    activityLayout.setOrientation(LinearLayout.VERTICAL);
    activityLayout.setPadding(16, 16, 16, 16);

    ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);


    setup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            name_var=name.getText().toString();
            if(validateGoogle(name_var)){
                getResultsFromApi();}
                else {
                name.setError("Enter a valid name");
            }

        }
    });

    mProgress = new ProgressDialog(this);
    mProgress.setMessage("Calling Google Sheets API ...");

    setContentView(activityLayout);
    // Initialize credentials and service object.
    mCredential = GoogleAccountCredential.usingOAuth2(
            getApplicationContext(), Arrays.asList(SCOPES))
            .setBackOff(new ExponentialBackOff());
      }
     public  void getResultsFromApi() {
    if (! isGooglePlayServicesAvailable()) {
        acquireGooglePlayServices();
    } else if (mCredential.getSelectedAccountName() == null) {
        chooseAccount();
    } else if (! isDeviceOnline()) {
        Toast.makeText(SpreadSheetActivity.this,"Please connect to internet 
      and try again",Toast.LENGTH_LONG).show();
    } else {

        new 
   MakeRequestTask(SpreadSheetActivity.this,mCredential,name_var).execute();


    }
}

    @AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
     public  void chooseAccount() {
    if (EasyPermissions.hasPermissions(
            this, Manifest.permission.GET_ACCOUNTS)) {
        String accountName = getPreferences(Context.MODE_PRIVATE)
                .getString(PREF_ACCOUNT_NAME, null);
        if (accountName != null) {
            mCredential.setSelectedAccountName(accountName);
            getResultsFromApi();
        } else {
            // Start a dialog from which the user can choose an account
            startActivityForResult(
                    mCredential.newChooseAccountIntent(),
                    REQUEST_ACCOUNT_PICKER);
        }
          } else {
        // Request the GET_ACCOUNTS permission via a user dialog
        EasyPermissions.requestPermissions(
                this,
                "This app needs to access your Google account (via 
       Contacts).",
                REQUEST_PERMISSION_GET_ACCOUNTS,
                Manifest.permission.GET_ACCOUNTS);
    }
    }

    @Override
      public void onActivityResult(
        int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
        case REQUEST_GOOGLE_PLAY_SERVICES:
            if (resultCode != RESULT_OK) {
                Toast.makeText(SpreadSheetActivity.this,"This app requires 
    Google Play Services. Please install " +
                        "Google Play Services on your device and relaunch 
    this app.",Toast.LENGTH_LONG).show();
            } else {
                getResultsFromApi();
            }
            break;
        case REQUEST_ACCOUNT_PICKER:
            if (resultCode == RESULT_OK && data != null &&
                    data.getExtras() != null) {
                String accountName =

          data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                if (accountName != null) {
                    SharedPreferences settings =
                            getPreferences(Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString(PREF_ACCOUNT_NAME, accountName);
                    editor.apply();
                    mCredential.setSelectedAccountName(accountName);
                    getResultsFromApi();
                }
            }
            break;
        case REQUEST_AUTHORIZATION:
            if (resultCode == RESULT_OK) {
                getResultsFromApi();
            }
            break;
            }
       }
        @Override
       public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
       super.onRequestPermissionsResult(requestCode, permissions, 
      grantResults);
         EasyPermissions.onRequestPermissionsResult(
            requestCode, permissions, grantResults, this);
       }
     @Override
     public void onPermissionsGranted(int requestCode, List<String> list) {
       // Do nothing.
      }

     @Override
      public void onPermissionsDenied(int requestCode, List<String> list) {
        // Do nothing.
     }

     public  boolean isDeviceOnline() {
    ConnectivityManager connMgr =
            (ConnectivityManager) 
     getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    return (networkInfo != null && networkInfo.isConnected());
    }

    public boolean isGooglePlayServicesAvailable() {
    GoogleApiAvailability apiAvailability =
            GoogleApiAvailability.getInstance();
    final int connectionStatusCode =

   apiAvailability.isGooglePlayServicesAvailable(SpreadSheetActivity.this);
    return connectionStatusCode == ConnectionResult.SUCCESS;
}


     public  void acquireGooglePlayServices() {
    GoogleApiAvailability apiAvailability =
            GoogleApiAvailability.getInstance();
    final int connectionStatusCode =
            apiAvailability.isGooglePlayServicesAvailable(this);
    if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
        showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
    }
}

   void showGooglePlayServicesAvailabilityErrorDialog(
        final int connectionStatusCode) {
    GoogleApiAvailability apiAvailability = 
 GoogleApiAvailability.getInstance();
    Dialog dialog = apiAvailability.getErrorDialog(
            SpreadSheetActivity.this,
            connectionStatusCode,
            REQUEST_GOOGLE_PLAY_SERVICES);
    dialog.show();
}
     public boolean validateGoogle(String url_var){
    boolean valid=true;
    if (name_var.isEmpty()) {
        name.setError("enter a name for new Spreadsheet");
        valid = false;
    } else {
        name.setError(null);
    }
    return valid;
}

} 现在在asynctask类中我创建了一个电子表格,之后我想更新该电子表格中的数据。我是否必须在每次更新时都执行此操作?或者有什么方法我不知道?

0 个答案:

没有答案