无法在Android应用中获取Gmail联系人 - 可以使用相同的代码从Desktop Java App获取

时间:2012-01-07 02:19:12

标签: android google-contacts

我的Java应用程序能够连接和获取我的Gmail联系人,但Android应用程序抛出异常“错误连接登录URI”。

以下是两个应用程序的代码。我在模拟器和手机上试过Android App。在两者中,我得到了同样的错误。我可以在网络浏览器中打开两个页面(我的意思是,我有互联网访问权限)。请指教。

//Java Application Code
public static void main(String[] args) throws ServiceException, IOException {
    ContactsService service;
    URL feedUrl;
    ContactFeed resultFeed;
    String url = "https://www.google.com/m8/feeds/" + "contacts/"
            + "username@gmail.com" + "/thin";
    System.err.println("This is the url:" + url);
    try {
        feedUrl = new URL(url);
        service = new ContactsService("Google-contactsExampleApp-3");
        service.setUserCredentials("username@gmail.com", "password");
        resultFeed = service.getFeed(feedUrl, ContactFeed.class);
        for (ContactEntry entry : resultFeed.getEntries()) {

            if (entry.getTitle() != null) {

                System.err.println("Contact name: "
                        + entry.getTitle().getPlainText());

            } else {
                System.err.println("Contact has no name");

            }
        }
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    }
}

//Android Application Code
public void onClick(View arg0) {

    ContactsService service;
    URL feedUrl;
    ContactFeed resultFeed;

    String url = "https://www.google.com/m8/feeds/" + "contacts/"
            + "username@gmail.com" + "/thin";
    System.err.println("This is the url:" + url);
    try {
        feedUrl = new URL(url);
        service = new ContactsService("Google-contactsExampleApp-3");
        service.setUserCredentials("username@gmail.com", "password");
        resultFeed = service.getFeed(feedUrl, ContactFeed.class);
        for (ContactEntry entry : resultFeed.getEntries()) {

            if (entry.getTitle() != null) {
                Toast.makeText(getApplicationContext(),
                        "Contact name: " + entry.getTitle().getPlainText(),
                        Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(getApplicationContext(),
                        "Contact has no name", Toast.LENGTH_SHORT).show();

            }

        }
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(),
                "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        System.out.println("**** Exception: " + e.getMessage());

        //Exception: Error connecting with login URI

    }


}
}

2 个答案:

答案 0 :(得分:0)

您确定可以使用网络连接吗?确保此权限位于AndroidManifest.xml文件中:

<uses-permission android:name="android.permission.INTERNET" />

答案 1 :(得分:0)

 In android emulator you will find email application.You just click that and give the email Id and password.Login in to account.then run your code in emulator it will works