我怎样才能列出谷歌文档android?

发布于 2024-12-01 16:57:26 字数 5984 浏览 0 评论 0原文

使用 Accountmanager 我现在得到了令牌怎么办?

m 使用以下类

package com.googleaccount;


import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class GoogleAccountTestActivity extends Activity {
    /** Called when the activity is first created. */
     private static final int DIALOG_ACCOUNTS = 0;
    private static final int REQUEST_AUTHENTICATE = 0;
    protected static final String AUTH_TOKEN_TYPE = "";
    private String authToken;
    Context context;    


        @Override
          public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            context=this;          
            gotAccount(false);
          }

          @Override
          protected Dialog onCreateDialog(int id) {
            switch (id) {
              case DIALOG_ACCOUNTS:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Select a Google account");
                final AccountManager manager = AccountManager.get(this);
                final Account[] accounts = manager.getAccountsByType("com.google");
                final int size = accounts.length;
                String[] names = new String[size];
                for (int i = 0; i < size; i++) {
                  names[i] = accounts[i].name;
                }
                builder.setItems(names, new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {
                    gotAccount(manager, accounts[which]);
                  }
                });
                return builder.create();
            }
            return null;
          }

          private void gotAccount(boolean tokenExpired) {
            SharedPreferences settings = getSharedPreferences("test", 0);
            String accountName = settings.getString("accountName", null);
            if (accountName != null) {
              AccountManager manager = AccountManager.get(this);
              Account[] accounts = manager.getAccountsByType("com.google");
              int size = accounts.length;
              for (int i = 0; i < size; i++) {
                Account account = accounts[i];
                if (accountName.equals(account.name)) {

                     Toast.makeText(this,"OLD accunt name"+account.name , Toast.LENGTH_SHORT).show();
                  if (tokenExpired) {
                      Toast.makeText(this,"Token EXpired", Toast.LENGTH_SHORT).show();
                    manager.invalidateAuthToken("com.google", this.authToken);

                  }
                  gotAccount(manager, account);
                  return;
                }
              }
            }
            showDialog(DIALOG_ACCOUNTS);
          }

          private void gotAccount(final AccountManager manager, final Account account) {
            SharedPreferences settings = getSharedPreferences("test", 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("accountName", account.name);
            editor.commit();            

           new Thread() {
             @Override
              public void run() {
                try {
                  final Bundle bundle =
                      manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, null, null)
                          .getResult();

                  runOnUiThread(new Runnable() {

                   public void run() {
                     try {
                        if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                          Intent intent =
                              bundle.getParcelable(AccountManager.KEY_INTENT);
                          int flags = intent.getFlags();
                          flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                          intent.setFlags(flags);
                          startActivityForResult(intent, REQUEST_AUTHENTICATE);
                        } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                          authenticatedClientLogin(
                              bundle.getString(AccountManager.KEY_AUTHTOKEN));
                        }
                      } catch (Exception e) {
                       // handleException(e);
                          Toast.makeText(context,e.getMessage(), Toast.LENGTH_SHORT).show(); 
                      }
                    }
                  });
                } catch (Exception e) {
                  //handleException(e);
                    Toast.makeText(context,e.getMessage(), Toast.LENGTH_SHORT).show(); 
                }
              }
           }.start();
          }

          @Override
          protected void onActivityResult(
              int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
              case REQUEST_AUTHENTICATE:
                if (resultCode == RESULT_OK) {
                    Toast.makeText(this,"Result OK!!" , Toast.LENGTH_SHORT).show();
                  gotAccount(false);
                } else {
                    Toast.makeText(this,"Result False!!" , Toast.LENGTH_SHORT).show();
                  showDialog(DIALOG_ACCOUNTS);
                }
                break;
            }
          }

          private void authenticatedClientLogin(String authToken) {
            this.authToken = authToken;
            Toast.makeText(this,"Token "+authToken, Toast.LENGTH_LONG).show();
           //((GoogleHeaders) transport.defaultHeaders).setGoogleLogin(authToken);
            //authenticated();
          }
}

Using Accountmanager i get the token now what?

m using the following class

package com.googleaccount;


