AlarmManager, BroadcastReceiver not working on some devices - android

I am creating alarmmanager in one of my activities like following
AlarmManager alarmManager=(AlarmManager) MenuItems.this.getSystemService(Context.ALARM_SERVICE);
Intent intent23 = new Intent(MenuItems.this, MyReceiver.class);
PendingIntent pendingIntent23 = PendingIntent.getBroadcast(MenuItems.this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),300000,
pendingIntent);
After this i have following BroadcastReceiver
public class MyReceiver extends WakefulBroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
MyAlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
This broadcast receiver calls my following service
Public class MyAlarmService extends Service
{
private String server_response,data_to_send;
private String server ;
private String setLocation = "/xyz";
private URL url;
public double mLatitude;
private MainActivity main;
private boolean isGpsEnabled = false;
private sendToserver send;
private Context context;
public String vallatlong;
private boolean isNetworkEnabled = false;
private boolean canGetLocation = false;
private Location mLocation;
public MyAlarmService(Context context)
{
this.context = context;
getLocation();
}
public MyAlarmService()
{
}
public double mLongitude;
private LocationManager mLocationManager;
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
main = new MainActivity();
getLocation();
}
public String getLocation()
{
server = getString(R.string.server_add_new);
try {
Log.e("this is getlocation method ", "1");
mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
/*getting status of the gps*/
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
/*getting status of network provider*/
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnabled && !isNetworkEnabled) {
Log.e("no provider", "non availability");
} else {
Log.e("this is getlocation method ", "2");
this.canGetLocation = true;
/*getting location from network provider*/
if (isNetworkEnabled) {
// mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
Log.e("this is getlocation method ", "3");
if (mLocationManager != null) {
Log.e("this is getlocation method ", "7");
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
Log.e("this is getlocation method ", "8");
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
long user_id = main.getDefaultsint("user_id", MyAlarmService.this);
String stringLatitude = String.valueOf(mLatitude);
String stringLongitude = String.valueOf(mLongitude);
vallatlong = stringLatitude+stringLongitude;
try {
url = new URL(server+setLocation);
data_to_send = "lat=" + mLatitude + "&";
data_to_send += "long=" + mLongitude + "&";
data_to_send += "user_id=" + user_id ;
Log.e("data to send", "url"+data_to_send);
send = new sendToserver(url, data_to_send);
send.execute();
Log.e("this is getlocation method ", "6");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
/*if gps is enabled then get location using gps*/
if (isGpsEnabled) {
if (mLocation == null) {
// mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
Log.e("this is getlocation method ", "4");
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
Log.e("this is getlocation method ", "5");
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
long user_id = main.getDefaultsint("user_id", MyAlarmService.this);
try {
url = new URL(server+setLocation);
data_to_send = "lat=" + mLatitude + "&";
data_to_send += "long=" + mLongitude + "&";
data_to_send += "user_id=" + user_id ;
Log.e("data to send", "url"+data_to_send);
send = new sendToserver(url, data_to_send);
send.execute();
Log.e("this is getlocation method ", "6");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return vallatlong;
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
public double getLatitude() {
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}
public double getLongitude() {
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
}
return mLongitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public class sendToserver extends AsyncTask<URL, String, ArrayList<String>>
{
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
}
String data_to_send = "";
URL url;
public sendToserver(URL u, String data){
this.url = u;
this.data_to_send = data;
}
#Override
protected ArrayList<String> doInBackground(URL... params) {
BufferedReader reader=null;
try
{
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_to_send);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
Log.e("inside", "while loop");
}
server_response = sb.toString();
}
catch(Exception ex)
{
}
return null;
}
}
}
Everything is working fine, my activity sets Alarmmanager which triggers broadcast-receiver after every 5 minutes which executes my service even when my app is closed and phone is not in use i am getting user location at my server, but on some phones like galaxy NoteEdge this code is not working. I am not getting user location after every 5 minutes am i doing something wrong. Please suggest any relevant way of doing this if this is not right way of doing.

Related

Background service in android 10 to get location in every 10 minutes

I have facing issue in Android 10 to get location in every 10 minutes when app in background or app is killed. Till android 9 pie everything is working correct but in android 10 when app goes in background in few seconds onDestory() method is called in service and service is destroying. How can i reslove this issue and start service in background. Here is my service class :
public class LocaionTrackingService extends Service {
private static final String TAG = "LocaionTrackingService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = Common.LOCATION_TIME_INTERVAL;
private static final float LOCATION_DISTANCE = 0;
private Context mContext;
boolean checkGPS = false;
boolean checkNetwork = false;
Location loc;
public static final int notify = Common.LOCATION_TIME_INTERVAL; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Common.printLog(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Common.printLog(TAG, "onLocationChanged: " + location + "\n" + "Lat:" + location.getLatitude() + "\nLang:" + location.getLongitude());
mLastLocation.set(location);
try {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.size() > 0) {
String address = Common.getFullAddressFromGeoCoder(addresses.get(0));
PreferenceData.setLocationData(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()), address);
Common.printLog(TAG, "->address" + address);
}
sendLatLong(location.getLatitude() + "", location.getLongitude() + "", PreferenceData.getAddress(), Common.isGPSON(getApplicationContext()) ? "1" : "0");
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onProviderDisabled(String provider) {
Common.printLog(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Common.printLog(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Common.printLog(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Common.printLog(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
Common.printLog(TAG, "onCreate");
initializeLocationManager();
setLastLocation();
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task
}
void getAddressfromGeocoder(double Latitude, double Longitude) {
try {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = null;
addresses = geocoder.getFromLocation(Latitude, Longitude, 1);
if (addresses.size() > 0) {
String address = Common.getFullAddressFromGeoCoder(addresses.get(0));
PreferenceData.setLocationData(String.valueOf(Latitude), String.valueOf(Longitude), address);
Common.printLog(TAG, "tag->getAddressfromGeocoder :" + address + "\nLatitude" + Latitude + "\nLongitude" + Longitude);
}
} catch (IOException e) {
e.printStackTrace();
}
}
void setLastLocation() {
try {
if (!checkGPS && !checkNetwork) {
//Toast.makeText(mContext, "No Service Provider is available", Toast.LENGTH_SHORT).show();
} else {
if (checkGPS && !PreferenceData.getLastLAN().equals("") && !PreferenceData.getLastLAT().equals("")) {
Common.printLog(TAG, "check For GPS");
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
if (mLocationListeners != null) {
loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
getAddressfromGeocoder(loc.getLatitude(), loc.getLongitude());
}
}
} else if (checkNetwork) {
Common.printLog(TAG, "check For Network");
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
if (mLocationListeners != null) {
loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (loc != null) {
getAddressfromGeocoder(loc.getLatitude(), loc.getLongitude());
}
}
}
}
} catch (java.lang.SecurityException ex) {
Common.printLog(TAG, "fail to request location update, ignore" + ex);
} catch (IllegalArgumentException ex) {
Common.printLog(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy() {
Common.printLog(TAG, "onDestroy");
super.onDestroy();
mTimer.cancel();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Common.printLog(TAG, "fail to remove location listners, ignore" + ex);
}
}
}
}
private void initializeLocationManager() {
Common.printLog(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
// get GPS status
checkGPS = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// get network provider status
checkNetwork = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
}
void sendLatLong(final String Lat, final String Long, final String address, final String isLocationOn) {
if (NetworkUtil.getConnectivityStatus(getApplicationContext()) != 0) {
String url = Common.LIVE_EMP_TRACK;
Common.printLog(TAG, "url->" + url);
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Common.printLog(TAG + "->response", response);
PreferenceData.setLocationData(Lat, Long, address);
PreferenceData.setLastUpdateLocation(System.currentTimeMillis());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Common.printLog(TAG, String.valueOf(Common.getErrorMsg(mContext, error, null)));
PreferenceData.setLastUpdateLocation(System.currentTimeMillis());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Latitude", Lat);
params.put("Longitude", Long);
params.put("Location", address);
params.put("isLocationOn", isLocationOn);
params.put("EmpId", PreferenceData.getUserBy());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("API-Key", BuildConfig.KEY);
params.put("Clientip", PreferenceData.getIpAddress());
params.put("Userid", PreferenceData.getUserId());
return params;
}
};
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq);
} else {
Common.printLog("Service", "No network");
}
}
//class TimeDisplay for handling task
class TimeDisplay extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
setLastLocation();
Common.printLog(TAG, "Location Service running-" + Calendar.getInstance().getTimeInMillis());
//Toast.makeText(LocaionTrackingService.this, "Service is running", Toast.LENGTH_SHORT).show();
sendLatLong(PreferenceData.getLastLAT(), PreferenceData.getLastLAN(), PreferenceData.getAddress(), Common.isGPSON(getApplicationContext()) ? "1" : "0");
}
});
}
}
}
Due to the android's limitations for background tasks in post-O devices, background services are destroyed by the android system if the app is in the background for some time. You should use startForeground() in onStartCommand() to start the service as a foreground service and also show the notification for the same.

