2012-01-06 2 views
0

Это приложение работает с контактным номером, который я вводил первым ... но когда я меняю номер контакта и текст сообщения ... приложения отправляют сообщение на первый контактный номер не изменившийся контактный номер .. скажите, пожалуйста, как отправить сообщение на другом контакте в указанное время ..как отправить сообщение другому контакту в android в указанное время

Мой Главный класс:

public class TimeSms extends Activity implements OnClickListener { 
Button time_btn,date_btn,send_btn,pick_contact; 
EditText to,msg_body,time_txt,date_txt; 
Calendar calendar; 
int hour,min; 
int year,month,date; 
String recipient,message2,contact,pick_no; 
PendingIntent pi; 
ArrayList<PendingIntent> pn=new ArrayList<PendingIntent>(); 
ArrayList<PendingIntent> pnn=new ArrayList<PendingIntent>(); 
final static String SENT = "com.dinesg.TimeSms.action.SMS_SENT"; 
public static final int TIME_DIALOG=0; 

public static final int DATE_DIALOG=1; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    to=(EditText)findViewById(R.id.editText1); 
    msg_body=(EditText)findViewById(R.id.editText2); 
    time_txt=(EditText)findViewById(R.id.editText3); 
    date_txt=(EditText)findViewById(R.id.editText4); 

    time_btn=(Button)findViewById(R.id.button1); 
    date_btn=(Button)findViewById(R.id.button2); 
    send_btn=(Button)findViewById(R.id.button3); 
    pick_contact=(Button)findViewById(R.id.button4); 

    time_btn.setOnClickListener(this); 
    date_btn.setOnClickListener(this); 
    send_btn.setOnClickListener(this); 
    pick_contact.setOnClickListener(this); 

    calendar=Calendar.getInstance(); 
    hour=calendar.get(Calendar.HOUR_OF_DAY); 
    min=calendar.get(Calendar.MINUTE); 

    year=calendar.get(Calendar.YEAR); 
    month=calendar.get(Calendar.MONTH); 
    date=calendar.get(Calendar.DAY_OF_MONTH); 


    UpdateDate(); 
    UpdateTime(); 


} 
private void UpdateDate() { 

    date_txt.setText(new StringBuilder().append(date).append("-").append(month+1).append("-").append(year));// TODO Auto-generated method stub 

} 
private void UpdateTime() { 
    // TODO Auto-generated method stub 
    time_txt.setText(new StringBuilder().append(hour).append(":").append(min)); 

} 
public TimePickerDialog.OnTimeSetListener time_listen=new TimePickerDialog.OnTimeSetListener() { 

    @Override 
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 
     hour=hourOfDay;// TODO Auto-generated method stub 
     min=minute; 
     UpdateTime(); 

    } 
}; 

public DatePickerDialog.OnDateSetListener date_listen=new DatePickerDialog.OnDateSetListener() { 

    @Override 
    public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) { 
     year=arg1; 
     month=arg2; 
     date=arg3; 
     UpdateDate();// TODO Auto-generated method stub 

    } 
}; 

public Dialog onCreateDialog(int id){ 

    switch(id){ 
    case TIME_DIALOG: 
     return new TimePickerDialog(this,time_listen,hour,min,false); 
    case DATE_DIALOG: 
     return new DatePickerDialog(this,date_listen,year,month,date); 
    } 

    return null; 

} 

