Timer is not getting called on scheduled time - java

I want to track a location every 10 minutes and send it to server through TraceDelivery async task. For this I tried to use a service and timer to get the location every 10 minutes.
But when from another activity I call the service it works only once, i.e. once TraceDelivery api gets called but not again. For testing I have given just a second delay still its not getting called again.
Also if I check if mLatLang is null and then call the TraceDelivery it it did not get called at least once. But if location is null it gets crashed with a null pointer on mLatLang.
Service code :
public class LocationTrackerService extends IntentService implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{
private Handler handler;
private Timer timer;
private TimerTask timerTask;
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
private LatLng mLatLang;
LocationManager mLocationManager = null;
boolean gps_enabled = false;
boolean network_enabled = false;
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.NETWORK_PROVIDER),
new LocationListener(LocationManager.GPS_PROVIDER)
};
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public LocationTrackerService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
#Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(1000);
buildGoogleApiClient();
mGoogleApiClient.connect();
handler = new Handler();
initializeLocationManager();
requestLocation();
startTimer(intent.getStringExtra("dl_id"), intent.getStringExtra("pt_id"), intent.getStringExtra("ur_id"),intent.getStringExtra("address"),
intent.getStringExtra("api_key"));
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
public void startTimer(String dlId,String ptId,String urId,String add,String key) {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask(dlId, ptId, urId,key);
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
timer.schedule(timerTask, 1000, 1000);//
}
public void initializeTimerTask(final String dlId, final String ptId, final String urId, final String key) {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
TraceDeliveryAsyncTask traceDeliveryAsyncTask = new TraceDeliveryAsyncTask(LocationTrackerService.this);
traceDeliveryAsyncTask.execute(dlId, ptId, urId, String.valueOf(mLatLang.latitude),
String.valueOf(mLatLang.longitude),"", key);
Log.e("timer","success");
}
});
}
};
}
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(LocationTrackerService.this)
.addConnectionCallbacks(LocationTrackerService.this)
.addOnConnectionFailedListener(LocationTrackerService.this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
// Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
// Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
private void initializeLocationManager() {
// Log.e(Application.TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
try {
gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
if(!CommonUtils.isGPSEnabled(getApplicationContext()))
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
public class LocationListener implements android.location.LocationListener {
public LocationListener() {
}
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
//get current location
if(mLastLocation != null && !mLastLocation.equals("")) {
mLastLocation.set(location);
mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
}
else {
}
}
#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);
}
}
//request for location, first by network, then by gps
public void requestLocation() {
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
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, 0, 0,
mLocationListeners[1]);
} 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());
}
}
}
How can I achieve this?
Please help with this.Thank you..

IntentService will stop immediately one its finished the task in OnHandleIntent,
So instead of using IntentService try to use Service for long running operations.

The Android AlarmManager class can trigger an intent to be sent to your application at set intervals and execute the defined task.Probably what have you been looking for

Related

Background service always running

