2013-09-15 3 views
-1

//ScheduleActivity.java//
package com.example.sked;Плановые sms не работают (код прилагается)

импорт java.util.Calendar;

импорт java.util.concurrent.TimeUnit;

импорт android.app.Activity;

импорт android.app.AlarmManager;

импорт android.app.AlertDialog;

импорт android.app.PendingIntent;

импорт android.content.Intent;

импорт android.os.Bundle;

импорт android.view.Menu;

импорт android.view.View;

импорт android.widget.Button;

импорт android.widget.DatePicker;

импорт android.widget.EditText;

импорт android.widget.TimePicker;

импорт android.widget.Toast;

общественный класс ScheduleActivity extends Деятельность { private PendingIntent pendingIntent;

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    setContentView(R.layout.activity_schedule); 
    super.onCreate(savedInstanceState); 

    Calendar cal=Calendar.getInstance(); 

    final int year_set=cal.get(Calendar.YEAR); 
    final int month_set=cal.get(Calendar.MONTH); 
    final int day_set=cal.get(Calendar.DAY_OF_MONTH); 

    final int hr_set=cal.get(Calendar.HOUR); 
    final int min_set=cal.get(Calendar.MINUTE); 

    final DatePicker dp_c = (DatePicker) findViewById(R.id.datePicker1); 
    final TimePicker tp_c = (TimePicker) findViewById(R.id.timePicker1); 

    dp_c.updateDate(year_set, month_set, day_set); //Setting current date in date picker // 

    tp_c.setCurrentHour(hr_set); //Setting current time in time picker // 
    tp_c.setCurrentMinute(min_set); 


    //For Scheduling a message// 
    final Button view = (Button) findViewById(R.id.set_message); 
    { 
    view.setOnClickListener(new View.OnClickListener() 
    { 

    @Override 
    public void onClick(View v) 
    { 


     // Processing the input values from the user// 
     EditText text = (EditText)findViewById(R.id.reci_number); 
     final String phno= text .getText().toString(); 

     EditText text1 = (EditText)findViewById(R.id.message); 
     final String msg= text1.getText().toString(); 

     if(phno.length()==10)//Checking length of the mobile number// 
     { 
     if(msg.length()<=160 && msg.length()>0) //Checking length of the message// 
     { 


     DatePicker dp = (DatePicker) findViewById(R.id.datePicker1);//Getting selected date values// 
     int day = dp.getDayOfMonth(); 
     int month = dp.getMonth() + 1; 
     int year = dp.getYear(); 

     TimePicker tp=(TimePicker) findViewById(R.id.timePicker1);//Getting selected time values// 
     int hours= tp.getCurrentHour(); 
     int minutes= tp.getCurrentMinute(); 


     Calendar cal=Calendar.getInstance();//Getting Current date values// 

     final int year_curr=cal.get(Calendar.YEAR); 
     final int month_curr=cal.get(Calendar.MONTH); 
     int day_curr=cal.get(Calendar.DAY_OF_MONTH); 

     final int hr_curr=cal.get(Calendar.HOUR);//Getting Current time values// 
     final int min_curr=cal.get(Calendar.MINUTE); 

     int year_act=year-year_curr; 
     int mon_act=month-month_curr; 
     int day_act=day-day_curr; 
     int hr_act=hours-hr_curr; 
     int min_act=minutes-min_curr; 

     int diff=year_act+mon_act+day_act+hr_act+min_act; 

      if (diff>=0)//Checking if its the future date// 
      { 


       Intent myIntent = new Intent(ScheduleActivity.this, MyAlarmService.class); 

       Bundle bundle = new Bundle(); 
       bundle.putCharSequence("extraSmsNumber", phno); 
       bundle.putCharSequence("extraSmsText", msg); 
       myIntent.putExtras(bundle); 

       pendingIntent = PendingIntent.getService(ScheduleActivity.this, 0, myIntent, 0);//Sending intent to Alarm class// 


      int year_act_indays=year_act*365; 
      long year_act_mil=TimeUnit.MILLISECONDS.convert(year_act_indays, TimeUnit.DAYS); 


      int mon_act_indays=mon_act*30; 
      long mon_act_mil=TimeUnit.MILLISECONDS.convert(mon_act_indays, TimeUnit.DAYS); 


      long day_act_mil=TimeUnit.MILLISECONDS.convert(day_act, TimeUnit.DAYS); 


      long hr_act_mil=TimeUnit.MILLISECONDS.convert(hr_act, TimeUnit.HOURS); 


      long min_act_mil=TimeUnit.MILLISECONDS.convert(min_act, TimeUnit.MINUTES); 


      long elapsedtimer_act= year_act_mil+mon_act_mil+day_act_mil+hr_act_mil+min_act_mil; 

      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
      alarmManager.set(AlarmManager.RTC_WAKEUP,elapsedtimer_act, pendingIntent); 

      final AlertDialog.Builder dlgAlert = new AlertDialog.Builder(ScheduleActivity.this, 0); 

      //set the dialog 
      dlgAlert.setMessage("Message successfully scheduled at the specified time & date"); 
      dlgAlert.setTitle("Success"); 
      dlgAlert.setPositiveButton("OK", null); 
      dlgAlert.setCancelable(true); 
      dlgAlert.create().show(); 

      //Reseting the fields// 
      EditText text_r = (EditText)findViewById(R.id.reci_number); 
      ((EditText)text_r).setText(""); 

      EditText text_m = (EditText)findViewById(R.id.message); 
      ((EditText)text_m).setText(""); 

      } 
      else 
      { 
       Toast.makeText(getBaseContext(), 
         "Please check the entered date...And enter future time. ",Toast.LENGTH_SHORT).show(); 
      } 

     } 

     else 
     { 

      Toast.makeText(getBaseContext(), 
      "Message too long or too short .... cannot send ... :(",Toast.LENGTH_SHORT).show(); 
     } 
     } 
     else 
     { 

      Toast.makeText(getBaseContext(), 
       "Check the number Entered",Toast.LENGTH_SHORT).show(); 
     } 
     } 


    } 

    ); 



    } 



} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) 
{ 
    // Inflate the menu; this adds items to the action bar if it is present. 

    getMenuInflater().inflate(R.menu.schedule, menu); 


    // menu.add("Reset"); 

    return true; 
} 

}

