How can I start Android service separately? - android

Here what I need, how can I start Android service separately?
I got service running from background (Preference.Class),
public void startService(){
Intent intent;
intent = new Intent(getBaseContext(), ForegroundService.class);
startService(intent);
intent = new Intent(getBaseContext(), PostMobileHistory.class);
startService(intent);
intent = new Intent(getBaseContext(), PostLocation.class);
startService(intent);
sharedPreferences.edit().putBoolean("serviceStatus", true).commit();
}
and start the Location Manager which run in service after from the BroadcastReceiver, but why the previous service gone, and just only Lcation Manager left?
public class LocationManager extends Service implements LocationListener{
private android.location.LocationManager locationManager;
private String previousProvider = "gps";
private float previousAccuracy = 100;
public String mobileHistory_GUID = null;
Context context = this;
#Override
public void onCreate() {
SharedPreferences sharedPreferences = context.getSharedPreferences("mobileHistory", Context.MODE_PRIVATE);
mobileHistory_GUID = sharedPreferences.getString("GUID", "DEFAULT");
Log.i("SP Mobile History GUID", mobileHistory_GUID);
startTracking();
}
public void onDestroy(){
stopTracking();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void stopTracking(){
if(locationManager != null){
locationManager.removeUpdates(this);
Log.i("Location Manager", "Tracking stopped");
}
}
public void startTracking() {
//Get the location manager
locationManager = (android.location.LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean isGPSEnabled = locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager.isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
Log.i("Provider Status", "No provider");
}
else {
if (isNetworkEnabled) {
String locationProvider = android.location.LocationManager.NETWORK_PROVIDER;
Log.i("Provider Status", "Network enabled");
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(locationProvider, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
if (isGPSEnabled) {
String locationProvider = android.location.LocationManager.GPS_PROVIDER;
Log.i("Provider Status", "GPS enabled");
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(locationProvider, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
}
if(locationManager != null){
Log.i("Location Manager", "Tracking started");
}
}
public void onLocationChanged(Location location) {
SharedPreferences sharedPreferences = context.getSharedPreferences("mobileHistory", Context.MODE_PRIVATE);
String mobileHistory_GUID = sharedPreferences.getString("GUID", "DEFAULT");
String location_GUID = String.valueOf(UUID.randomUUID());
if (location != null) {
String latitude = valueOf(location.getLatitude());
String longitude = valueOf(location.getLongitude());
String altitude = valueOf(location.getAltitude());
String accuracy = valueOf(location.getAccuracy());
String speed = valueOf(location.getSpeed());
String provider = location.getProvider();
float floatAccuracy = Float.valueOf(accuracy);
if(floatAccuracy <= 20 && provider.equals("gps")){
Arrays.setLocationArrayList(new Model_Location(location_GUID, mobileHistory_GUID, provider, latitude, longitude, altitude, accuracy, speed));
Log.i("Location", "GPS");
Log.i("Location", "<= 20");
Log.i("Location", latitude + " " + longitude + " " + altitude + " " + accuracy + " " + speed);
previousProvider = provider;
previousAccuracy = floatAccuracy;
}
else if(floatAccuracy > 20 && provider.equals("gps")){
previousProvider = provider;
previousAccuracy = floatAccuracy;
}
else if(floatAccuracy > 20 && floatAccuracy <= 100 && provider.equals("network")){
if(previousAccuracy > 20 && previousProvider.equals("gps")){
Arrays.setLocationArrayList(new Model_Location(location_GUID, mobileHistory_GUID, provider, latitude, longitude, altitude, accuracy, speed));
Log.i("Location", "Network");
Log.i("Location", ">= 20 && <= 50");
Log.i("Location", latitude + " " + longitude + " " + altitude + " " + accuracy + " " + speed);
}
}
else{
Log.i("Location", latitude + " " + longitude + " " + altitude + " " + accuracy + " " + speed);
}
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

The problem solve, I shouldn't put function in the onCreate() on service, moved to onStartCommand() and its work perfectly well...

Related

onlocationchanged is not called (delay parameter does not apply)

in
locationManager.requestLocationUpdates(provider, time, distance, locationListener);
I knew that without the priority of time and distance, If it satisfied with either condition is called a onLocationChanged()
But onLocationChanged() is not called, only called this circumstances.
1. Load the page and turns on the gps.
2. location listener catch (0,0) white gps is turned on. (onLocationChanged called)
3. gps is turn on finish.
4. The location listener is called after the time that was 'time' parameter of requestLocationUpdates(). (onLocationChanged called)
5. After... onLocationChanged is not called never..
 
1. If the beginning location is normal value, not (0,0). onLocationChanged is not ever call. (Even after the time specified in the parameters)
Why does not apply to the time parameters of requestLocationUpdates()?
this is my code.
private BroadcastReceiver gpsReceiver = new BroadcastReceiver() {
private final String GET_GPS = "getGPS";
private final String SET_GPS = "setGPS";
private final String START_GPS = "startGPS";
private final String FINISH_GPS = "finishGPS";
Location location;
LocationManager locationManager;
double lat;
double lon;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 1000 *60;
boolean isGpsMode = false;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra("action");
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
JSONObject obj = new JSONObject();
if(action.equals(GET_GPS)){
if(isGPSOn()){
try {
obj.put("result","gpsOn");
} catch (JSONException e) {
e.printStackTrace();
}
} else{
try {
obj.put("result","gpsOff");
} catch (JSONException e) {
e.printStackTrace();
}
}
}else if(action.equals(SET_GPS)){
Intent settingIntent= new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
settingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(settingIntent);
}else if(action.equals(START_GPS)){
Log.d("GPS", "GPS Start");
//stopUsingGPS();
startCallback();
}else if(action.equals(FINISH_GPS)){
Log.d("GPS", "GPS Finish");
stopUsingGPS();
}
if(!(obj.toString().equals("{}"))){
sendScript("javascript:getGPS" + "(" + obj + ")");
}
}
public boolean isGPSOn(){
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public boolean isNetworkOn(){
return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void stopUsingGPS(){
Log.d("GPS", "stopUsingGPS()");
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
Log.d("GPS", "lovationManager remove");
}
}
public void startCallback(){
Log.d("GPS", "startCallback()");
if(isGpsMode != isGPSOn()){
if(isGpsMode){
if(isNetworkOn()){
NetworkRegistration();
}
}else{
if(!GPSRegistration()){
if(isNetworkOn()){
NetworkRegistration();
}
}
}
}
}
public boolean GPSRegistration(){
Log.d("GPS", "call location value from GPS");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
saveLocation();
isGpsMode = true;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon: " + String.valueOf(lon));
return isAvailableLocation(lat, lon);
}
public void NetworkRegistration(){
Log.d("GPS", "call location value from Network");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
saveLocation();
isGpsMode = false;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon : " + String.valueOf(lon));
}
public void saveLocation(){
location = null;
if (locationManager != null) {
location = getLastKnownLocation();
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
}
}
private Location getLastKnownLocation() {
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
return bestLocation;
}
public boolean isAvailableLocation(double lat, double lon){
if(lon>124 && lon<132 && lat>33 && lat<43){
return true;
}
return false;
}
private LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("GPS", "onLocationChanged - lat: "+lat+" / lon: "+lon);
if(!(isAvailableLocation(lat, lon))){
stopUsingGPS();
if(isGpsMode){
if(isNetworkOn()){
NetworkRegistration();
if(isAvailableLocation(lat, lon)){
isGpsMode = !isGpsMode;
}
}
}else{
if(isGPSOn()){
GPSRegistration();
if(isAvailableLocation(lat, lon)){
isGpsMode = !isGpsMode;
}
}
}
}
if(isAvailableLocation(lat, lon)){
JSONObject obj = new JSONObject();
try{
obj.put("lat", lat);
obj.put("lon", lon);
}catch( JSONException e){
Log.d("GPS", "onRegistered: JSON exception");
}
sendScript("javascript:sendGPS("+obj+");");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
};
};
The reason I coding like this, it must be in Cordova Activity. (And the boss want it... )
+) I delete comment deliberately, because comment was Korean.. (I'm Korean)
I'm sorry that hard to understand because no comment... :(
All, thanks :)
I think you should use Service instead of BroadcastReceiver for GPS.
Self answer.
1. onlocationchanged is not called
This situation is shown when used GPS provider indoors.
When using the GPS provider at room onLocationChange () is not called. (The network provider is operating very successfully.)
So, the value of the gps provider is invalid, must be connected to the network provider.
2. The Time parameters of requestLocationUpdates() is not apply
Although not accurate, I think this is probably related to the length of time.
Because, I confirmed to be the working when by the 5 minutes(1000 * 60 * 5 ms).
It operates abnormally if shorter than the certain period.
I think Certain period is one minutes(1000 * 6 ms).
If you need, this is my code.
private BroadcastReceiver gpsReceiver = new BroadcastReceiver() {
private final String GET_GPS = "getGPS";
private final String SET_GPS = "setGPS";
private final String START_GPS = "startGPS";
private final String FINISH_GPS = "finishGPS";
LocationManager locationManager;
double lat;
double lon;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 5;
boolean isGpsMode = false;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra("action");
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
JSONObject obj = new JSONObject();
if(action.equals(GET_GPS)){
if(isGPSOn()){
try {
obj.put("result","gpsOn");
} catch (JSONException e) {
e.printStackTrace();
}
} else{
try {
obj.put("result","gpsOff");
} catch (JSONException e) {
e.printStackTrace();
}
}
}else if(action.equals(SET_GPS)){
Intent settingIntent= new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
settingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(settingIntent);
}else if(action.equals(START_GPS)){
Log.d("GPS", "GPS start");
startCallback();
}else if(action.equals(FINISH_GPS)){
Log.d("GPS", "GPS finish");
stopUsingGPS();
}
if(!(obj.toString().equals("{}"))){
sendScript("javascript:getGPS" + "(" + obj + ")");
}
}
public boolean isGPSOn(){
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public boolean isNetworkOn(){
return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void stopUsingGPS(){
Log.d("GPS", "stopUsingGPS()");
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
}
public void startCallback(){
if(isGPSOn()){
GPSRegistration();
} else if(isNetworkOn()){
NetworkRegistration();
}
}
public boolean GPSRegistration(){
Log.d("GPS", "call location value from GPS");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
isGpsMode = true;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon: " + String.valueOf(lon));
return isAvailableLocation(lat, lon);
}
public void NetworkRegistration(){
Log.d("GPS", "call location value from Network");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
isGpsMode = false;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon: " + String.valueOf(lon));
}
public boolean isAvailableLocation(double lat, double lon){
if(lon>124 && lon<132 && lat>33 && lat<43){
return true;
}
return false;
}
private LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
Log.d("GPS", "onLocationChanged - lat: "+lat+" / lon : "+lon);
if (isAvailableLocation(lat, lon)) {
JSONObject obj = new JSONObject();
try{
obj.put("lat", lat);
obj.put("lon", lon);
}catch( JSONException e){
Log.d("GPS", "onRegistered: JSON exception");
}
sendScript("javascript:sendGPS("+obj+");");
} else {
stopUsingGPS();
if(isGpsMode){
if(isNetworkOn()){
NetworkRegistration();
}
}else{
if(isGPSOn()){
GPSRegistration();
}
}
return;
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
};
};
And I've coded this code in onCreate(),
registerReceiver(gpsReceiver, new IntentFilter("actionName"));
this code in onDestroy().
unregisterReceiver(gpsReceiver);
Then, available through
startIntent(actionName).

android: how to get updated location with gps

I'm making an app to send current location of user via sms after fixed time but it always send the same coordinates. I read lot of links but I don't know where is the mistake kindly tell me what is the problem in my code you can edit the code as u like
public class AlarmReceiver extends BroadcastReceiver implements LocationListener {
long time = 600* 1000;
long distance = 10;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
Location location;
String device_id;
String phoneNo = "+923362243969";
#SuppressLint("NewApi")
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("alarm receiver....");
Intent service = new Intent(context, MyService.class);
context.startService(service);
//Start App On device restart
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent App = new Intent(context, MainActivity.class);
App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(App);
}
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
device_id = tm.getDeviceId(); // returns IMEI number
try {
LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,time,distance, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
location.getLatitude();
location.getLongitude();
String Text = " From GPS: Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude() + " Device Id: " + device_id;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, Text, null, null);
Log.i("Send SMS", "");
this.abortBroadcast();
}
}
}
}
else {
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, time,distance, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
location.getLatitude();
location.getLongitude();
String Text = " From Network: Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude() + " Device Id: " + device_id;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, Text, null, null);
Log.i("Send SMS", "");
this.abortBroadcast();
}
}
}
}
} catch (Exception e) {
Toast.makeText(context, "no connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
This is where you need to get the location. Take Longitude and Latitude variables as public members and updated them in the below event.
double Latitude, Longitude;
#Override
public void onLocationChanged(Location location) {
Longitude = location.getLongitude();
Latitude = location.getLatitude();
}
And while sending a SMS, put Longitude and Latitude variables in place of location.

Unable to get GPS location

I want user location. both network and GPS location. i am getting network location but GPS location is always null. here is the code that i write for that.
public class GetLocation extends Service implements LocationListener {
LocationManager locationManager;
Location networkLocation, gpsLocation;
Intent intentBroadcastLocationUpdate;
boolean gpslocationOn, networklocationOn;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
broadcastLocation();
handler.postDelayed(this, 3000);
}
};
#Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
intentBroadcastLocationUpdate = new Intent("UPDATE_LOCATION");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 1000 * 60 * 1, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 1000 * 60 * 1, this);
networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
networklocationOn = true;
gpslocationOn = true;
broadcastLocation();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler.postDelayed(runnable, 3000);
return START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(),
location.getProvider() + " Location Changed:" + location.getLatitude() + " , "
+ location.getLongitude(), Toast.LENGTH_LONG).show();
};
#Override
public void onProviderDisabled(String arg0) {
Toast.makeText(getApplicationContext(), arg0 + " Disabled", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
if (provider.equals("network")) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 1000 * 60 * 1, this);
}
if (provider.equals("gps")) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 1000 * 60 * 1, this);
}
Toast.makeText(getApplicationContext(), provider + " Enabled", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onDestroy() {
super.onDestroy();
locationManager.removeUpdates(this);
handler.removeCallbacks(runnable);
}
private void broadcastLocation() {
if (gpsLocation == null && networkLocation == null) {
Toast.makeText(getApplicationContext(),
"on create Couldn't get user location", Toast.LENGTH_LONG).show();
intentBroadcastLocationUpdate.putExtra("loc", "Could not retrive location");
sendBroadcast(intentBroadcastLocationUpdate);
} else if (gpsLocation != null) {
intentBroadcastLocationUpdate.putExtra("loc", "GPS:" + gpsLocation.getLatitude() + ","
+ gpsLocation.getLongitude());
sendBroadcast(intentBroadcastLocationUpdate);
} else if (networkLocation != null) {
intentBroadcastLocationUpdate.putExtra("loc", "Net:" + networkLocation.getLatitude() + ","
+ networkLocation.getLongitude());
sendBroadcast(intentBroadcastLocationUpdate);
} else if (gpsLocation != null && networkLocation != null) {
intentBroadcastLocationUpdate.putExtra(
"loc",
"Net:" + networkLocation.getLatitude() + ","
+ networkLocation.getLongitude() + " AND GPS:"+ gpsLocation.getLatitude() + ","
+ gpsLocation.getLongitude());
sendBroadcast(intentBroadcastLocationUpdate);
}
}
}
Can anybody tell me what is wrong that i am doing? why i'm unable to get GPS location? and what is the best practice of getting GPS location?
Add these permissions in your manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Refer this tutorial
public void getMyLocation() {
LocationManager locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
List<String> providers = locationManager.getProviders(true);
Location l = null;
for (int i = 0; i < providers.size(); i++) {
l = locationManager.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
if (l != null) {
latitude = l.getLatitude();
longitude = l.getLongitude();
}
}

Cannot get current location coordinates

I want to get current longitude and latitude as int
So I use this code
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
....Notify
}
if (gps_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
if (network_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
locationManager.removeUpdates(this);
Unfortunately longitude and latitude are always null.
I have all permission needed in the manifest.
How can I fix this issue?
Well this is what i use for location listener
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class LocationUtils implements LocationListener{
Context context;
private String provider;
private LocationManager locationManager;
private String latitude="no value";
private String longitude="no value";
public LocationUtils(Context context) {
this.context=context;
// Get the location manager
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
latitude="no value";
longitude="no value";
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
/*Toast.makeText(context, "Provider " + provider + " has been selected.",
Toast.LENGTH_SHORT).show();*/
// System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
/*Toast.makeText(context, "Location not available",
Toast.LENGTH_SHORT).show();*/
}
}
#Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latitude = lat + "";
longitude = lng + "";
/* Toast.makeText(context, " lat: "+lat +" Long:"+lng,
Toast.LENGTH_SHORT).show(); */
}
#Override
public void onProviderDisabled(String provider) {
//Toast.makeText(context, "Disabled provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
//Toast.makeText(context, "Enabled new provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
}
Now in your activity u can get
LocationUtils appLocationManager = new LocationUtils(getContext());
String latitude = appLocationManager.getLatitude();
String longitude = appLocationManager.getLongitude();
Also add
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
in your manifest file
First check the GPS enabled in your device.
Check all the permissions included in the manifest
You are fetching the last known location using the GPS provider so remove that line and fetch the location individually for both the provider(There should be possible that your GPS is not available at that time so you did not get the location and you are fetching the last known location using the GPS so it can be null and if location will be null then it will not goes inside the conditions like if(network_enabled) and if(gps_enabled).).
In short check the Last known location of GPS if it is null then try to get the location using the Location provider and use that location.
public class SMS_Service extends Service {
private final String LOGTAG = "SMS_Service";
String latLongString;
String addressString;
double altitude;
int LAC;
int mcc = 0;
int mnc = 0;
String pn_no;
Altitude_Details ld = new Altitude_Details();
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.e(LOGTAG, "created");
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e(LOGTAG, "destroyed");
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e(LOGTAG, "started");
SmsManager sms = SmsManager.getDefault();
// get phone number from shared preference
SharedPreferences default1 = getSharedPreferences("Device",
MODE_WORLD_WRITEABLE);
pn_no = default1.getString("Phone_NO", "");
Log.e("phone_no in sms service", pn_no);
String From = intent.getStringExtra("From");
String Msg = intent.getStringExtra("Msg"); // get message from intent
Log.e("ON start:", "" + From);
Log.e("ON start:", "" + Msg);
String number = From.substring(7, 11);
Log.e("ON start: SUBSTRING", "" + number);
// check msg for Location keyword match or not
if (Msg.equals("LOCATION") && pn_no.equals(number)) {
Log.e("location:", "Location found");
TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tel.getNetworkOperator();
// find MNC and MCC
if (networkOperator != null) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
mnc = Integer.parseInt(networkOperator.substring(3));
Log.e("MCC", "" + mcc);
Log.e("MNC", "" + mnc);
}
// find LAC for GSM
if (tel.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
final GsmCellLocation location = (GsmCellLocation) tel
.getCellLocation();
if (location != null) {
LAC = location.getLac();
Log.e("cell location", "LAC: " + location.getLac()
+ " CID: " + location.getCid());
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
// update method return latest location
updateWithNewLocation(location);
// location change then listner called
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
// send mcc,mnc,latitude,longitude,altitude,address,Link in message
String Url = "http://itouchmap.com/latlong.html";
sms.sendTextMessage(pn_no, null, "\nLocation:\n" + "MCC: " + mcc
+ "\nMNC: " + mnc + "\nLAC:" + LAC + latLongString
+ "\nAltitude:" + altitude + "feet"
+ "\nGo to Below site:\n" + Url, null, null);
sms.sendTextMessage(pn_no, null, "\nAddress:\n" + addressString,
null, null);
// stop service automatically
SMS_Service.this.stopSelf();
}
else {
Log.e("loation:", "Location not found");
SMS_Service.this.stopSelf();
}
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
// TODO Auto-generated method stub
addressString = "\nno address found";
// check location get or not from provider
if (location != null) {
// get latitude and longitude
double latitude = location.getLatitude();
double longitude = location.getLongitude();
latLongString = "\nLat:" + latitude + "\nLong:" + longitude;
Log.e("location", "" + latLongString);
// get altitude from method
altitude = ld.getElevationFromGoogleMaps(latitude, longitude);
Log.e("Altitude", "" + altitude);
// find address from latitude and longitude
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude,
longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
}
addressString = sb.toString();
Log.e("Address", "" + addressString);
} catch (IOException e) {
}
} else {
latLongString = "\n No location found";
Log.e("location", "" + latLongString);
}
}
}
hey you can make the service and use this code to get altitude and latitude and decode this using class
Try This code
double longitude,latitude;
int lon,lat;
getcurrentloc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(GpsLocationFinder.this, "Enable Your GPS", Toast.LENGTH_LONG).show();
}else{
LocationResult locationResult=new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
longitude=location.getLongitude();
latitude=location.getLatitude();
lon=(int)longitude;
lat=(int)latitude;
Toast.makeText(GpsLocationFinder.this, "Current Longitude"+longitude+" Current Latitude"+latitude,Toast.LENGTH_LONG).show();
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(GpsLocationFinder.this, locationResult);
}
}
});
And the MyLocation Class is Below
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
double longitude,latitude;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
//Log.e("GPS DISTANCE","GPS Enabled");
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
//don't start listeners if no provider is enabled
//try{
try{
gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){
}
try{
network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){
}
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 100, locationListenerGps);
}
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 30000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}

