SKB
SKB

Reputation: 137

How do I use time picker?

I am using time picker for my app which sends sms based on a particular time in future. I have the sms sending part ready using sms manager. I also have the user time using getCurrentHour() and getCurrentMinute(). This is my code

 if(phoneNo.length()>0&&message.length()>0)
    {
     sendSMS(phoneNo,message);
    }
      else        
      {
       Toast myToast=Toast.makeText(getBaseContext(),"Please enter both phone number and message.",Toast.LENGTH_SHORT);
       myToast.show();
        }
      }
  });
}

How do I proceed to send the sms at a particular time?

Upvotes: 0

Views: 524

Answers (1)

Mark Allison
Mark Allison

Reputation: 21924

You'll need to move your sendSms() method in to a Service, and then use AlamManager to cause your Service to be woken at the correct time, and send your SMS.

You will need to define your Service:

class SmsService extends IntentService
{
    @override
    void onStartCommand( Intent intent, int flags, int startId )
    {
        String number = intent.getStringExtra( "number" );
        String message = intent.getStringExtra( "message" );

        // Send your SMS here
    }
}

You'll need declare this service in your manifest:

<service android:name=".SmsService">
    <intent-filter>
        <action android:name="mypackage.SEND_SMS" />
    </intent-filter>
</service>

Finally you'll need to set the alarm which will wake up at the given time and send your message:

AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent= new Intent( "mypackage.SEND_SMS" );
intent.setExtra( "number", number );
intent.setExtra( "message", message );
PendingIntent pi = PendingIntent.startService( this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT );
mgr.set( AlarmManager.RTC_WAKEUP, time, pi );

This will need to be called from within an Activity or Service which has either extends or has access to a Context.

Upvotes: 1

Related Questions