connection to aspx page from android? - android

I have developed an application get location but i need to save it to server using aspx webpage.
I have created tables on the webpage and i need to save these lat,long to the webpagepage using the unique id as imei?
I have created a table with imei, latlong, datetime
aspx name /http://Log.aspx/
can anybody help me please I have searched many but I couldn't understand.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
// initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// check if GPS is enabled
// else switch on gps
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Intent intent = new Intent(
"android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
}
else {
// get a location provider from location manager
// empty criteria searches through all providers and returns the
// best one
String providerName = manager.getBestProvider(new Criteria(),
true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView) findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
Intent intent = new Intent(
"android.location.GPS_ENABLED_CHANGE");
intent.putExtra("disabled", false);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
}
else {
// get cell id
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
.getCellLocation();
String networkOperator = mTelephonyManager
.getNetworkOperator();
Log.d("CID", Integer.toString(loc.getCid()));
Log.d("LAC", Integer.toString(loc.getLac()));
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
TextView tv1 = (TextView) findViewById(R.id.locationResults);
if (loc != null) {
tv.setText("Cell ID: " + loc.getCid() + " , " + "Lac: "
+ loc.getLac() + "mcc : " + mcc + "mnc : "
+ mnc);
// to write it to file
appendData("Cell ID: " + loc.getCid() + " , " + "Lac: "
+ loc.getLac() + "mcc : " + mcc + "mnc : "
+ mnc);
}
}
manager.requestLocationUpdates(providerName, 1000 * 60 * 15, 0,
this);
}
}
}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
// sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt(((lat - curStatLat) * (lat - curStatLat))
+ ((lon - curStatLon) * (lon - curStatLon)));
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView) findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
// to write the file..
appendData(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting gps NETWORK ID : ");
}
}

I wrote a WS few months back like this:
<%# WebService Language="VBScript" Class="DataIns" %>
Imports System
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Data
Imports System.Globalization
<WebService(Namespace:="http://www.mysite.org/webservices/")> Public Class DataIns :Inherits WebService
<WebMethod()> Public Function devIns (ByVal dm As String) As String
Dim strArr() As String
Dim rtnVal As String
strArr = dm.split("^")
Dim connection As SqlConnection
Dim connection1 As SqlConnection
Dim connection2 As SqlConnection
Dim cmd As SqlCommand
Dim connectionString As String
connectionString = ConfigurationManager.ConnectionStrings("sqlsds").ConnectionString
connection = New SqlConnection(connectionString)
Dim cmdtrans As SqlCommand
Dim cmdCheck As SqlCommand
Dim result as String
Dim sqltrans as String
Dim notes as String
Dim notes1 As String
sqltrans= "select dbo.fnCheckBlackList(#p_imei)"
cmdtrans=new sqlcommand(sqltrans,connection)
cmdtrans.Parameters.AddWithValue("#p_imei",strArr(0))
Try
connection.Open()
notes=cmdtrans.ExecuteScalar()
Catch ex As Exception
notes = ex.Message
Finally
connection.Close()
End Try
notes = If(IsDBNull(notes),"","")
if notes.Trim().Equals("TIMEUP") then
Context.Response.Output.Write("Save Completed Wipeout")
Context.Response.End()
return string.Empty
else
connection1 = New SqlConnection(connectionString)
result = "select dbo.fnCheckImeiDateWise(#p_imei)"
cmdCheck=new sqlcommand(result,connection1)
cmdCheck.Parameters.AddWithValue("#p_imei",strArr(0))
Try
connection1.Open()
notes1=cmdCheck.ExecuteScalar()
Catch ex As Exception
notes1 = ex.Message
Finally
connection1.close()
End Try
if notes1.Trim().Equals("FINE") then
connection2 = New SqlConnection(connectionString)
cmd = New SqlCommand("dbo.spInsertDeviceData", connection2)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#p_imei", strArr(0))
cmd.Parameters.AddWithValue("#p_location", strArr(1))
cmd.Parameters.AddWithValue("#p_aic", Integer.Parse(strArr(2)))
cmd.Parameters.AddWithValue("#p_adc", Integer.Parse(strArr(3)))
cmd.Parameters.AddWithValue("#p_ail", strArr(4))
cmd.Parameters.AddWithValue("#p_adl", strArr(5))
cmd.Parameters.AddWithValue("#p_tsss", Double.Parse(strArr(6)))
cmd.Parameters.AddWithValue("#p_ts", Double.Parse(strArr(7)))
cmd.Parameters.AddWithValue("#p_tsgp", Double.Parse(strArr(8)))
cmd.Parameters.AddWithValue("#p_tvpc", Double.Parse(strArr(9)))
Try
connection2.Open()
rtnVal = cmd.ExecuteNonQuery()
Catch ex As Exception
rtnVal = ex.Message
Finally
connection2.Close()
End Try
'Context.Response.Output.Write(rtnVal)
Dim parameterString As String
Dim dow2 As String
parameterString = ConfigurationManager.AppSettings("FREQUENCY")
parameterString = parameterString + "|"
parameterString = parameterString + getNewTime(ConfigurationManager.AppSettings("UPDATEAT1"))
parameterString = parameterString + "|"
parameterString = parameterString + ConfigurationManager.AppSettings("DAYOFWEEK1")
dow2 = ConfigurationManager.AppSettings("DAYOFWEEK2")
if String.IsNullOrEmpty(dow2) then
else
parameterString = parameterString +"*"
parameterString = parameterString + dow2
end if
parameterString = parameterString + "|"
parameterString = parameterString + ConfigurationManager.AppSettings("DAYOFMONTH")
Context.Response.Output.Write("Save Completed" + "|"+ parameterString)
Context.Response.End()
return string.Empty
else
Context.Response.Output.Write("ERROR")
Context.Response.End()
return string.Empty
End If
End If
end function
end class
and this was called like
http://www.mysite.org/DataIns.asmx/dIns?dm=<data-separated=by-^>