How do I switch between GPS and Network provider?

In my app, I wanna use both location provider.
That means, if the gps is disabled I want my app to switch to network, and when gps is enabled to switch back it.
I'm using two LocationListener to handle those two requests.
public void onStatusChanged(String provider, int status,Bundle extras)
switch (status) {
case LocationProvider.TEMPORARILY_UNAVAILABLE:
......
break;
case LocationProvider.OUT_OF_SERVICE
.....
break;
case LocationProvider.AVAILABLE
.....
break;
}
And in the each listener ,I detect those status in the onStatusChanged().
It turns out, this method will be used in the first change(disabled network),but when I enable the network again, it shows nothing.Why was that? The listener won't detect the status all the time??
Please help me, it would be best to post you solution in code...Thanks!
This is what I do:
public class LocationActivity extends Activity implements LocationListener{
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
private TextView outputField;
private Location location;
private ScrollView scrollView;
private Criteria criteria;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
latituteField = (TextView) findViewById(R.id.lat_textView);
longitudeField = (TextView) findViewById(R.id.long_textView);
outputField = (TextView) findViewById(R.id.output_textView);
scrollView = (ScrollView) findViewById(R.id.scrollView1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
List<String> providers = locationManager.getProviders(criteria, true);
outputField.append("Providers available..." + "\n");
for (String provider : providers) {
outputField.append(provider + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 400, 1, this);
if (provider != null) {
outputField.append("Provider " + provider + " has been selected." + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
if (location != null) {
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
} else {
outputField.append("No provider selected" + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
double lat =location.getLatitude();
double lng =location.getLongitude();
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
outputField.append("New Location: " + String.valueOf(lat) + " " + String.valueOf(lng) + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
#Override
public void onProviderDisabled(String dProvider) {
outputField.append("Provider " + dProvider + " has been disabled." + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 400, 1, this);
if (provider != null) {
outputField.append("Provider " + provider + " has been selected." + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
if (location != null) {
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
} else {
outputField.append("No provider selected" + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
}
#Override
public void onProviderEnabled(String eProvider) {
outputField.append("Provider " + eProvider + " has been enabled." + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 400, 1, this);
if (provider != null) {
outputField.append("Provider " + provider + " has been selected." + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
if (location != null) {
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
} else {
outputField.append("No provider selected" + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
outputField.append("Provider " + provider + " status changed to: " + Integer.toString(status) + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
}
Your answer is here What is the simplest and most robust way to get the user's current location in Android?. In this Fedor nicely explained with example of how to switching between location provider.
Thanks.

Categories

Resources