Reputation: 281
I'm still new to android. I call the onDestroy method using stopService. The onDestroy method is called as I can see the toast message. But the infinite for loop used to send location updates keeps running. Is there something I need to change?
public class myservice extends IntentService {
LocationManager locationManager ;
public myservice() {
super(myservice.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
String numb=intent.getStringExtra("num");
for (;;) {
send(numb);
}
}
public IBinder onBind(Intent intent) {
return null;
}
public void send(String numb) {
locationManager = (LocationManager)this
.getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) {}
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Geocoder geocoder;
geocoder = new Geocoder(this, Locale.getDefault());
try {
Thread.sleep(3000);
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
Toast toast1 = Toast.makeText(this, "message sent", Toast.LENGTH_SHORT);
toast1.setText(numb.toString());
toast1.show();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(numb, null, "current postition is" + addresses.get(0).getAddressLine(0) + "," + addresses.get(0).getAddressLine(1) + "," + addresses.get(0).getAddressLine(2), null, null);
Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
@Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "DESTROY2", Toast.LENGTH_LONG).show();
super.stopSelf();
super.onDestroy();
}
}
Upvotes: 3
Views: 1141
Reputation: 317402
You don't call onDestroy()
yourself. Never call lifecycle methods on your own. Android will call them when the service is stopped.
Subclassing IntentService isn't really the best thing to do to manage ongoing work. It would be better for you to manage a thread on your own and manage the start and stop commands that are delivered to that service. It's not exactly easy work.
http://developer.android.com/guide/components/services.html
Upvotes: 5