how to update latitude and longitude through a background service at regular intervals?

I have written a background service to insert latitude , longitude and some other details into my sqlite database based on the time limit set in my AlarmManager.
I am using GoogleApiClient to calculate latitude and longitude , but i am facing some problems.
Problem
When i am travelling outside without net , the latitude and longitude is not getting updated at regular intervals. The data is getting inserted in my sqlite at regular intervals but latitude and longitude remains same even after half an hour though i am travelling some about 10 kms.
I want the latitude and longitude to change while i am travelling like auto update.
I wanted to know if the FusedLocationApi calculates latitude longitude properly even if i am not connected to the internet , if yes then i need some suggestions to improve the code that i have tried.
Code i have tried.
AlarmManagerService.java
public class AlarmManagerService extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = "AlarmManagerService";
AlarmReceiver alarmReceiver;
DriverDbHelper driverDbHelper;
Handler handler;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
// Location updates intervals in sec
private static int UPDATE_INTERVAL = 120000; // 2 mins
private static int FATEST_INTERVAL = 60000; // 1 min
private static int DISPLACEMENT = 10; // 10 meters
public Activity activity;
protected String mLastUpdateTime;
String areaName0, areaName1, areaName2, areaName3, fullAreaName,
sessionMobileNo, sessionDriverName, sessionDID, sessiondriverUserId,
date, time, dateTime, doc, trac_transId;
double latitude, longitude;
PowerManager.WakeLock mWakeLock;
SessionManager session;
ConnectionDetector cd;
Boolean isInternet = false;
String sync_no = "No";
String sync_yes = "Yes";
public AlarmManagerService() {
alarmReceiver = new AlarmReceiver();
driverDbHelper = new DriverDbHelper(this);
cd = new ConnectionDetector(this);
}
public void setActivity(Activity activity) {
this.activity = activity;
}
#Override
public void onCreate() {
super.onCreate();
try {
driverDbHelper.open(AlarmManagerService.this);
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Service created", "Alarm Service Created");
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
PowerManager mgr = (PowerManager)
getSystemService(Context.POWER_SERVICE);
if (this.mWakeLock == null) {
this.mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakeLock");
}
if (!this.mWakeLock.isHeld()) {
this.mWakeLock.acquire();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
Log.d("Service started", "Alarm Service Started");
handler = new Handler(Looper.myLooper());
handler.post(new Runnable() {
#Override
public void run() {
postDatabaseDetails();
}
});
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("Service started", "Alarm Service Destroyed");
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
mGoogleApiClient.disconnect();
}
if (this.mWakeLock != null) {
this.mWakeLock.release();
this.mWakeLock = null;
}
}
private void displayLocation() {
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
List<Address> addressList = null;
try {
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
addressList = gcd.getFromLocation(mLastLocation.getLatitude(),
mLastLocation.getLongitude(), 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
areaName0 = address.getLocality(); // city name
areaName1 = address.getSubLocality();
areaName2 = address.getAdminArea();// statename
//areaName3 = address.getFeatureName(); plot no
//areaName3 = address.getCountryCode();// IN
areaName3 = address.getThoroughfare();
fullAreaName = areaName3 + "\n" + areaName1 + "\n" +
areaName0 + "," + areaName2;
} else {
Log.i("Location ", "Location null");
}
} catch (IOException e1) {
Log.e("HomePage", "IO Exception in getFromLocation()");
e1.printStackTrace();
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments " +
Double.toString(mLastLocation.getLatitude()) + " , " +
Double.toString(mLastLocation.getLongitude()) +
" passed to address service";
Log.e("HomePage", errorString);
e2.printStackTrace();
}
}
}
/**
* Creating google api client object
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Creating location request object
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
//mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
/**
* Method to verify google play services on the device
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, activity,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i("Google play services", "Device not supported");
activity.finish();
}
return false;
}
return true;
}
/**
* Starting the location updates
*/
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Stopping location updates
*/
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
public void onConnected(Bundle bundle) {
// Once connected with google api, get the location
//displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
if (mLastLocation == null) {
mLastLocation =
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
displayLocation();
}
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.d("Location changed ", "Location changed " + mLastLocation);
Log.d("Last updated time", "Last updated location " + mLastUpdateTime);
// Displaying the new location on UI
displayLocation();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ connectionResult.getErrorCode());
}
public void postDatabaseDetails() {
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
sessionMobileNo = user.get(SessionManager.KEY_MOBILENO);
sessionDriverName = user.get(SessionManager.KEY_NAME);
sessionDID = user.get(SessionManager.KEY_DEVICEID);
sessiondriverUserId = user.get(SessionManager.KEY_DRIVERUSERID);
Calendar in = Calendar.getInstance();
Date dt = new Date();
in.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss");
date = sdf.format(dt);
time = stf.format(dt);
String timeval = time.toString();
String dateval = date.toString();
dateTime = date.toString() + " " + time.toString();
doc = sessionDID + "" + dateTime;
isInternet = cd.isConnectingToInternet();
if (isInternet) {
long id = driverDbHelper.insertDriverDetails(doc, sessionDID,
sessiondriverUserId, latitude, longitude,
fullAreaName, dateTime, "DEMO", sync_no, dateval, timeval);
postDriverDetails();
Log.d("GPS", "Service started after 2 mins with internet");
} else {
Log.d("Internet status", "No internet available for service");
long id = driverDbHelper.insertDriverDetails(doc, sessionDID,
sessiondriverUserId, latitude, longitude,
"NA", dateTime, "DEMO", sync_no, dateval, timeval);
Log.d("GPS", "Service started after 2 mins without internet");
}
}
I am calling this service from the activity HomePage.java , but from where do i have to call the below code , from onStart() or after setContentView(R.layout.home)?
try {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MINUTE, 2);
AlarmManager am = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(Home_Page.this, AlarmManagerService.class);
PendingIntent pi = PendingIntent.getService(Home_Page.this, 0, i,0);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), EXEC_INTERVAL, pi);
} catch (Exception e) {
e.printStackTrace();
}
I hope i can get some suggestions to improve the above service code as i want it to run smoothly in background updating the latitude and longitude at regular intervals.

