Reputation: 13
I tried developing an Android app for SMS Scheduling using AlarmManager and a Background Service.Here is the code snippet:(after getting user input)
Bundle b=getIntent().getExtras() ;
String s1,s2,s3,s4 ;
s1=b.getString("time") ;
s2=b.getString("target") ;
s3=b.getString("text") ;
s4=b.getString("date") ;
t1.setText(s1) ;
t2.setText(s2) ;
t3.setText(s3) ;
Calendar cal=Calendar.getInstance() ;
Intent intent=new Intent(SecondActivity.this,SmsSrevice.class) ;
intent.putExtra("date",s4) ;
intent.putExtra("time",s1) ;
intent.putExtra("num",s2) ;
intent.putExtra("message",s3) ;
this.startService(intent);
PendingIntent pindent=PendingIntent.getService(SecondActivity.this,0, intent,0) ;
AlarmManager am=(AlarmManager)getSystemService(Context.ALARM_SERVICE) ;
am.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),1000,pindent) ;
And this is the service code snippet:
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId) ;
Calendar cal=Calendar.getInstance() ;
String cdate, ctime ;
SimpleDateFormat sf=new SimpleDateFormat("d-M-yyyy") ;
SimpleDateFormat sd=new SimpleDateFormat("H:m") ;
cdate=sf.format(cal.getTime()) ;
ctime=sd.format(cal.getTime()) ;
Bundle b ;
b=intent.getExtras() ;
String m1=b.getString("date") ;
String m2=b.getString("time") ;
String m3=b.getString("num") ;
String m4=b.getString("message") ;
if(m1.equals(cdate) && m2.equals(ctime) && f!=1)
{ SmsManager sms=SmsManager.getDefault() ;
sms.sendTextMessage(m3,null,m4,null,null) ;
Toast.makeText(this,"Message sent",Toast.LENGTH_LONG).show() ;
//super.onDestroy();
m2="done" ;
}
else
{
q=1 ;
//f=2 ;
}
return 0 ;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
ActivityManager ama=(ActivityManager)getSystemService(ACTIVITY_SERVICE) ;
}
I cannot stop the service...it keeps on sending SMSs from the given time..Any ideas please??I m new to android development....Thanks in advance...
Upvotes: 1
Views: 2158
Reputation: 9996
Call stopself
from the Service
after work of Service
is done:
sms.sendTextMessage(m3,null,m4,null,null) ;
stopself();
See here for more details.
Upvotes: 0
Reputation: 536
I think you want to stop your service which is running in background.
To stop the running background service
Intent svc = new Intent(MainActivity.this , BackGroundActivity.class);
stopService(svc);
Here BackGroundActivity is the activity running in the background.
MainActivity is the activity from where BackGroungActivity is running.
Hope this helps..!!
Upvotes: 1