I have some code to create background service to working always.
this service will be working after app destroyed.
I test more than 20 code example and this code working in simulator, but not working in my phone marshmallow android 6.
This is service file for my app
public class locationService extends Service implements LocationListener {
private LocationManager _locMgr;
com.parse.groupbox.tools.locationTools loc;
Random RND = new Random();
Timer timer = new Timer();
#Override
public void onCreate() {
super.onCreate();
loc = new com.parse.groupbox.tools.locationTools(this);
}
#Override
public void onRebind(Intent intent) {
super.onRebind(intent);
try {
gpsSetup();
timer.cancel();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
updateGps();
}
}, 5000, 10);
} catch (Exception ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
gpsSetup();
timer.schedule(new TimerTask() {
#Override
public void run() {
updateGps();
}
}, 5000, 10);
} catch (Exception ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "start", Toast.LENGTH_SHORT).show();
return Service.START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
try {
gpsSetup();
timer.cancel();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
updateGps();
}
}, 5000, 10);
} catch (Exception ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "task service start", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
super.onDestroy();
try {
gpsSetup();
timer.cancel();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
updateGps();
}
}, 5000, 10);
} catch (Exception ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "service destroyed", Toast.LENGTH_SHORT).show();
}
public void gpsSetup() {
try {
_locMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
locationCriteria.setPowerRequirement(Criteria.POWER_MEDIUM);
String locationProvider = _locMgr.getBestProvider(locationCriteria, true);
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
_locMgr.requestLocationUpdates(locationProvider, 1, 1, this);
Toast.makeText(this, "start service", Toast.LENGTH_SHORT).show();
}
catch (Exception Ex)
{
Toast.makeText(this, Ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void updateGps(){
try{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
String locationProvider = LocationManager.NETWORK_PROVIDER;
_locMgr.requestLocationUpdates(locationProvider, 1, 1, this);
}catch (Exception Ex){
Toast.makeText(this, Ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
int result = RND.nextInt(100);
if(result > 30){
try{
loc.LocationSyncToServer(location);
Toast.makeText(this, "location", Toast.LENGTH_LONG).show();
}catch (Exception Ex){
Toast.makeText(this, Ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Please read my codes and give me answer to solve it.
This is the code to run the service:
Intent background = new Intent(getApplicationContext(), com.parse.groupbox.services.locationService.class);
startService(background);
try this
put this code where you want to stop service
Intent intent = new Intent(getApplicationContext(),com.parse.groupbox.services.locationService.class);
intent.setAction(Constants.ACTION.STOPTFOREGROUND_ACTION);
stopService(intent);
in your Service onStartCommand()
if(intent.getAction()==Constants.ACTION.STOPTFOREGROUND_ACTION){
stopForeground(true);
stopSelf();
}
create a class Constants
public class Constants {
public interface ACTION {
String STOPFOREGROUND_ACTION = "com.package.packageName.action.stopforeground";
}
}
Android M introduced Doze and App Standby which limits background services in order to preserve battery. How to handle Doze can be found in here android developer site.

Update Hashmap in background service

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?

Unable to send data to Firebase in a back ground 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

Android - Getting user Current location in certain time interval

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

Remove updates on location manager not working

I have a map on which I want to show user's current location and I am calling an api after getting user's location to get the nearby merchants.
I am getting the user's current location, also all the merchants are getting plot by markers on map.
But I have called the setMap method in the onLocationChanged() method of LocationListener. This method get's called continuously.
I want to get the location once and show on the marker, again when next time user comes to this fragment then only I want to get updated location.
But now it's going in a loop continuously that onLocation method get's called and so accessMerchants is getting called.
To stop this I tried to remove updates from location manager, also I tried to set a boolean variable if it first time goes in onLocationChanged() method, it will be false but again it is also going in a loop.
Remove updates also not working, if remove updates is worked, then onLocationChanged method should not get called again right?
public class SearchMerchantFragment extends Fragment implements GetSearchedMerchantsAsyncTask.GetSearchedMerchantsCallBack, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search_merchant, container, false);
setUpUI(view);
return view;
}
public void setUpUI(View view) {
initializeLocationManager();
requestLocation();
setUpMapIfNeeded();
mLocationsList = new ArrayList<>();
markers = new ArrayList<>();
edtSearch = (EditText) view.findViewById(R.id.edtSearch);
rv_fetch_merchants = (RecyclerView) view.findViewById(R.id.rv_fetch_merchants);
merchantsList = new ArrayList<Merchants>();
merchantsAdapter = new SearchedMerchantsAdapter(this.getContext(), merchantsList);
rv_fetch_merchants.setLayoutManager(new LinearLayoutManager(getActivity()));
rv_fetch_merchants.setAdapter(merchantsAdapter);
rv_fetch_merchants.setHasFixedSize(true);
rv_fetch_merchants.setItemViewCacheSize(30);
rv_fetch_merchants.setDrawingCacheEnabled(true);
rv_fetch_merchants.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
}
//get searched merchants
public void accessMerchants() {
if (CommonUtils.isConnectedToInternet(getContext())) {
new GetSearchedMerchantsAsyncTask(getActivity(), SearchMerchantFragment.this).execute(access_token, sessionUserId, String.valueOf(mLastLocation.getLatitude()), String.valueOf(mLastLocation.getLongitude()));
} else {
showAlert(String.valueOf(R.string.check_network));
}
}
#Override
public void doPostExecute(ArrayList<Merchants> merchantsArrayList) {
merchantsList.clear();
merchantsList.addAll(merchantsArrayList);
merchantsAdapter.notifyDataSetChanged();
for (Merchants merchants : merchantsList) {
LatLng latLng = new LatLng(merchants.getLatitude(), merchants.getLongitude());
MarkerOptions marker = new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).title(merchants.getKirana_name());
Marker m = mGoogleMap.addMarker(marker);
markers.add(m);
}
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
// getLocation();
}
}
//setup map
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
buildGoogleApiClient();
mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
// Toast.makeText(getActivity(),"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
// Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
// Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
private void removeMarkers() {
if (mGoogleMap != null) {
for (Marker marker : markers) {
marker.remove();
}
mGoogleMap.clear();
markers.clear();
}
}
#Override
public void onDetach() {
super.onDetach();
mapConnected = false;
}
return true;
}
public void setMap() {
try {
int locationPermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
int coarseLocation = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_COARSE_LOCATION);
if(locationPermission == PackageManager.PERMISSION_GRANTED && coarseLocation == PackageManager.PERMISSION_GRANTED && GPSTracker.isGPSEnabled) {
if(receivedLocation) {
receivedLocation = false;
mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
accessMerchants();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mLatLang);
markerOptions.title(getString(R.string.position));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mMarker = mGoogleMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(mLatLang).zoom(14).build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
// mLocationRequest = new LocationRequest();
// mLocationRequest.setInterval(5000); //5 seconds
// mLocationRequest.setFastestInterval(3000); //3 seconds
// mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
LocationListener locationListener = new LocationListener();
mLocationManager.removeUpdates(locationListener);
}
}
else {
showAlert(getString(R.string.locationAlert));
}
} catch (SecurityException e) {
}
}
private void initializeLocationManager() {
// Log.e(Application.TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
}
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
showAlert(getString(R.string.locationAlert));
}
}
public class LocationListener implements android.location.LocationListener {
public LocationListener() {
}
public LocationListener(String provider) {
Log.e(Application.TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(Application.TAG, "onLocationChanged: " + location);
receivedLocation = true;
mLastLocation.set(location);
if (receivedLocation) {
setMap();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.e(Application.TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(Application.TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(Application.TAG, "onStatusChanged: " + provider);
}
}
public void requestLocation() {
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(Application.TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(Application.TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(Application.TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(Application.TAG, "gps provider does not exist " + ex.getMessage());
}
}
}
What's going wrong?? Please help.. Where should I call removeUpdates?? thank you..
You register for updates from 2 providers, did you deregister from both?
Also, to make the boolean flag work you need to make a change- set it to true at the end of the function, and change the if to if(!receivedLocation) That will make it run only once. As it is, it will never run.

Categories

Resources