Android geocoding api can't return addressess

I'm having some trouble geocoding locations, i guess i've implemented everything. I've registered a google api, i've recieved a working google Api key, i also turned on google maps and geocoding services, but i can't get any locations associated with some hardcoded longitudes and latitudes.
Here's the code:
My AppLocationService
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
My LocationAddress class
public class LocationAddress {
private static final String TAG = "LocationAddress";
public static void getAddressFromLocation(final double latitude, final double longitude,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n\nAddress:\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n Unable to get address for this lat-long.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
Somewhere deep in my mainActivity:
appLocationService = new AppLocationService(
ServerInterface.this);
Location location = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double latitude = 47.162494;
double longitude = 19.503304;
LocationAddress locationAddress = new LocationAddress();
LocationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeocoderHandler());
}
Thanks,
I think you can take look at this. I tried and it worked.
Hope it hopes.

onLocationChanged is not fired in jelly bean

I have used following code for getting the location. It is working fine in Android 4.0.4 but not in 4.1.1. Googled a lot but not found any solution.Please help me Thanks in advance.
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocListener = new UserLocationListener(getApplicationContext());
if (mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1, 0, mLocListener);
} else if (mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1, 0, mLocListener);
}
public class UserLocationListener implements LocationListener {
Context mContext;
String mCurrLocation = null;
double latitude, longitude;
String locale;
public String getLocale() {
return locale;
}
public String getmCurrLocation() {
return mCurrLocation;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public UserLocationListener(Context _mContext) {
mContext = _mContext;
}
#Override
public void onLocationChanged(Location location) {
Geocoder gcd = new Geocoder(mContext, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
longitude = location.getLongitude();
latitude = location.getLatitude();
locale = Locale.getDefault().getCountry();
if (addresses.size() > 0) {
mCurrLocation = formatAddress(addresses.get(0));
} else {
Log.e("LocationListener",
"Geocoder backend service not present");
}
} catch (IOException e) {
} catch (NullPointerException e) {
}
}
/**
* Formats the Address to a meaningful String representation
*
* #param address
* #return String
*/
private String formatAddress(Address address) {
String addr = "";
StringBuilder sb = new StringBuilder();
if (address.getAddressLine(0) != null) {
sb.append(address.getAddressLine(0));
} else if (address.getSubThoroughfare() != null) {
sb.append(address.getSubThoroughfare());
} else if (address.getSubThoroughfare() != null) {
sb.append(address.getSubThoroughfare());
} else if (address.getThoroughfare() != null) {
sb.append(address.getThoroughfare());
} else if (address.getSubLocality() != null) {
sb.append(address.getSubLocality() + ",");
} else if (address.getPremises() != null) {
sb.append(address.getPremises() + ",");
} else if (address.getLocality() != null) {
sb.append(address.getLocality() + ",");
} else if (address.getSubAdminArea() != null) {
sb.append(address.getSubAdminArea() + ",");
} else if (address.getAdminArea() != null) {
sb.append(address.getAdminArea() + ",");
} else if (address.getPostalCode() != null) {
sb.append(address.getPostalCode() + ",");
} else if (address.getCountryName() != null)
sb.append(address.getCountryName() + ",");
addr = sb.toString();
return addr;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

How to populate pin on Android Map Smoothly?

I am showing place by using pin image on google map in android by calling This Url
This url refresh all the time when zoom-in or zoom-out map.
I am using this code for populating pin on map call url in doInbackground an load in onPostExcution of AsyncTask As-
if(!valueoftotal.equalsIgnoreCase("") && !valueoftotal.equalsIgnoreCase(null))
{
if(Integer.parseInt(valueoftotal) > 0 && Integer.parseInt(valueoftotal) <= 100)
{
OverlayItem oi;
if(myHandler.getParsedData()!=null)
{
arrayList = myHandler.getParsedData();
}
linearbottom2.setClickable(true);
mapOverlays.clear();
//OverlayItem overlayItem,overlayItem1;
overlay.removeAll();
lineartabbar.setBackgroundResource(R.drawable.mapbar);
if( arrayList.size()!=0 && arrayList.size()>1 )
{
for(int i = 0; i < arrayList.size(); i++)
{
String latvalue = arrayList.get(i).getLatitude().toString();
String lonvalue = arrayList.get(i).getLongitude().toString();
GeoPoint point = null;
try
{
point = new GeoPoint((int)(Double.parseDouble(latvalue)*1E6),(int)(Double.parseDouble(lonvalue)*1E6));
}
catch (NumberFormatException e)
{
// TODO: handle exception
}
if(point != null)
{
if(arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
System.out.println("overlayyyyyyyyyyyyy" + overlay + "\toiiiiiiiiii"+oi);
if(overlay!=null)
{
overlay.addItem(oi);
}
}
else if(!arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
if(overlay!=null)
{
System.out.println("2overlayyyyyyyyyyyyy" + overlay + "\toiiiiiiiiii" + oi);
overlay.addItem(oi);
}
}
}
}
mapOverlays.add(overlay);
mapView.invalidate();
}
else if( arrayList.size()!=0 && arrayList.size()==1 )
{
for(int i = 0; i < arrayList.size(); i++)
{
String latvalue = arrayList.get(i).getLatitude().toString();
String lonvalue = arrayList.get(i).getLongitude().toString();
GeoPoint point = null;
try
{
point = new GeoPoint((int)(Double.parseDouble(latvalue)*1E6),(int)(Double.parseDouble(lonvalue)*1E6));
}
catch (NumberFormatException e)
{
// TODO: handle exception
}
if(point != null)
{
if(arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
System.out.println("listing when 1 value is "+arrayList.get(i).getUnitstotal());
overlay.addItem(oi);
mc.animateTo(point);
}
else if(!arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
System.out.println("listing when more value is "+ arrayList.get(i).getUnitstotal());
overlay.addItem(oi);
mc.animateTo(point);
mc.setCenter(point);
mc.setZoom(18);
}
}
}
mapOverlays.add(overlay);
mapView.invalidate();
MapController mcontrller =mapView.getController();
But the problem is when I touch map immediately, it remove all pin and start loading new position. I want to load smoothly get all the position first and then remove.
Please anyone help me ASAP, sorry for my explanation.
public class HelloAndroidGpsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener
{
private EditText editTextShowLocation;
private Button buttonGetLocation;
private ProgressBar progress;
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
progress = (ProgressBar) findViewById(R.id.progressBar1);
progress.setVisibility(View.GONE);
buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(this);
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
progress.setVisibility(View.VISIBLE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please enable location providers");
builder.setPositiveButton("OK", this);
builder.setNeutralButton("Cancel", this);
builder.create().show();
progress.setVisibility(View.GONE);
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// This needs to stop getting the location data and save the battery power.
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
progress.setVisibility(View.GONE);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == DialogInterface.BUTTON_NEUTRAL){
editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
}else if (which == DialogInterface.BUTTON_POSITIVE) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
}

Categories

Resources