import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class GoogleAccountTestActivity extends Activity {
    /** Called when the activity is first created. */
     private static final int DIALOG_ACCOUNTS = 0;
    private static final int REQUEST_AUTHENTICATE = 0;
    protected static final String AUTH_TOKEN_TYPE = "";
    private String authToken;
    Context context;    


        @Override
          public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            context=this;          
            gotAccount(false);
          }

          @Override
          protected Dialog onCreateDialog(int id) {
            switch (id) {
              case DIALOG_ACCOUNTS:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Select a Google account");
                final AccountManager manager = AccountManager.get(this);
                final Account[] accounts = manager.getAccountsByType("com.google");
                final int size = accounts.length;
                String[] names = new String[size];
                for (int i = 0; i < size; i++) {
                  names[i] = accounts[i].name;
                }
                builder.setItems(names, new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {
                    gotAccount(manager, accounts[which]);
                  }
                });
                return builder.create();
            }
            return null;
          }

          private void gotAccount(boolean tokenExpired) {
            SharedPreferences settings = getSharedPreferences("test", 0);
            String accountName = settings.getString("accountName", null);
            if (accountName != null) {
              AccountManager manager = AccountManager.get(this);
              Account[] accounts = manager.getAccountsByType("com.google");
              int size = accounts.length;
              for (int i = 0; i < size; i++) {
                Account account = accounts[i];
                if (accountName.equals(account.name)) {

                     Toast.makeText(this,"OLD accunt name"+account.name , Toast.LENGTH_SHORT).show();
                  if (tokenExpired) {
                      Toast.makeText(this,"Token EXpired", Toast.LENGTH_SHORT).show();
                    manager.invalidateAuthToken("com.google", this.authToken);

                  }
                  gotAccount(manager, account);
                  return;
                }
              }
            }
            showDialog(DIALOG_ACCOUNTS);
          }

          private void gotAccount(final AccountManager manager, final Account account) {
            SharedPreferences settings = getSharedPreferences("test", 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("accountName", account.name);
            editor.commit();            

           new Thread() {
             @Override
              public void run() {
                try {
                  final Bundle bundle =
                      manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, null, null)
                          .getResult();

                  runOnUiThread(new Runnable() {

                   public void run() {
                     try {
                        if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                          Intent intent =
                              bundle.getParcelable(AccountManager.KEY_INTENT);
                          int flags = intent.getFlags();
                          flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                          intent.setFlags(flags);
                          startActivityForResult(intent, REQUEST_AUTHENTICATE);
                        } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                          authenticatedClientLogin(
                              bundle.getString(AccountManager.KEY_AUTHTOKEN));
                        }
                      } catch (Exception e) {
                       // handleException(e);
                          Toast.makeText(context,e.getMessage(), Toast.LENGTH_SHORT).show(); 
                      }
                    }
                  });
                } catch (Exception e) {
                  //handleException(e);
                    Toast.makeText(context,e.getMessage(), Toast.LENGTH_SHORT).show(); 
                }
              }
           }.start();
          }

          @Override
          protected void onActivityResult(
              int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
              case REQUEST_AUTHENTICATE:
                if (resultCode == RESULT_OK) {
                    Toast.makeText(this,"Result OK!!" , Toast.LENGTH_SHORT).show();
                  gotAccount(false);
                } else {
                    Toast.makeText(this,"Result False!!" , Toast.LENGTH_SHORT).show();
                  showDialog(DIALOG_ACCOUNTS);
                }
                break;
            }
          }

          private void authenticatedClientLogin(String authToken) {
            this.authToken = authToken;
            Toast.makeText(this,"Token "+authToken, Toast.LENGTH_LONG).show();
           //((GoogleHeaders) transport.defaultHeaders).setGoogleLogin(authToken);
            //authenticated();
          }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

她如夕阳 2024-12-08 16:57:26

最好的选择是使用 Google API 客户端库:
http://code.google.com/p/google-api -java-client/wiki/Setup

下载核心 jar(链接可在 wiki 中找到)和依赖项。特别是,您应该寻找以下 jar:

  • google-api-client-version-alpha.jar
  • google-api-client-googleapis-version-alpha.jar
  • guava-version.jar
  • jackson-core-asl-

version.jar 。设置描述您的 feed 的模型类。对于 DocList,请参考此示例:
Google API DocList 示例

DocUrl.java、DocumentListEntry.java、 DocumentListFeed.java、Entry.java、Feed.java & Link.java 是应该设置的模型类。

接下来,通过选择解析器(即 Atom/Json)初始化 HTTPTransport 并触发您的请求。

    public static final XmlNamespaceDictionary NAMESPACE_DICTIONARY = new XmlNamespaceDictionary();

