I am using a Service for fetching Coordinates from GPS as well as from Network
I am Using Alarm Manager to activate the Service every 2 Minute like
Intent myIntent=new Intent(Main.this,ServiceNew.class);
PendingIntent pendingIntent=PendingIntent.getService(OkayaMain.this,0,myIntent,0);
AlarmManager alarmManager=(AlarmManager)getSystemService(ALARM_SERVICE);
Calendar cal=Calendar.getInstance();
cal.add(Calendar.MINUTE,0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),UPDATE_INTERVAL,pendingIntent);
It activates every 2 min But after some time it kill or OS Make it to kill ,
I Dont Want to use Foreground Services
my ServiceClass is ServiceNew.class
public class ServiceNew extends Service
{
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
dLat=location.getLatitude();
dLng=location.getLongitude();
sCoordinateType=location.getProvider();
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
fnPushLocation();
}
private void fnPushLocation(){
try{
context=getApplicationContext();
timer1=new Timer();
checkTime=new TimerTask(){
public void run(){
if(lIteration>=1){
if(timer1!=null){
timer1.cancel();
timer1=null;
}
SaveLocation();
}
lIteration++;
}
};
timer1.schedule(checkTime,0,UPDATE_INTERVAL);
}
catch(Exception ex){
sResponse=ex.toString();
//fnShowMessage(sResponse);
return;
}
}
it get me the coordinates after some time android kill the application , how can i handle this in a proper manner
so as it clear the RAM and activate my application again
I dont want application to be killed , do we have any solution for this
Please Help ,Thanks in advance
public void killSelf(Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(Activity.ACTIVITY_SERVICE);
am.killBackgroundProcesses(getPackageName());
if (mServiceList != null) {
for (RunningServiceInfo service : mServiceList) {
context.stopService(new Intent().setComponent(service.service));
}
}
}
please follow below link for reference.I hope its useful for you..
http://code.google.com/p/my-test-project-lion/
Related
I have a service that runs in both foreground and background to get the user location at all times, I simply use a LocalBroadCastManager to send the location from the foreground to an activity in my application and then start my API call.
How to achieve the same when the service is running in the background or when the application is closed.
The service:
public class LocationService extends Service {
private static final String TAG = "LocationService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 1000f;
private HandlerThread mHandlerThread;
private Handler mHandler;
private final IBinder mBinder = new MyLocalBinder();
Location mLastLocation;
private class LocationListener implements android.location.LocationListener
{
public LocationListener(String provider)
{
Helper.showLog(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Helper.showLog(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
sendBroadcast();
}
#Override
public void onProviderDisabled(String provider)
{
Helper.showLog(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Helper.showLog(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Helper.showLog(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
mHandlerThread = new HandlerThread("LocalServiceThread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
sendBroadcast();
}
public void postRunnable(Runnable runnable) {
mHandler.post(runnable);
}
public class MyLocalBinder extends Binder {
public LocationService getService() {
return LocationService.this;
}
}
#Override
public void onDestroy()
{
Helper.showLog(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listeners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Helper.showLog(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private void sendBroadcast(){
Intent intent = new Intent ("message"); //put the same message as in the filter you used in the activity when registering the receiver
intent.putExtra("latitude",mLastLocation.getLatitude() );
intent.putExtra("longitude",mLastLocation.getLongitude() );
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
I am creating app which updates the location in background using service. Now it is done by gps and network provider both. But I want to get last location using network provider only because gps consumes lot of battery. I got code online which I modified is as below
public class MyLocationServiceOne extends Service {
private static final String TAG = "MyLocationService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;//MIN_TIME_BW_UPDATES 1 Minute
private static final float LOCATION_DISTANCE = 0f;//MIN_DISTANCE_CHANGE_FOR_UPDATES
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
Log.e(TAG, "Location : " + location.getLatitude()+" , "+
location.getLongitude());
mLastLocation.set(location);
double lati=location.getLatitude();
double longi=location.getLongitude();
if(String.valueOf(lati)!=null&&String.valueOf(longi)!=null) {
Toast.makeText(MyLocationServiceOne.this, String.valueOf(lati)+String.valueOf(longi), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
//new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
//buildAlertMessageNoGps();
}
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
/*try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}*/
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
But it gives gps coordinates only when gps is on.
Thanks for any help
Getting location through gps is painful to user since it consumes a lot of battery as you indicated above. You can select your provider too, that is what is source of getting location, is it network or it is gps. These all depends on your location needs and some other logics of app. well to cut short it, I must say you need to learn location strategies. This will give you better understanding. Please look this here.
I will recommend you to use google's fused location API. This give you better control on locations, and the best part of this API is that it is battery efficient and it is really fast and reliable. here is a link if you want to learn about it. and for some more code snippts and helping material see this, this and this one is so advance also if you are using kotlin it has its demo code.
Ask if there is any confusion.
this code is work with me to take the coordination even if the application is not in use but when i switch of my phone then open my phone again it is not working in the background i need it continue working in the background. even if the user mobile pone is switched off and then it is opened again
public class Check2 extends Service
{
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
}
private static final String TAG = "GPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000*6;
private static final float LOCATION_DISTANCE = 0f;
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
double lat = mLastLocation.getLatitude();;
double lon = mLastLocation.getLongitude();
Toast.makeText(getApplicationContext(), "Lat: "+lat+" Long: "+lon, Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
LocationManager loc;
loc=(LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener listener =new LocationListener(TAG);
Location location ;
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
// location = listener.mLastLocation;
location= loc.getLastKnownLocation(LocationManager.GPS_PROVIDER);
listener.onLocationChanged(location);
Log.d("is work","here");
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
location= loc.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
listener.onLocationChanged(location);
Log.d("is work", "here");
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
Create a Broadcast receiver to listen for Boot Complete event
Check this link for tutorials
Broadcast receiver for Boot Action
1 to Vivek, but also you should start your service in another process from your application. For example,
<< service
android:name=".TweetCollectorService"
android:process=":remote">
Then in your service you should add BroadcastReceiver to receive intent BOOT_COMPLETE. If you want this service to keep running no matter what, consider replacind startService method with startForeground
I had developed a real-time GPS location tracking system in which the mobile devices integrated with GPS device send location information to web server obtained at database and it is being plotted in Google map by calling the function to plot GPS data in map periodically as function is called repeatedly over specific time interval.
On the user end we can watch the location update like the plotters blinking and changing the location in Google map.
Is there any other best method to show real-time GPS location on Google map?
Any method to make the plotters move without blinking, like continuously flowing through map?
Any piece of code is appreciated & thanks in advance.
I suggest you to store the location history in database, make it short duration and lets call it Location Frame. Now you have a from and to coordinate positions to move your plotters in the map. update the frame by setting a frequency in which the new frame can be applied when plotter have approached the destination of last frame. Build pragram on this logic. hope it helped :)
I implemented this code into a service and it only get the cordinates... they are never rendered into any map....
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
sLat = Double.toString(location.getLatitude());
sLong = Double.toString(location.getLongitude());
Speed = Double.toString(location.getSpeed());
sAlt = Double.toString(location.getAltitude());
sTime = Double.toString(location.getTime());
Log.e(TAG, "onLocationChanged: " + location + localTime);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
TelephonyManager mngr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
IMEI = mngr.getDeviceId();
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
I am newbie. I wrote a class, that implements service and uses gps, but location allways null. All needed permissions are wrote and service is normally starting, i could bind to it, but retrieved location is allways null and it never goes in onLocationChanged(Location location). Can anybody help, please?
public class GPSService extends Service {
private static final String TAG = "GPS_SERVICE";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
Location currentLocation;
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
if (location != null){
mLastLocation.set(location);
currentLocation = mLastLocation;
}
}
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
private IBinder mBinder = new GPSServiceBinder();
public class GPSServiceBinder extends Binder {
public GPSService getServerInstance() {
return GPSService.this;
}
}
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
public IBinder onBind(Intent intent) {
return mBinder;
}
int minTime = 6000;
float minDistance = 15;
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
public Location getLocation()
{
return currentLocation;
}
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
If you're using emulator with 2.3 version of Android then there is a bug. I've just recently faced with it. You can install 2.3 x86 emulator in this case. It works fine.