/ / Como trazer contatos para enviar um texto - android, sms, android-contentprovider, android-contacts

Como criar contatos para enviar um texto - android, sms, android-contentprovider, android-Contacts

Eu tenho um aplicativo que define uma palavra eem seguida, envia a definição por SMS. O problema é que o usuário precisa digitar um número de telefone. Eu estava pensando que talvez o aplicativo devesse abrir a lista de contatos, para que o usuário possa selecionar um contato que o usuário possa enviar a mensagem para esse contato. Aqui está o meu código para a SMSActivity:

public class SMSActivity extends Activity
{

String APPTAG = "SMSTransmit";

//Private static strings:
private final static String SENT = "SMS_SENT";
private final static String DELIVERED = "SMS_DELIVERED";

private Button btnSend;
private Button btnExit;
private Button btnClear;
private EditText etPhoneNumber;
private EditText etUserMessage;

//Private BroadcastReceiver member variables:
private SMSDispatchReceiver sendReceiver = null;
private SMSReceiptReceiver receiptReceiver = null;


@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);

Bundle extras = getIntent().getExtras();
String definiedWord = null;
if (extras != null)
{
definiedWord = extras.getString("DEFINITION");
}
else
{
definiedWord = "None";
}

Log.d("recievedAGAIN", definiedWord);
Log.v(APPTAG, "MainActivity: onCreate() called");

//Create a new broadcast receiver for sending the SMS
sendReceiver = new SMSDispatchReceiver();

//Create a new broadcast receiver for receipt of the send SMS
receiptReceiver = new SMSReceiptReceiver();

//Register the new receivers (as new IntentFiler() objects):
registerReceiver(sendReceiver, new IntentFilter(SENT));
registerReceiver(receiptReceiver, new IntentFilter(DELIVERED));

//Get the view objects:
btnSend = (Button) findViewById(R.id.btnSend);
btnClear = (Button) findViewById(R.id.btnClear);
btnExit = (Button) findViewById(R.id.btnExit);
etPhoneNumber = (EditText) findViewById(R.id.etNumber);
etUserMessage = (EditText) findViewById(R.id.etMessage);

//Disable the soft keyboard (this is only in general):
InputMethodManager inMethodMgr =                                                                (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inMethodMgr.hideSoftInputFromInputMethod(etPhoneNumber.getWindowToken(), 0);
inMethodMgr.hideSoftInputFromInputMethod(etUserMessage.getWindowToken(), 0);

//Set the hint for the EditText boxes:
etPhoneNumber.setHint("Enter phone number (Default = 5556)");
etUserMessage.setHint(definiedWord);

//Create an click event listener for the Send button (OnClickListener):
btnSend.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View v)
{

String strMessage = null;
String strNumber = null;

//Get the phone number from the EditText box:
strNumber = etPhoneNumber.getText().toString();

//Check the phone number:
if (strNumber.length() <= 0)
{

//No phone number, then get the default (5556):
strNumber = SMSProperties.getPhoneNumber();
}


//Get the message from the EditText box:
strMessage = etUserMessage.getText().toString();

//Check the message contains some content:
if (strMessage.length() > 0)
{

//Sent the SMS to the phone number
sendSMS(strNumber, strMessage);

} else
{

//Warn the user and reset the focus / hint:
Toast.makeText(getBaseContext(), "No message text! Please      enter some text for the SMS!!", Toast.LENGTH_SHORT).show();
etUserMessage.setHint("Enter message text here . . . ");
etUserMessage.requestFocus();

}

}
});



//Create an click event listener for the Clear button (OnClickListener):
btnClear.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

//Clear the appropriate EditText box:
if (etUserMessage.isFocused()) {

//Clear the text in the user message EditText box:
etUserMessage.setText("");

//Set the hint in the user message EditText box:
etUserMessage.setHint("Enter message text here . . . ");

} else if (etPhoneNumber.isFocused()) {

//Clear the text in the phone number EditText box:
etPhoneNumber.setText("");

//Set the hint in the phone number EditText box:
etPhoneNumber.setHint("Enter phone number (Default = 5556)");
}
}
});



//Create an click event listener for the Exit button (OnClickListener):
btnExit.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View v)
{

//Finish the activity:
//NOTE: As this is the main activity it will cause onDestroy() to be called!
finish();
}
});

}



//Method to send an SMS message to another device:
private void sendSMS(String strNum, String strMsg)
{
//TODO: Create a pending intent for the SMSDistatchReceiver (SENT):
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent("SENT"), 0);

//TODO: Create a pending intent for the SMSReceiptReceiver (DELIVERED):
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent("DELIVERED"), 0);
//Get a default SmsManager object:
SmsManager smsMgr = SmsManager.getDefault();

//TODO: Send the SMS using the SmsManager:
smsMgr.sendTextMessage(strNum, null, strMsg, sentPI, deliveredPI);
}

Respostas:

1 para resposta № 1

considere que o contato é um botão para abrir a lista de contatos

contact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View g) {
Intent q = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(q, 1001);

}
});

e para lidar com o resultado (que é referenciado por 1001) use isto:

public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);

if (resultCode == Activity.RESULT_OK) {
// getting the URI from result for further working
Uri contactData = data.getData();
Cursor c =  managedQuery(contactData, null, null, null, null);

if (c.moveToFirst()) {


String  id =c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

String hasPhone =c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));



if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,
null, null);
phones.moveToFirst();
//this string will hold the contact number
String cNumber = phones.getString(phones.getColumnIndex("data1"));
//this string will hold the contact name
String cName = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

}

}}
}