static {
    NAMESPACE_DICTIONARY.set("", "http://www.w3.org/2005/Atom");
    NAMESPACE_DICTIONARY.set("app", "http://www.w3.org/2007/app");
    NAMESPACE_DICTIONARY.set("batch", "http://schemas.google.com/gdata/batch");
    NAMESPACE_DICTIONARY.set("docs", "http://schemas.google.com/docs/2007");
    NAMESPACE_DICTIONARY.set("gs", "http://schemas.google.com/spreadsheets/2006");
    NAMESPACE_DICTIONARY.set("gd", "http://schemas.google.com/g/2005");
    NAMESPACE_DICTIONARY.set("gsx", "http://schemas.google.com/spreadsheets/2006/extended");
    NAMESPACE_DICTIONARY.set("openSearch", "http://a9.com/-/spec/opensearch/1.1/");
    NAMESPACE_DICTIONARY.set("xml", "http://www.w3.org/XML/1998/namespace");
}

    private static HttpTransport transport;

    private void setupTransport() {
        transport = new NetHttpTransport();
        GoogleHeaders headers = new GoogleHeaders();
        transport.defaultHeaders = headers;
        headers.setApplicationName("MyApp/1.0");
        headers.gdataVersion = "3.0";
        ((GoogleHeaders) transport.defaultHeaders)
                                        .setGoogleLogin(<yourtoken>);
        AtomParser parser = new AtomParser();
        parser.namespaceDictionary = Util.NAMESPACE_DICTIONARY;
        transport.addParser(parser);

    }

    public processDocs() {
      setupTransport();
      DocUrl url = DocUrl.relativeToRoot(<URL suffix>);
      DocListFeed feed = DocListFeed.executeGet(transport, url);
      if (feed.entries != null) {
          for (DocEntry entry : feed.entries) {
              //<do whatever>
          }
       }

Your best bet is to use the Google API Client library:
http://code.google.com/p/google-api-java-client/wiki/Setup

Download the core jars(link to be found in the wiki) and dependencies. In particular, you should be looking for these jars:

  • google-api-client-version-alpha.jar
  • google-api-client-googleapis-version-alpha.jar
  • guava-version.jar
  • jackson-core-asl-version.jar

Next. set up your model classes that describe your feed. For DocList, refer this sample:
Google API DocList Sample

DocUrl.java, DocumentListEntry.java, DocumentListFeed.java, Entry.java, Feed.java & Link.java are the model classes which should set you up.

Next, initialize your HTTPTransport by choosing the parser i.e. Atom/Json and fire your request.

    public static final XmlNamespaceDictionary NAMESPACE_DICTIONARY = new XmlNamespaceDictionary();

static {
    NAMESPACE_DICTIONARY.set("", "http://www.w3.org/2005/Atom");
    NAMESPACE_DICTIONARY.set("app", "http://www.w3.org/2007/app");
    NAMESPACE_DICTIONARY.set("batch", "http://schemas.google.com/gdata/batch");
    NAMESPACE_DICTIONARY.set("docs", "http://schemas.google.com/docs/2007");
    NAMESPACE_DICTIONARY.set("gs", "http://schemas.google.com/spreadsheets/2006");
    NAMESPACE_DICTIONARY.set("gd", "http://schemas.google.com/g/2005");
    NAMESPACE_DICTIONARY.set("gsx", "http://schemas.google.com/spreadsheets/2006/extended");
    NAMESPACE_DICTIONARY.set("openSearch", "http://a9.com/-/spec/opensearch/1.1/");
    NAMESPACE_DICTIONARY.set("xml", "http://www.w3.org/XML/1998/namespace");
}

    private static HttpTransport transport;

    private void setupTransport() {
        transport = new NetHttpTransport();
        GoogleHeaders headers = new GoogleHeaders();
        transport.defaultHeaders = headers;
        headers.setApplicationName("MyApp/1.0");
        headers.gdataVersion = "3.0";
        ((GoogleHeaders) transport.defaultHeaders)
                                        .setGoogleLogin(<yourtoken>);
        AtomParser parser = new AtomParser();
        parser.namespaceDictionary = Util.NAMESPACE_DICTIONARY;
        transport.addParser(parser);

    }

    public processDocs() {
      setupTransport();
      DocUrl url = DocUrl.relativeToRoot(<URL suffix>);
      DocListFeed feed = DocListFeed.executeGet(transport, url);
      if (feed.entries != null) {
          for (DocEntry entry : feed.entries) {
              //<do whatever>
          }
       }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文