I have it done right now with an if statement and the code for each every time, but what I'd like to do is something like this:
import android.content.Intent;
import android.provider.Contacts;
import android.provider.ContactsContract;
public class AddContacts{
public static void newContacts(){
Intent i = new Intent(Intent.ACTION_INSERT);
i.setType(ContactsContract.Contacts.CONTENT_TYPE);
i.putExtra(ContactsContract.Intents.Insert.NAME, Directory.ResultsDetails[0]);
i.putExtra(ContactsContract.Intents.Insert.PHONE, Directory.ResultsDetails[4]);
i.putExtra(ContactsContract.Intents.Insert.PHONE_TYPE, 3);
i.putExtra(ContactsContract.Intents.Insert.EMAIL, Directory.ResultsDetails[3]);
i.putExtra(ContactsContract.Intents.Insert.EMAIL_TYPE, 2);
startActivity(i);
}
public static void oldContacts(){
Intent i = new Intent(Contacts.Intents.Insert.ACTION, Contacts.People.CONTENT_URI);
i.putExtra(Contacts.Intents.Insert.NAME, Directory.ResultsDetails[0]);
i.putExtra(Contacts.Intents.Insert.PHONE, Directory.ResultsDetails[4]);
i.putExtra(Contacts.Intents.Insert.PHONE_TYPE, 3);
i.putExtra(Contacts.Intents.Insert.EMAIL, Directory.ResultsDetails[3]);
i.putExtra(Contacts.Intents.Insert.EMAIL_TYPE, 2);
startActivity(i);
}
}
and then have something like:
if(sdk >=5){
AddContacts.newConta开发者_开发技巧cts();
}else{
AddContacts.oldContacts();}
when the 'Add to Contacts' button is pressed.
Unfortunately, I'm not sure how I should do this. I tried making a new class in the package (AddContacts) and putting those in, but it won't let me start an activity that way. I'd like to push this code out to it's own class because it will save some clutter in the rest of my app. Any help is appreciated!
The error I get is on startActivity(i); | The method startActivity(Intent) is undefined for the type AddContacts
The method startActivity(Intent) is undefined for the type AddContacts
Have newContacts()
and oldContacts()
take an Activity
as a parameter, and call startActivity()
on that Activity
.
However, your code here will not work in general. If you are trying to support Android 1.x, you cannot refer to ContactsContract
in a class that will be loaded into the VM, since ContactsContract
won't exist -- you will get a VerifyError
at runtime. Conversely, if you are only trying to support Android 2.x/3.x, then skip Contacts
outright and only worry about ContactsContract
.
Here is a sample project demonstrating accessing both Contacts
and ContactsContract
, in a backwards-compatible way, where it will use Contacts
on 1.x and ContactsContract
on 2.x/3.x. In this case I am querying the providers, but the same concept holds for inserting as well.
That being said, I would recommend just supporting Android 2.x/3.x for a brand new app, as 1.x is around 4% of the market at the moment, and falling.
精彩评论