//MyAlarmService.java//

package com.example.sked; 

импорт android.app.Service;

импорт android.content.Intent;

импорт android.os.Bundle;

импорт android.os.IBinder;

импорт android.telephony.SmsManager;

общественного класса MyAlarmService расширяет Услуги {

String smsNumberToSend, smsTextToSend; 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 

    return null; 
} 

@SuppressWarnings("deprecation") 
@Override 
public void onStart(Intent intent, int startId) { 
    // TODO Auto-generated method stub 
    super.onStart(intent, startId); 

    Bundle bundle = intent.getExtras(); 
    smsNumberToSend = (String) bundle.getCharSequence("extraSmsNumber"); 
    smsTextToSend = (String) bundle.getCharSequence("extraSmsText"); 

    SmsManager smsManager = SmsManager.getDefault(); 
    smsManager.sendTextMessage(smsNumberToSend, null, smsTextToSend, null, null); 
} 

}

ответ

0

Вы должны использовать BroadcastReceiver планировать события с AlarmManager. Расширьте BroadcastReceiver и переопределите метод onReceive(), тогда ваше устройство пробудится в течение времени, необходимого для завершения этого метода. Это позволит вам отправлять SMS-сообщения или запускать сервис.

class MyReceiver extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(final Context context, final Intent intent) { 
     //YOUR CODE HERE 
    } 
} 

Обратите внимание, что Wakelock, который держит устройство активно будет продолжаться только в течение всего OnReceive метода, так что если вы начинаете услугу или деятельность, они не могут выполнить весь код до того, как устройство возвращается в режим сна.

В этом случае ожидающий запрос должен быть создан с использованием «getBroadcast» вместо «getService».

+0

Я сделал изменения и сказал .. но сообщение не отправляется .. пожалуйста, помогите ... и разрешения SMS также установлены. –

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