I'm trying to make a service that inserts the location of a device in a database and when the device is outside of a list of geofences it sends another message to the server. Right now I only have the part where the service sends the location to the server.
Here's what I have:
public class UbicacionEmisor extends Service {
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 10000;
private static final float LOCATION_DISTANCE = 0;
private SOService mService;
SharedPreferences preferences;
SharedPreferences.Editor editor;
private static final String PREF_NAME = "decaught-preferences";
private List<GeofenceR> geofenceRList = new ArrayList<>();
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);
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String date = f.format(new Date());
editor.putString("latitude", String.valueOf(location.getLatitude()));
editor.putString("longitude", String.valueOf(location.getLongitude()));
editor.apply();
//This part is used to send to the server the Location
mService.add_location("Token " + preferences.getString("token", ""), preferences.getString("imei",""), date, String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()), true).enqueue(new Callback<escoladeltreball.org.decaught.models.Location>() {
#Override
public void onResponse(Call<escoladeltreball.org.decaught.models.Location> call, Response<escoladeltreball.org.decaught.models.Location> response) {
if (response.isSuccessful()) {
Log.d("UbicationEmisor", "Ubication send");
} else {
int statusCode = response.code();
if (response.code() == 400) {
try {
Log.v("Error code 400", response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d("UbicationEmisor", "Ubication not send, error: " + statusCode);
Log.d("UbicationEmisor", "Ubication not send, error: " + response.errorBody());
// handle request errors depending on status code
}
}
#Override
public void onFailure(Call<escoladeltreball.org.decaught.models.Location> call, Throwable t) {
Log.d("RolSelectionActivity", "Error trying to connect to database");
}
});
}
#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);
preferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
editor = preferences.edit();
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
mService = ApiUtils.getSOService();
obtainGeofences();
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());
}
}
private void obtainGeofences() {
String imei = preferences.getString("imei","");
mService.listGeofence("Token " + preferences.getString("token", ""), imei).enqueue(new Callback<List<GeofenceR>>() {
#Override
public void onResponse(Call<List<GeofenceR>> call, Response<List<GeofenceR>> response) {
geofenceRList = response.body();
}
#Override
public void onFailure(Call<List<GeofenceR>> call, Throwable t) {
}
});
}
#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);
}
}
}
Any idea how to make the Geofence part? Or should I start over?
I've worked with Geofences, I really suggest you to read this Geofence Documentation and this example
Regarding your question, I'd suggest you start over again because geofences don't use LocationManager (or at least not explicitly).
You want to do something like (step list):
Define Geofence lng/lat and radius and assign exit event
mGeofenceList.add(new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId(entry.getKey())
.setCircularRegion(
entry.getValue().latitude,
entry.getValue().longitude,
Constants.GEOFENCE_RADIUS_IN_METERS
)
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
.build());
Define pending intent
public class MainActivity extends AppCompatActivity {
// ...
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
mGeofencePendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
return mGeofencePendingIntent;
}
**Define the Service**
public class GeofenceTransitionsIntentService extends IntentService {
// ...
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = GeofenceErrorMessages.getErrorString(this,
geofencingEvent.getErrorCode());
Log.e(TAG, errorMessage);
return;
}
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
// Test that the reported transition was of interest.
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
// Get the geofences that were triggered. A single event can trigger
// multiple geofences.
// HERE YOUR CODE TO SAVE THE LOCATION IN THE DB
// AND SEND THE NOTIFICATION
sendNotification(geofenceTransitionDetails);
Log.i(TAG, geofenceTransitionDetails);
} else {
// Log the error.
Log.e(TAG, getString(R.string.geofence_transition_invalid_type,
geofenceTransition));
}
}
NB
The most annoying thing of working with Geofences is Doze.
After a while you won't see anymore any notification because Doze stop it in order to save battery, so bear that in mind.
Make sure to read this before you start DOZE.
Enjoy =)
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);
}
}
It kills the service when app is killed. Is there any way to keep the service running on backgroud after the app killed for the android nougat.
Please find the below code:
it's running well for marshmellow.
package com.example.espl.pluzpluz.locationService;
import static android.support.v4.app.NotificationCompat.PRIORITY_MAX;
public class MyService extends Service
{
static final int NOTIFICATION_ID = 543;
public static boolean isServiceRunning = false;
SharedPreferences sharedPref;
JSONArray jsonArray;
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE =0 ;
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);
sharedPref = getApplicationContext().getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
String jsonString = sharedPref.getString(getString(R.string.jsonString),"");
try {
jsonArray=new JSONArray(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("lat",String.valueOf(location.getLatitude()));
jsonObject.put("long",String.valueOf(location.getLongitude()));
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(jsonObject);
sharedPref = getApplicationContext().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(getString(R.string.jsonString),jsonArray.toString());
editor.commit();
System.out.println("jsonString"+jsonString);
}
#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;
}
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
if (intent != null && intent.getAction().equals("start_service")) { C.ACTION_START_SERVICE
startServiceWithNotification();
}else if(intent != null && intent.getAction().equals("stop_service")){
stopMyService();
}
return START_STICKY;
}
void stopMyService() {
stopForeground(true);
stopSelf();
isServiceRunning = false;
}
public void onCreate()
{
startServiceWithNotification();
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (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 (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());
}
}
void startServiceWithNotification() {
if (isServiceRunning) return;
isServiceRunning = true;
Intent notificationIntent11 = new Intent(this, DashboardActivity.class);
notificationIntent11.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent11.setAction("action_main");
notificationIntent11.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentPendingIntent11 = PendingIntent.getActivity(this, 0, notificationIntent11, 0);
Notification notification0 = new NotificationCompat.Builder(this)
.setGroup("12345")
.setGroupSummary(true)
.setContentIntent(contentPendingIntent11)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
android.R.drawable.ic_dialog_email))
.setContentTitle("Bundled Notifications Content Title")
.setContentText("Content Text for group summary")
.setStyle(new NotificationCompat.InboxStyle()
.setSummaryText("This is my inbox style summary."))
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
.setVibrate(new long[]{800, 800, 800, 800})
.setDefaults(Notification.DEFAULT_SOUND)
.setOngoing(true)
.setDeleteIntent(contentPendingIntent11)
.setPriority(PRIORITY_MAX)
.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification0.flags = notification0.flags | Notification.FLAG_NO_CLEAR;
notification0.flags |= Notification.FLAG_FOREGROUND_SERVICE;
notification0.flags |= Notification.FLAG_ONGOING_EVENT;
startForeground(NOTIFICATION_ID, notification0);
}
#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 using service class along with wakelock functionality to make the application work in the background even if the screen is off or sleep. But even if i force close the application the wakelock is not releasing and the app is working in the background. I have attached the service class code below.
Snippet
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
wakeLock= mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
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());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
wakeLock.release();
}
I am acquiring the wakelock in the onCreate method of the service class and releasing it in the onDestroy method of the same class. How to overcome this issue. I am new to services and wakelocks. Thanks in advance.
EDIT 1:
MainActivity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Intent serviceIntent = new Intent(context , MyLocationService.class);
context.startService(serviceIntent );
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
if (!isGooglePlayServicesAvailable()) {
finish();
} else {
Log.d("onCreate", "Google Play Services available.");
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
Location service
public class MyLocationService extends IntentService {
private static final String TAG = "MyLocationService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 3000;
private static final float LOCATION_DISTANCE = 0f;
Context context = this;
PowerManager.WakeLock wakeLock;
public int e=0;
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public MyLocationService(String name) {
super(name);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
protected void onHandleIntent(Intent intent) {
wakeLock.release();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "MyService Started.", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
wakeLock= mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
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());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
// wakeLock.release();
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
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 LocationListener class to get location updates
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
double latitude;
double longitude;
LatLng latLngcurrent;
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);
latitude = location.getLatitude();
longitude = location.getLongitude();
Store.latu=latitude;
Store.longu=longitude;
latLngcurrent = new LatLng(location.getLatitude(), location.getLongitude());
Toast.makeText(context,"Location " + String.valueOf(e), Toast.LENGTH_SHORT).show();
e++;
Toast.makeText(MyLocationService.this,Store.latu+" "+Store.longu, 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);
}
}
}
Solution:
I have finally found the solution for this. its very simple. In your manifest while using the tag add this line too.
Snippet:
<service android:name=".MyLocationService"
android:stopWithTask="true"></service>
stopWithTask will stop the service when we force close the application and the WakeLock will also stop.
here is the documentation. After adding this my application works fine.
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 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.