Related

How to find location name from given lattitude & longitude?

I am trying to get location name or address. I have successfully fetched the latitude and longitude by Google Fused Location API.
Now I want to fetch the location address (example : City name,Road no, or specific address) by using the latitude and longitude.
For this purpose I am using Google Geocoder and it works fine. But in some devices the location address returns the null value.
I searched in the net for the solution of this problem and found that some device manufacturers does not include this feature in their devices. That's why those device can't find the the address by Reverse Geocoding method. Here is the link of that information
So is there any alternative way to find the address name as string without Geoconding ?
Here is my code for fetching address by Geocoding
public static void getAddress(Context context, double LATITUDE, double LONGITUDE) {
try {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
Log.d(TAG, "getAddress: address" + address);
Log.d(TAG, "getAddress: city" + city);
Log.d(TAG, "getAddress: state" + state);
Log.d(TAG, "getAddress: postalCode" + postalCode);
Log.d(TAG, "getAddress: knownName" + knownName);
}
} catch (IOException e) {
e.printStackTrace();
}
return;
}
Use this its working for me
public class LocationAddress {
private static final String TAG = "LocationAddress";
private static String area = null;
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");
}
area = address.getSubLocality();
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);
bundle.putString("area",area);
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);
bundle.putString("area",area);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
To call this in your Activity use
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(latitude,longitude,
getApplicationContext(), new GeocoderHandler());
GeocoderHandler
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String locationAddress = null;
String area = null;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
area = bundle.getString("area");
break;
default:
locationAddress = null;
}
if(locationAddress != null)
locationAddress=locationAddress.replaceAll("[\r\n]+", " ");
Log.d("===========>>>",area);
Log.d("===========>>>>",locationAddress);
}
}

Get location name from fetched coordinates get the name

I have found this solution: here to get the location name but I don't know how to display it in my textView:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if(null!=locations && null!=providerList && providerList.size()>0){
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
String _Location = listAddresses.get(0).getAddressLine(0);
}
} catch (IOException e) {
e.printStackTrace();
t.append("\n " + ????? + " ");
}
}
The t is the textView
You have the name address in the String _Location. Therefore, you could set the value of TextView in the try block.
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
String _Location = listAddresses.get(0).getAddressLine(0);
}
t.setText(_Location);
}
Further Infomation
String address1 = listAddresses.get(0).getAddressLine(0);
String city = listAddresses.get(0).getLocality();
String state = listAddresses.get(0).getAdminArea();
String country = listAddresses.get(0).getCountryName();
String postalCode = listAddresses.get(0).getPostalCode();
String knownName = listAddresses.get(0).getFeatureName();
t.setText(address1 + " " + city + "\n" + state + " " + postalCode);
You could use this code to get further information about the adress

Gsm network info in android

