stop service after execution - android

Hi I am writing program which fetches users current lattitude and longitude every 5 minutes using Alarmmanager and store the value in shared preferences.I want to run this search backgroun so iam using service.I want to stop the service after fetching the lattitude and longitude to avoid battery drain.This is my code
CurrentLocation.java
import com.google.android.gms.maps.model.LatLng;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
public class CurrentLocation extends Service implements LocationListener {
private Context mcontext;
SharedPreferences shprefs;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
this.mcontext=this;
getlocation();
}
private void getlocation() {
// TODO Auto-generated method stub
Log.i("evvterer", "mnbj");
LocationManager locationManager = (LocationManager) mcontext.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
shprefs=PreferenceManager.getDefaultSharedPreferences(CurrentLocation.this);
double latitude=location.getLatitude();
Editor edit=shprefs.edit();
edit.putString("Ltd", ""+latitude);
edit.commit();
double longitude=location.getLongitude();
Editor edits=shprefs.edit();
edits.putString("Lngtd", ""+longitude);
edits.commit();
LatLng loca=new LatLng(latitude,longitude);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
please help me
Thanks in advance

use Broadcast receiver instead of service because broadcast receiver intent trigger when your condition meet so use broadcast for fetches users current latitude and longitude every 5 minutes.:) from broadcast receiver your battery is not reduce very much as service do

As you use returning null from onBind, you may be using startService() to start your CurrentLocation service.
So when you are done with your CurrentLocation service, simpally call stopService (Intent service)
But if you have used bindService then you have to use unBindService().
To stop service at exact time, you can call a method in your activity at end of onLocationChanged() and from that method stop the service.
Or send a message to handler associated with your Activity to stop the service.
And add your code to start the service, so that it will help others to answer your question.

Related

Stop a location listener activity when the user presses the back button, or when a new intent is made

This app will beep whenever the user's location changes. The problem is, the app will continue monitoring the user's location even after they have left the app and it is in the background.
How do I stop the location listener, once the app goes into the background?
I think I have to add something to the OnPause(), but I can't make it work.
package com.example.locationbeeper;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements LocationListener {
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set up location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 200, 5, this); // time in miliseconds, distance in meters (Distance drains battry life) originally set to 20000 and 0
}
#Override
public void onLocationChanged(Location location) {
// beep when location changed
final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
tg.startTone(ToneGenerator.TONE_PROP_BEEP);
}
#Override
public void onSaveInstanceState(Bundle outState) {
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onPause(){
super.onPause();
locationManager = null;
}
}
Based on your requirement, you can add below lines either in onPause() or onStop() callback method of your activity.
if(locationManager !=null)
locationManager.removeUpdates(this);
Use LocationManager.removeUpdates to stop receiving updates from LocationManager when Activity is stop:
#Override
public void onStop(){
super.onStop();
if(locationManager !=null)
locationManager.removeUpdates(this);
}

Android - Update Location every x minutes

