I need to get the user current location using gps in certain time interval even after closing the application. i have done using service.
here is my service class.
public class MyService extends Service {
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
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, "LocationListener " + location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled " + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled" + provider);
}
}
android.location.LocationListener[] mLocationListener = new android.location.LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Nullable
#Override
public IBinder onBind(Intent intent) {
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");
initializeLocationManagrr();
try {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListener[0]);
}catch(java.lang.SecurityException ex){
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex1){
Log.d(TAG, "gps provider does not exist " + ex1.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG,"onDestroy");
super.onDestroy();
if(mLocationManager!=null){
for(int i=0;i<mLocationListener.length;i++){
try{
mLocationManager.removeUpdates(mLocationListener[i]);
}catch ( Exception e2){
Log.i(TAG, "fail to remove location listners, ignore", e2);
}
}
}
}
private void initializeLocationManagrr(){
Log.e(TAG,"initializeLocationManagaer");
if(mLocationManager==null){
mLocationManager=(LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
And am calling this class from MainActivity.java like this
startService(new Intent(MainActivity.this,MyService.class));
and in my Log nothing is shown regarding the location.
And also i have added the google service config files in my app.
My main problem is am not getting any user location in my Log cat but the app is running fine.
Can Anyone help me please.
you can use LocationListener which gets called when your location get changed and moreover you can provide time interval too
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener(context);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1,mlocL istener);
// syntax: mlocManager.requestLocationUpdates(provider, minTime, minDistance, listener)
you can set time and distance both in this method see ths syntax
Related
I am implementing location tracker from Android app by using foreground service.
The expectation is the foreground service should run even
when app is removed from recent open apps.
When app is in open/foreground.
When app is in background i.e. app is still open but went to background
The case 2 & 3 are working fine but case 1 is working weirdly.
In case 1, sometimes foreground service is getting restarted (notification is going off and coming back) after few seconds i.e. 1 to 3 seconds.
In some other times it is never restarted.
I want the foreground service to never go off. In short, I want it like whatsapp location tracking. The whatsapp tracking icon never goes off when the app is closed.
Please give any pointers on what else I am missing
Activity class
public void enableTracking(String planId, JSONArray trackList, CallbackContext callbackContext) {
Log.i(TAG,"In enableTracking");
Intent intent = new
Intent(cordova.getActivity().getApplicationContext(),LocationTracker.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
cordova.getActivity().startForegroundService(intent);
callbackContext.success("Location Tracking is enabled");
} else {
callbackContext.error("Build version is less than OREO");
}
}
public void disableTracking(CallbackContext callbackContext) {
Log.i(TAG,"In disableTracking");
Intent intent = new Intent(cordova.getActivity().getApplicationContext(),LocationTracker.class);
cordova.getActivity().stopService(intent);
callbackContext.success("Location Tracking is disabled");
}
Service class
public class LocationTracker extends Service {
private final IBinder mBinder = new MyBinder();
private static final String CHANNEL_ID = "2";
private static final String TAG = "LocationTracker";
private FusedLocationProviderClient mFusedLocationClient;
RequestQueue mRequestQueue;
public LocationTracker() {
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.i(TAG, "onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
#Override
public void onCreate() {
super.onCreate();
buildNotification();
// logic to start location tracking
}
#Override
public void onDestroy() {
super.onDestroy();
// logic to stop tracking
}
private void fetchAndSendLocation() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
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) {
Log.e(TAG, "No permission to fetch location");
return;
}
// mFusedLocationClient.getCurrentLocation()
Task fetchLocTask = mFusedLocationClient.getLastLocation();
fetchLocTask.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
Location loc = (Location) o;
if (loc != null) {
Log.i(TAG, "Lat " + loc.getLatitude() + " lon " + loc.getLongitude() + " date " + (new Date()).toString());
postLocation(loc);
}
}
});
}
private void buildNotification() {
String stop = "stop";
PendingIntent broadcastIntent = PendingIntent.getBroadcast(
this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);
// Create the persistent notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText("Location tracking is working")
.setOngoing(true)
.setContentIntent(broadcastIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getString(R.string.app_name),
NotificationManager.IMPORTANCE_DEFAULT);
channel.setShowBadge(false);
channel.setDescription("Location tracking is in progress");
channel.setSound(null, null);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
}
startForeground(1, builder.build());
}
public class MyBinder extends Binder {
public LocationTracker getService() {
return LocationTracker.this;
}
}
}
AndroidManifest.xml
<service android:enabled="true" android:exported="true" android:foregroundServiceType="location" android:name=".LocationTracker" />
Using LocationManager as in code below has solved this similar situation for me.
public class MyLocationService extends Service {
private static final String TAG = "MyLocationService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
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);
}
#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.PASSIVE_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.PASSIVE_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());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
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) {
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listener, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: "+ LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE);
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
You could modify this to suit your need.
I have a background service to track users location. In the service, I have a hashmap with Integer key and LatLng value. The service compares the user's location with the LatLng values. My problem is that sometimes I need to add another value to the hashmap.
I've tried 2 things.
I use https://github.com/orhanobut/hawk for sharedpref storage where I store this hashmap. When the hashmap is updated I save it to Hawk and then as the user's location changes I get the hashmap from the Hawk storage. Problem is that it returns the hashmap without the new value. The only time it actually gives the hashmap with updated value is if I restart the app.
I make the hashmap a static global variable in the Service so I can just update it in the service any time I need. In this case, the hashmap doesn't get updated at all.
So what's the best way for me to update the hashmap in my service?
EDIT Here's my Service Code -
public class LocationService extends Service {
private static final String TAG = "LOCATIONTEST";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
public static HashMap<Integer, LatLng> mLocationList;
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);
// DO stuff here with update mLocationList HashMap
// This should be the update list
mLocationList = Hawk.get("LocationHashmap");
}
#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");
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
mLocationList =Hawk.get("LocationHashmap", new HashMap<Integer, LatLng>());
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());
}
}
#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);
}
}
}
In another Fragment the list is updated by first retreiving it from local storage then updating the list then saving it again.
HashMap<Integer, LatLng> locationList = Hawk.get("LocationList");
locationList.put(order.getId(), latLng);
Hawk.put("LocationList", locationList;
Now, when OnLocationChanged is called I try to call Hawk.get("LocationList") to get the updated hashmap but it's not updated. I think there is something wrong with the library but I'm not sure what else to do. I've also tried making the list in the service static and just updating that list. So instead of the code above in the Fragment it would look like this:
LocationService.mLocationList.put(order.getId(), latLng)
But again the list isn't updated.
In OnCreate I get the HashMap from local storage. Say that list size is 2. Elsewhere in the app I update that list, now the list size is 3. Now when the service hits onLocationChanged I want to iterate through all of the values in the hashmap. But if I tried that same get from local storage to get the update hashmap the size is still 2. How can i update that hashmap in the service?
Sending data to the Firebase but unable to send, my service crash but application still running and when I remove the Firebase code, service runs correctly.
I just want to upload the data to the Firebase with the current location. Every thing is working perfect but Firebase is not sending data to the database but it works with the same code in the activity.
Starting service,
public class location_service extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 50000;
private static final float LOCATION_DISTANCE = 10f;
DatabaseReference databasecustomer;
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("onLocationChanged: " ,"");
mLastLocation.set(location);
String lats= "s";
String lngs= "s";
databasecustomer= FirebaseDatabase.getInstance().getReference("Labor");
String id= databasecustomer.push().getKey();
send_request send_request=new send_request(id,lats,lngs);
databasecustomer.child(id).setValue(send_request);
Toast.makeText(getApplicationContext(),"This is my toast message"+id,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)
{
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());
}
}
#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);
}
}
}
It may be because of the security of database in firebase, change the rule of your database to
{
"rules": {
".read": true,
".write": true
}
}
make sure that your android studio is connected to firebase and to firebase database
We are working on logistics app on Android. App will start independent GPS service that is sending location on change to web server (Apache). GPS service starts with UID and Android Studio log shows that GPS service has this UID working. The problem is that lat and long values are coming to server corretly but UID is simple "0". How can we make GPS service to send UID correctly to server?
Here is the code as it is working right now:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import java.util.HashMap;
public class MyService extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static String UID = null;
private static final int LOCATION_INTERVAL = 5000;
private static final float LOCATION_DISTANCE = 10f; // 10f
private class LocationListener implements android.location.LocationListener // private // public
{
Location mLastLocation;
//public String UID;
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);
//Intent intent = new Intent(this, MyService.class);
HashMap<String, String> data = new HashMap<String, String>();
data.put("id", UID); // SIIN SOOVIN KÄTTE SAADA VÄÄRTUST!!!!
//data.put("id2", iddata);
data.put("lat", Double.toString(location.getLatitude()));
data.put("lng", Double.toString(location.getLongitude()));
AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
asyncHttpPost.setListener(new AsyncHttpPost.Listener(){
#Override
public void onResult(String result) {
// do something, using return value from network
}
});
asyncHttpPost.execute("https://www.isekallur.ee/android/read_gps2.php");
Log.e(TAG, "DATA: " + data);
}
// private void postText(){
//}
#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 intent)
{
return null;
}
/*#Override
protected void onHandleIntent(Intent intent) {
String myID = intent.getExtras().getString("USER_ID");
}*/
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
String iddata =(String) intent.getExtras().get("USER_ID");
final String UID = intent.getStringExtra("USER_ID");
//doSomething2(UID);
Log.e(TAG, "UID: " + UID + " - " + iddata);
//postID(UID);
return START_STICKY; // START_STICKY_COMPATIBILITY // START_STICKY
}
/*private void postID(String UID){
Log.e(TAG, "UID2: " + UID);
}*/
#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());
}
}
#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 have been trying for a long time to figure out how to send data from the service class to the mainactivity class. I am using broadcast receivers right now to do it. The issue is that they aren't being received in the MainActivity class.
public class MyService extends Service {
//all my code for the service which takes the users gps location.
private static final String TAG = "Hello";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 10;//change this for time
private static final float LOCATION_DISTANCE = 0f;//change this to get it every distance
private static final String MY_ACTION = "MY_ACTION";
private final Handler handler = new Handler();
Intent intent;
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.toString());
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);
}
}
//different possible uses for locations
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
//the start of the activity sends data every 5 seconds
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
//initializes locationManager
initializeLocationManager();
try {
Toast.makeText(MyService.this, "It Works", Toast.LENGTH_SHORT).show();
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 initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 5000); // 5 seconds delay
}
};
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intent = new Intent();
initializeLocationManager();
try {
Toast.makeText(MyService.this, "It Works", Toast.LENGTH_SHORT).show();
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
intent.putExtra("Latitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude());
intent.putExtra("Longitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude());
sendBroadcast(intent);
Log.i(TAG,"intent sent");
} 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());
}
}
}
The data is sent. When I try to access it from MainActivity, though, it doesn't seem to get it.
public class MainActivity extends AppCompatActivity {
public SimpleLocation location;
Intent intent;
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Sets views for Android
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
startService(new Intent(this, MyService.class));
intent = new Intent(this, MyService.class);
LocalBroadcastManager.getInstance(this).registerReceiver(
broadcastReceiver, new IntentFilter());
Toast.makeText(MainActivity.this, "" + latitude, Toast.LENGTH_SHORT).show();
}
//sets up broadcast Reciever
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Double latitude = intent.getDoubleExtra("Latitude", 0);
Double longitude = intent.getDoubleExtra("Longitude", 0);
Log.d("hello", "It came this far");
Log.d("hello", " " + latitude);
Log.d("hello", " " + longitude);
TextView txtDateTime = (TextView) findViewById(R.id.textView);
txtDateTime.setText(latitude.toString());
}
};
#Override
public void onResume() {
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter());
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
}
Does anyone know what I am doing wrong?
First,you should add an action to your intent be sent,assume is location,then replace
intent.putExtra("Latitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude());
intent.putExtra("Longitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude());
sendBroadcast(intent);
with
intent.setAction("location");
intent.putExtra("Latitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude());
intent.putExtra("Longitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
And replace
LocalBroadcastManager.getInstance(this).registerReceiver(
broadcastReceiver, new IntentFilter());
with
IntentFilter filter = new IntentFilter("location");
LocalBroadcastManager.getInstance(this).registerReceiver(
broadcastReceiver, filter);
And you should register receiver before start service,so replace
#Override
public void onResume() {
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter());
}
with
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter());
startService(intent);
}
And since you have register in onResume,so you can remove
LocalBroadcastManager.getInstance(this).registerReceiver(
broadcastReceiver, new IntentFilter());
from your onCreate method.
You need to add some actions in intent filter when you register the receiver and at the time of send broadcast you need to set this action to your intent.