如何在android中导入谷歌联系人(以编程方式)?

时间:2015-08-11 04:17:35

标签: android google-contacts

任何机构都可以建议一种方式,如何从谷歌提取联系人到Android应用程序?

谢谢!

下面是我的代码,我在第57行遇到运行时错误。具体来说,它在AsyncTask中显示异常。

package com.example.isan.contacts;

import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;

import com.google.gdata.client.Query;
import com.google.gdata.client.Service;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.Link;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.NoLongerAvailableException;
import com.google.gdata.util.ServiceException;


public class MainActivity extends ActionBarActivity {

private URL feedUrl;
private static final String username="username";
private static final String pwd="password";
private ContactsService service;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String url = "https://www.google.com/m8/feeds/contacts/username/full";

    try {
        this.feedUrl = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    new GetTask().execute();
}





private class GetTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        service = new ContactsService("Contacts");
        try {
            service.setUserCredentials(username, pwd);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        try {
            queryEntries();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}

private void queryEntries() throws IOException, ServiceException{
    Query myQuery = new Query(feedUrl);
    myQuery.setMaxResults(50);
    myQuery.setStartIndex(1);
    myQuery.setStringCustomParameter("showdeleted", "false");
    myQuery.setStringCustomParameter("requirealldeleted", "false");
    //        myQuery.setStringCustomParameter("sortorder", "ascending");
    //        myQuery.setStringCustomParameter("orderby", "");


    try{
        ContactFeed resultFeed = (ContactFeed)this.service.query(myQuery, ContactFeed.class);
        for (ContactEntry entry : resultFeed.getEntries()) {
            printContact(entry);
        }
        System.err.println("Total: " + resultFeed.getEntries().size() + " entries found");

    }
    catch (NoLongerAvailableException ex) {
        System.err.println("Not all placehorders of deleted entries are available");
    }

}
private void printContact(ContactEntry contact) throws IOException, ServiceException{
    System.err.println("Id: " + contact.getId());
    if (contact.getTitle() != null)
        System.err.println("Contact name: " + contact.getTitle().getPlainText());
    else {
        System.err.println("Contact has no name");
    }

    System.err.println("Last updated: " + contact.getUpdated().toUiString());
    if (contact.hasDeleted()) {
        System.err.println("Deleted:");
    }

    //        ElementHelper.printContact(System.err, contact);

    Link photoLink = contact.getLink("http://schemas.google.com/contacts/2008/rel#photo", "image/*");
    if (photoLink.getEtag() != null) {
        Service.GDataRequest request = service.createLinkQueryRequest(photoLink);

        request.execute();
        InputStream in = request.getResponseStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        RandomAccessFile file = new RandomAccessFile("/tmp/" + contact.getSelfLink().getHref().substring(contact.getSelfLink().getHref().lastIndexOf('/') + 1), "rw");

        byte[] buffer = new byte[4096];
        for (int read = 0; (read = in.read(buffer)) != -1; )
            out.write(buffer, 0, read);
        file.write(out.toByteArray());
        file.close();
        in.close();
        request.end();
    }

    System.err.println("Photo link: " + photoLink.getHref());
    String photoEtag = photoLink.getEtag();
    System.err.println("  Photo ETag: " + (photoEtag != null ? photoEtag : "(No contact photo uploaded)"));

    System.err.println("Self link: " + contact.getSelfLink().getHref());
    System.err.println("Edit link: " + contact.getEditLink().getHref());
    System.err.println("ETag: " + contact.getEtag());
    System.err.println("-------------------------------------------\n");
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

2 个答案:

答案 0 :(得分:1)

它很简单。你可以尝试这段代码。

public static void printAllContacts(ContactsService myService)
    throws ServiceException, IOException {
  // Request the feed
  URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/liz@gmail.com/full");
  ContactFeed resultFeed = myService.getFeed(feedUrl, ContactFeed.class);
  // Print the results
  System.out.println(resultFeed.getTitle().getPlainText());
  for (int i = 0; i < resultFeed.getEntries().size(); i++) {
    ContactEntry entry = resultFeed.getEntries().get(i);
    System.out.println("\t" + entry.getTitle().getPlainText());

    System.out.println("Email addresses:");
    for (Email email : entry.getEmailAddresses()) {
      System.out.print(" " + email.getAddress());
      if (email.getRel() != null) {
        System.out.print(" rel:" + email.getRel());
      }
      if (email.getLabel() != null) {
        System.out.print(" label:" + email.getLabel());
      }
      if (email.getPrimary()) {
        System.out.print(" (primary) ");
      }
      System.out.print("\n");
    }

    System.out.println("IM addresses:");
    for (Im im : entry.getImAddresses()) {
      System.out.print(" " + im.getAddress());
      if (im.getLabel() != null) {
        System.out.print(" label:" + im.getLabel());
      }
      if (im.getRel() != null) {
        System.out.print(" rel:" + im.getRel());
      }
      if (im.getProtocol() != null) {
        System.out.print(" protocol:" + im.getProtocol());
      }
      if (im.getPrimary()) {
        System.out.print(" (primary) ");
      }
      System.out.print("\n");
    }

    System.out.println("Groups:");
    for (GroupMembershipInfo group : entry.getGroupMembershipInfos()) {
      String groupHref = group.getHref();
      System.out.println("  Id: " + groupHref);
    }

    System.out.println("Extended Properties:");
    for (ExtendedProperty property : entry.getExtendedProperties()) {
      if (property.getValue() != null) {
        System.out.println("  " + property.getName() + "(value) = " +
            property.getValue());
      } else if (property.getXmlBlob() != null) {
        System.out.println("  " + property.getName() + "(xmlBlob)= " +
            property.getXmlBlob().getBlob());
      }
    }

    String photoLink = entry.getContactPhotoLink().getHref();
    System.out.println("Photo Link: " + photoLink);

    if (photoLink.getEtag() != null) {
      System.out.println("Contact Photo's ETag: " + photoLink.getEtag());
    }

    System.out.println("Contact's ETag: " + entry.getEtag());
  }
}

有关如何使用最新的Contacts API版本3的完整指南,请查看this

更新

您需要导入这些包。

import com.google.gdata.client.*;
import com.google.gdata.client.contacts.*;
import com.google.gdata.data.*;
import com.google.gdata.data.contacts.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.io.IOException;
import java.net.URL;

答案 1 :(得分:0)

import

无法google contacts app current contacts

但您可以访问app中的qs2 = Offer.objects.select_related('subscription').annotate(monthly_fee=F('subscription__monthly_fee'))