Does someone know how to get gsm information in android? Information like BCCH (Broadcast Control Channel) and BCIS (Base Station Identity Code). I already got the LAC (Location Area Code) and CID (Cell ID). I know that is a low level information but does someone know to get those information? I am having a hard time researching and i don't have an idea about cellular network. Please Help thanks :)
Here is function which gives you complete information of gsm network.
just Call with context from your activity
private void getNWInfo(Context context) {
/**
* <uses-permission android:name="android.permission.READ_PHONE_STATE"
* /> <uses-permission
* android:name="android.permission.ACCESS_NETWORK_STATE"/>
*/
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = telephonyManager.getNetworkOperator();
int mcc = 0, mnc = 0;
if (networkOperator != null) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
mnc = Integer.parseInt(networkOperator.substring(3));
}
String SimNumber = telephonyManager.getLine1Number();
String SimSerialNumber = telephonyManager.getSimSerialNumber();
String countryISO = telephonyManager.getSimCountryIso();
String operatorName = telephonyManager.getSimOperatorName();
String operator = telephonyManager.getSimOperator();
int simState = telephonyManager.getSimState();
String voicemailNumer = telephonyManager.getVoiceMailNumber();
String voicemailAlphaTag = telephonyManager.getVoiceMailAlphaTag();
// Getting connected network iso country code
String networkCountry = telephonyManager.getNetworkCountryIso();
// Getting the connected network operator ID
String networkOperatorId = telephonyManager.getNetworkOperator();
// Getting the connected network operator name
String networkName = telephonyManager.getNetworkOperatorName();
int networkType = telephonyManager.getNetworkType();
String network = "";
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
if (cm.getActiveNetworkInfo().getTypeName().equals("MOBILE"))
network = "Cell Network/3G";
else if (cm.getActiveNetworkInfo().getTypeName().equals("WIFI"))
network = "WiFi";
else
network = "N/A";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("network :" + network +
"\n" + "countryISO : " + countryISO + "\n" + "operatorName : "
+ operatorName + "\n" + "operator : " + operator + "\n"
+ "simState :" + simState + "\n" + "Sim Serial Number : "
+ SimSerialNumber + "\n" + "Sim Number : " + SimNumber + "\n"
+ "Voice Mail Numer" + voicemailNumer + "\n"
+ "Voice Mail Alpha Tag" + voicemailAlphaTag + "\n"
+ "Sim State" + simState + "\n" + "Mobile Country Code MCC : "
+ mcc + "\n" + "Mobile Network Code MNC : " + mnc + "\n"
+ "Network Country : " + networkCountry + "\n"
+ "Network OperatorId : " + networkOperatorId + "\n"
+ "Network Name : " + networkName + "\n" + "Network Type : "
+ networkType);
}
you can find more details on this blog
http://khurramitdeveloper.blogspot.in/search?updated-max=2013-11-07T03:23:00-08:00&max-results=7
hope it will help you :)
Please visit here. It explains that no APIs are available to get the Radio Information.
You can try this:
public static JSONArray getCellInfo(Context ctx){
TelephonyManager tel = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
JSONArray cellList = new JSONArray();
int phoneTypeInt = tel.getPhoneType();
String phoneType = "unknown";
if (phoneTypeInt == TelephonyManager.PHONE_TYPE_GSM)
phoneType = "gsm";
else if (phoneTypeInt == TelephonyManager.PHONE_TYPE_CDMA)
phoneType = "cdma";
//from Android M up must use getAllCellInfo
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
List<NeighboringCellInfo> neighCells = tel.getNeighboringCellInfo();
for (int i = 0; i < neighCells.size(); i++) {
try {
JSONObject cellObj = new JSONObject();
NeighboringCellInfo thisCell = neighCells.get(i);
cellObj.put("cellId", thisCell.getCid());
cellObj.put("lac", thisCell.getLac());
cellObj.put("rssi", thisCell.getRssi());
cellList.put(cellObj);
} catch (Exception e) {
}
}
} else {
List<CellInfo> infos = tel.getAllCellInfo();
for (int i = 0; i < infos.size(); ++i) {
try {
JSONObject cellObj = new JSONObject();
CellInfo info = infos.get(i);
if (info instanceof CellInfoGsm) {
CellSignalStrengthGsm gsm = ((CellInfoGsm) info).getCellSignalStrength();
CellIdentityGsm identityGsm = ((CellInfoGsm) info).getCellIdentity();
cellObj.put("cellId", identityGsm.getCid());
cellObj.put("lac", identityGsm.getLac());
cellObj.put("dbm", gsm.getDbm());
cellList.put(cellObj);
} else if (info instanceof CellInfoLte) {
CellSignalStrengthLte lte = ((CellInfoLte) info).getCellSignalStrength();
CellIdentityLte identityLte = ((CellInfoLte) info).getCellIdentity();
cellObj.put("cellId", identityLte.getCi());
cellObj.put("tac", identityLte.getTac());
cellObj.put("dbm", lte.getDbm());
cellList.put(cellObj);
}
} catch (Exception ex) {
}
}
}
return cellList;
}

How to get location update for every half an hour android?