@Override 
public void onClick(View arg0) { 
    switch(arg0.getId())// TODO Auto-generated method stub 
    { 
    case R.id.button1: 
     showDialog(TIME_DIALOG); 
     break; 
    case R.id.button2: 
     showDialog(DATE_DIALOG); 
     break; 
    case R.id.button3: 
     recipient=to.getText().toString(); 
     message2=(msg_body.getText().toString()); 
     contact=pick_no; 
     if(recipient.length()!=0&& message2.length()!=0) 
     { 

     Intent b_Intent=new Intent(); 
     b_Intent.setAction(AlarmService.ACTION);    
     b_Intent.putExtra("RQS", AlarmService.RQS_STOP_SERVICE); 

     Intent myIntent=new Intent(this,AlarmService.class); 
     myIntent.setAction(Intent.ACTION_SEND); 
     Bundle bundle=new Bundle(); 
     bundle.putString("sms_number", recipient); 
     bundle.putCharSequence("body", message2); 
     bundle.putString("contact_choose", contact);    
     myIntent.putExtras(bundle); 

     pi=PendingIntent.getService(this, 0, myIntent,0); 
     pn.add(PendingIntent.getBroadcast(this, 0, b_Intent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK)); 
     pn.add(pi); 
     AlarmManager alarm_manager=(AlarmManager)getSystemService(Context.ALARM_SERVICE); 
     calendar.setTimeInMillis(System.currentTimeMillis()); 
     calendar.set(Calendar.DAY_OF_MONTH, date); 
     calendar.set(Calendar.MONTH, month); 
     calendar.set(Calendar.YEAR, year); 
     calendar.set(Calendar.HOUR_OF_DAY, hour); 
     calendar.set(Calendar.MINUTE, min); 
     calendar.clear(); 
     alarm_manager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pi); 

     Toast.makeText(this, "your msg will be sending at "+hour+" hours and "+min+" min", Toast.LENGTH_LONG).show(); 

     break; 
    } 
     else{ 
      Toast.makeText(this, "fill both", Toast.LENGTH_LONG).show(); 
     } 

    case R.id.button4: 
     Intent intent=new Intent(Intent.ACTION_PICK); 
     intent.setType(ContactsContract.Contacts.CONTENT_TYPE); 
     intent.setData(android.provider.Contacts.People.CONTENT_URI); 
     startActivityForResult(intent,1); 
    } 
} 



    } 

МОЯ класс обслуживания:

 public class AlarmService extends Service{ 

     String To,message_body,pick; 
    NotifyServiceReceiver notifyServiceReceiver; 

    final static String ACTION = "NotifyServiceAction"; 
    final static String STOP_SERVICE = ""; 
    final static int RQS_STOP_SERVICE = 1; 


     private static final int MY_NOTIFICATION_ID=1; 
     private NotificationManager notificationManager; 
     private Notification myNotification; 

    SmsManager sms; 
@Override 
public IBinder onBind(Intent arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public void onCreate() { 
    // TODO Auto-generated method stub 
    super.onCreate(); 
    Toast.makeText(this, "Service created", Toast.LENGTH_LONG).show();  
    notifyServiceReceiver = new NotifyServiceReceiver(); 
} 

@Override 
public void onDestroy() { 
    // TODO Auto-generated method 
    super.onDestroy(); 
    Toast.makeText(getBaseContext(), "destroy", 
      Toast.LENGTH_SHORT).show(); 


} 

private void CancelService() { 
    // TODO Auto-generated method stub 

} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    // TODO Auto-generated method stub 

    IntentFilter intentFilter = new IntentFilter(); 
    intentFilter.addAction(ACTION); 
    registerReceiver(notifyServiceReceiver, intentFilter); 

    Bundle bundle=intent.getExtras(); 
    Toast.makeText(this, "service Started", Toast.LENGTH_LONG).show(); 

    String SENT = "SMS_SENT"; 
    String DELIVERED = "SMS_DELIVERED"; 

    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, 
     new Intent(SENT), 0); 

    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, 
     new Intent(DELIVERED), 0); 

    //---when the SMS has been sent--- 
    registerReceiver(new BroadcastReceiver(){ 
     @Override 
     public void onReceive(Context arg0, Intent arg1) { 
      switch (getResultCode()) 
      { 
       case Activity.RESULT_OK: 
        Toast.makeText(getBaseContext(), "SMS sent", 
          Toast.LENGTH_SHORT).show(); 


        break; 
       case SmsManager.RESULT_ERROR_GENERIC_FAILURE: 
        Toast.makeText(getBaseContext(), "Generic failure", 
          Toast.LENGTH_SHORT).show(); 
        break; 
       case SmsManager.RESULT_ERROR_NO_SERVICE: 
        Toast.makeText(getBaseContext(), "No service", 
          Toast.LENGTH_SHORT).show(); 
        break; 
       case SmsManager.RESULT_ERROR_NULL_PDU: 
        Toast.makeText(getBaseContext(), "Null PDU", 
          Toast.LENGTH_SHORT).show(); 
        break; 
       case SmsManager.RESULT_ERROR_RADIO_OFF: 
        Toast.makeText(getBaseContext(), "Radio off", 
          Toast.LENGTH_SHORT).show(); 
        break; 
      } 
     } 
    }, new IntentFilter(SENT)); 


    registerReceiver(new BroadcastReceiver(){ 
     @Override 
     public void onReceive(Context arg0, Intent arg1) { 
      switch (getResultCode()) 
      { 
       case Activity.RESULT_OK: 
        Toast.makeText(getBaseContext(), "SMS delivered", 
          Toast.LENGTH_SHORT).show(); 
        break; 
       case Activity.RESULT_CANCELED: 
        Toast.makeText(getBaseContext(), "SMS not delivered", 
          Toast.LENGTH_SHORT).show(); 
        break;       
      } 
     } 
    }, new IntentFilter(DELIVERED)); 
    sms = SmsManager.getDefault(); 
    sms.sendTextMessage(bundle.getString("sms_number"), null,(String) bundle.getCharSequence("body") , sentPI, deliveredPI); 


    notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
    myNotification = new Notification(R.drawable.ic_launcher, "Notification!",System.currentTimeMillis()); 
    Context context = getApplicationContext(); 
    String notificationTitle = "Exercise of Notification!"; 
    String notificationText = "Message Notification"; 
    PendingIntent myIntent1 = PendingIntent.getActivity(context, 0, new Intent(Intent.ACTION_VIEW, People.CONTENT_URI), 0); 
    myNotification.defaults |= Notification.DEFAULT_SOUND; 
    myNotification.flags |= Notification.FLAG_AUTO_CANCEL; 
    myNotification.setLatestEventInfo(context,notificationTitle,notificationText, myIntent1); 
    notificationManager.notify(MY_NOTIFICATION_ID, myNotification); 
    Toast.makeText(this, "your msg will be sending at ", Toast.LENGTH_LONG).show(); 
    return START_STICKY; 
} 