I'm pretty new to android, and this is my first post here, so please be kind! :-)
I'm trying to create a service which runs in the background and does a location update every x minutes. To run it every x minutes I'm using the AlarmManager, as described here: Alarm Manager Example
Here's what I've got:
package com.example.service1;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
public class Scheduler extends BroadcastReceiver{
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
//Code which is executed every X seconds/minutes
getLocation(context);
//End of Code
wl.release();
}
public void setScheduler(Context context) {
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Scheduler.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 20, pi);
}
//Method to get the Location
public void getLocation(Context context) {
Log.e("null","getLocation");
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e(null, "location change");
makeUseOfLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
};
}
//Method to work with the location Data; Instance of Point is created
public void makeUseOfLocation(Location location) {
Log.e(null,"makeuse");
Log.e(null,location.getLatitude() + "");
}
}
getLocation() is called every 20 seconds, but then it never runs onLocationChanged() (I use the EmulatorControl in Eclipse to change the location).
I had the same problem before when I used the ScheduledExecutorService instead of the AlarmManager.
Can anyone help me?
Looking at your code I never see the call to locationManager.requestLocationUpdates() with your listener as an argument.
This means that your listener is never registered with the location manager, and therefore does not get called.
You probably only want to register one listener, instead of registering a new one every time.
Try this..
protected void updateNotification() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, normallocationwait, 0.250f, locationListener);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
private class MyLocationlistener implements LocationListener {
public void onLocationChanged(Location location){
if(location!=null){
if(location.hasAccuracy()){
dumpLocation(location);
}else{
dumpLocation(location);
}
}
}
public void onProviderDisabled(String provider){
Log.v("Loc Update","\nProvider disabled: " + provider);
}
public void onProviderEnabled(String provider){
Log.v("Loc Update","\nProvider enabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras){
Log.v("Loc Update","\nProvider status changed: " + provider + ", status="
+ status + ", extras=" + extras);
}

in gsp even I change latitude and longitude emuletar still show the same location why it reacts like that? and how I correct it?

this my code and it loade normali but when I change latitude and longitude it not show the corresponding location. I use emulatar to test the programe. I change latitude and longitude by using emulator control.
package com.rumes.gspuse;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class Main extends MapActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapView map=(MapView) findViewById(R.id.map);
map.setBuiltInZoomControls(true);
final MapController controller=map.getController();
LocationManager manager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listner=new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
controller.setCenter(new GeoPoint((int)location.getLatitude(), (int)location.getLongitude()));
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,listner);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
You need latitudeE6 and longitudeE6, that's why you don't see any difference in map!
if(location != null) // avoid crash (check for null)..
controller.setCenter(new GeoPoint((int)(location.getLatitude() * 1E6), (int)(location.getLongitude() * 1E6)));

Finding current location from background service android

I want to find current location and compare it with some data in my database through a background service activity...but not getting any idea on how to do it...so please give me some advice...this is how I am doing currently
package com.example.alert;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service{
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
Toast.makeText(this, "Background Service Created", Toast.LENGTH_LONG).show();
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
}
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
LocationListener ll = new MyLocationListener();
//lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5*60*10000, 0, ll);
lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll);
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
if(loc!=null)
{
double x;
String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
/* cr.moveToFirst();
while(!cr.isAfterLast()) {
al.add(cr.getString(cr.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
cr.moveToNext();
}*/
// lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 10009,, intent)
//for loop, alerters retrieving one by one
// x= calcDistance(loc.getLatitude(),loc.getLongitude(),z,y);
// if(x<1){
// Intent myIntent = new Intent(ViewAlerters.this,CallMode.class);
// startActivity(myIntent);
}
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Reto Meier (Android Developer Relations) did a whole lot of work in this area, I suggest you check it out.
Blogged here http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
Sample code here https://code.google.com/p/android-protips-location/

Service does not work?

I had service that run by BrodcastReceiver which suppose to run and give me the GPS data that I requested and I stopped it after I did what suppose to be done, but I notice that It did not provide me with the data that requested and did not stop too , any body can help me in figuring out my problem
the code is below and the service tested in real device:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.widget.Toast;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class GpsService extends Service implements LocationListener{
static LocationManager mlocManager;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
mlocManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,0, 0,this);
}
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
// Here to stop the service and make it finish its task
SystemClock.sleep(40000);
// stop the Gps system by this application
mlocManager.removeUpdates(this);
//Here to stop the service by itself
stopSelf();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
do you have the correct permissions on the manifest?
why do you make the service sleep and for so long? the service works on the UI thread , and such a thing can cause the service to be killed automatically by the system after about 5 seconds because the ui thread doesn't respond.
if you wish to delay the stopping and/or showing of the toast , either use Handler (and postDelayed) , or use asyncTask , or something of your own .
do you have the gps turned on? have you considered using a fake location app or the emulator for this task ?
good luck .

Categories

Resources