hi i have developed an android application for getting location and sending it to server it is working good but location update is not working it is currently running once i have to get location and send to server once in half an hour, and this process should run only for 9 hrs to 17 hrs how can i do it pls help me..!
my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String providerName = manager.getBestProvider(new Criteria(),
true);
Location location = manager.getLastKnownLocation(providerName);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
.getCellLocation();
String networkOperator = mTelephonyManager
.getNetworkOperator();
Log.d("CID", Integer.toString(loc.getCid()));
Log.d("LAC", Integer.toString(loc.getLac()));
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
TextView tv1 = (TextView) findViewById(R.id.locationResults);
if (loc != null) {
tv1.setText("Cell ID: " + loc.getCid() + " , "
+ "Lac: " + loc.getLac() + "mcc : " + mcc
+ "mnc : " + mnc);
}
// manager.requestLocationUpdates(providerName, 1000 * 60 *
// 2, 0,this);
}
}
else {
String providerName = manager.getBestProvider(new Criteria(),
true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView) findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
String imei = telephonyManager.getDeviceId();
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyyMMdd_HHmmss");
String cdt = sdf.format(new Date());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String lat = Double.toString(latitude);
String lon = Double.toString(longitude);
String locations = Double.toString(latitude) + ","
+ Double.toString(longitude);
// manager.requestLocationUpdates(providerName, 1000 * 60 *
// 2, 0,this);
}
else {
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
.getCellLocation();
String networkOperator = mTelephonyManager
.getNetworkOperator();
Log.d("CID", Integer.toString(loc.getCid()));
Log.d("LAC", Integer.toString(loc.getLac()));
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
// TextView tv1 = (TextView)
// findViewById(R.id.locationResults);
if (loc != null) {
tv.setText("Cell ID: " + loc.getCid() + " , " + "Lac: "
+ loc.getLac() + "mcc : " + mcc + "mnc : "
+ mnc);
}
}
manager.requestLocationUpdates(providerName, 1000 * 60 * 10, 1,
this);
}
}
}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
// sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt(((lat - curStatLat) * (lat - curStatLat))
+ ((lon - curStatLon) * (lon - curStatLon)));
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView) findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting gps NETWORK ID : ");
}
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
You can use requestLocationUpdates of LocationManager Class
requestLocationUpdates (long minTime, float minDistance, Criteria
criteria, PendingIntent intent)
So, the first param you can specify as 30 mins according to your requirement.
To keep track of hours elapsed, you can have something like :
var1 = System.CurrentTimeMillis(); //Get time when service started
In onLocationChanged()
var2 = System.CurrentTimeMillis();
Now calculate var2-var1 to get elapsed time. if >17 hrs, removeUpdates from locationManager
I have a similar project going on, I am using a Service for this, fired by an AlarmManager.
Check here for more info.
The approach provided by Schaemelhout and the approach taken by library referred to in the comments is the only workable solution I have found.
Using an AlarmManager to wake your service guarantees the service is periodically invoked/restarted. This serves to counteract any power saving actions that the OS/phone might hit your service with in the mean time.
Registering a location listener from your alarm BroadcastReceiver wakes up the GPS (the GPS would not normally be running if the phone is asleep). In your alarm BroadcastReceiver you will need to take and hold a WakeLock and stay awake until results are passed back to the listener.
The down side to this approach is that it takes a while for a location to be available and the accuracy may be bad. Your service might have to wait a while until acceptable accuracy is achieved (the Location accuracy value can be wrong, so it might be be best to wait for a few samples). The whole approach will need to be tuned to your required update frequency and accuracy requirements. If you need very frequent and accurate updates I suspect holding a wake-lock and keeping the GPS alive might be the only way to go.
I also tried using the lm.requestLocationUpdates() using a PendingIntent. This did faithfully wake up my service and pass it an Intent, but if the GPS was sleeping prior to the wake up the Intent lacked a location.

Get location name from fetched coordinates

What i have: currently my app is only telling me the coordinates of my current location.
What i want: Get location name from coordinates fetched by gps, so that i could know where exactly i am. (Name of location)
Here is complete code from fetching long - lat to getting address:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if(null!=locations && null!=providerList && providerList.size()>0){
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
String _Location = listAddresses.get(0).getAddressLine(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can us the GeoCoder which is available in android.location.Geocoder package. The JavaDocs gives u full explaination. The possible sample for u.
List<Address> list = geoCoder.getFromLocation(location
.getLatitude(), location.getLongitude(), 1);
if (list != null & list.size() > 0) {
Address address = list.get(0);
result = address.getLocality();
return result;
The result will return the name of the location.
Here i am given a single just pass the latitude and longitude in this function then you got all the information related to this latitude and longitude.
public void getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
GUIStatics.currentAddress = obj.getSubAdminArea() + ","
+ obj.getAdminArea();
GUIStatics.latitude = obj.getLatitude();
GUIStatics.longitude = obj.getLongitude();
GUIStatics.currentCity= obj.getSubAdminArea();
GUIStatics.currentState= obj.getAdminArea();
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
Log.v("IGA", "Address" + add);
// Toast.makeText(this, "Address=>" + add,
// Toast.LENGTH_SHORT).show();
// TennisAppActivity.showDialog(add);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
I hope you get the solution to your answer.

Categories

Resources