@Override 
public boolean onUnbind(Intent intent) { 
    // TODO Auto-generated method stub 
    return super.onUnbind(intent); 
} 

public class NotifyServiceReceiver extends BroadcastReceiver{ 

    @Override 
    public void onReceive(Context arg0, Intent arg1) { 
     // TODO Auto-generated method stub 
     int rqs = arg1.getIntExtra("RQS", 0); 
     if (rqs == RQS_STOP_SERVICE){ 
      stopSelf(); 
     } 
    } 

} 
    } 

ответ

0

Причина, почему он не отправляет на номер, изменить его или правильное тело письма, потому что вы извлекаете только «sms_number»

sms.sendTextMessage(bundle.getString("sms_number"), null,(String) bundle.getCharSequence("body") , sentPI, deliveredPI); 

Как вы видите, вы только получаете «sms_number» из расслоения. Вы не получаете контактный номер, когда вы вставляете пакет в свою деятельность.

Вы должны изменить свой код на что-то подобное в своем классе, который отправляет сообщение.

String contactPicked = bundled.getString("contact_picked"); 
String recipientEntered = bundle.getString("sms_number"); 

Тогда вы могли бы сделать проверку, чтобы увидеть, если либо равно нулю или Не должно содержимое, а затем поставить его в метод отправки сообщений, как это ..

sms.sendTextMessage(contactPicked, null,(String) bundle.getCharSequence("body") , sentPI, deliveredPI); // or recipient depending which you need to use. 
+0

я удалить случай R.id. button4: line ... Теперь я вводил номер получателя вручную .. не переключился на контактный переключатель. моя проблема, когда я ввожу новый номер с другим текстом ... но сообщение идет на первый введенный номер с первым текстовым сообщением не новый ... – DineshKumar

+0

Вы вводите новый номер в тот же редактор? Он должен быть получателем = to.getText(). ToString(); верно. –

+0

да я набираю число в том же editText ... – DineshKumar

Смежные вопросы