UPDATED AT BOTTOM
I have written an application that logs the users position, current speed, average speed and top speed. I would like to know how to make the application do the following things:
prevent the screen from turning off while it is open on the screen
if the user opens another app or returns to the home screen, gets a call etc, the app should keep collecting data
(or would it be better to just write all data to a database everytime the location is updated? and maybe have a button to signify when to start and stop collecting data?)
here is the code that I have written. (feel free to use it if you want and if you have any recommendations on how I might improve it I am very open to constructive criticism :D )
package Hartford.gps;
import java.math.BigDecimal;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
public class GPSMain extends Activity implements LocationListener {
LocationManager locationManager;
LocationListener locationListener;
//text views to display latitude and longitude
TextView latituteField;
TextView longitudeField;
TextView currentSpeedField;
TextView kmphSpeedField;
TextView avgSpeedField;
TextView avgKmphField;
//objects to store positional information
protected double lat;
protected double lon;
//objects to store values for current and average speed
protected double currentSpeed;
protected double kmphSpeed;
protected double avgSpeed;
protected double avgKmph;
protected double totalSpeed;
protected double totalKmph;
//counter that is incremented every time a new position is received, used to calculate average speed
int counter = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
run();
}
#Override
public void onResume() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, this);
super.onResume();
}
#Override
public void onPause() {
locationManager.removeUpdates(this);
super.onPause();
}
private void run(){
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setSpeedRequired(true);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
//Acquire a reference to the system Location Manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location newLocation) {
counter++;
//current speed fo the gps device
currentSpeed = round(newLocation.getSpeed(),3,BigDecimal.ROUND_HALF_UP);
kmphSpeed = round((currentSpeed*3.6),3,BigDecimal.ROUND_HALF_UP);
//all speeds added together
totalSpeed = totalSpeed + currentSpeed;
totalKmph = totalKmph + kmphSpeed;
//calculates average speed
avgSpeed = round(totalSpeed/counter,3,BigDecimal.ROUND_HALF_UP);
avgKmph = round(totalKmph/counter,3,BigDecimal.ROUND_HALF_UP);
//gets position
lat = round(((double) (newLocation.getLatitude())),3,BigDecimal.ROUND_HALF_UP);
lon = round(((double) (newLocation.getLongitude())),3,BigDecimal.ROUND_HALF_UP);
latituteField = (TextView) findViewById(R.id.lat);
longitudeField = (TextView) findViewById(R.id.lon);
currentSpeedField = (TextView) findViewById(R.id.speed);
kmphSpeedField = (TextView) findViewById(R.id.kmph);
avgSpeedField = (TextView) findViewById(R.id.avgspeed);
avgKmphField = (TextView) findViewById(R.id.avgkmph);
latituteField.setText("Current Latitude: "+String.valueOf(lat));
longitudeField.setText("Current Longitude: "+String.valueOf(lon));
currentSpeedField.setText("Current Speed (m/s): "+String.valueOf(currentSpeed));
kmphSpeedField.setText("Cuttent Speed (kmph): "+String.valueOf(kmphSpeed));
avgSpeedField.setText("Average Speed (m/s): "+String.valueOf(avgSpeed));
avgKmphField.setText("Average Speed (kmph): "+String.valueOf(avgKmph));
}
//not entirely sure what these do yet
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener);
}
//Method to round the doubles to a max of 3 decimal places
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
#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
}
}
BOTH PROBLEMS SOLVED THANKS TO ANSWERS FROM Marco Grassi AND Marcovena.
New Code:
package Hartford.gps;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.widget.TextView;
public class GPSMain extends Activity {
//text views to display latitude and longitude
static TextView latituteField;
static TextView longitudeField;
static TextView currentSpeedField;
static TextView kmphSpeedField;
static TextView avgSpeedField;
static TextView avgKmphField;
static TextView topSpeedField;
static TextView topKmphField;
//objects to store positional information
protected static double lat;
protected static double lon;
//objects to store values for current and average speed
protected static double currentSpeed;
protected static double kmphSpeed;
protected static double avgSpeed;
protected static double avgKmph;
protected static double totalSpeed;
protected static double totalKmph;
protected static double topSpeed=0;
protected static double topKmph=0;
//counter that is incremented every time a new position is received, used to calculate average speed
static int counter = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wL = powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,"My Tag");
wL.acquire();
startService(new Intent(this, Calculations.class));
latituteField = (TextView) findViewById(R.id.lat);
longitudeField = (TextView) findViewById(R.id.lon);
currentSpeedField = (TextView) findViewById(R.id.speed);
kmphSpeedField = (TextView) findViewById(R.id.kmph);
avgSpeedField = (TextView) findViewById(R.id.avgspeed);
avgKmphField = (TextView) findViewById(R.id.avgkmph);
topSpeedField = (TextView) findViewById(R.id.topspeed);
topKmphField = (TextView) findViewById(R.id.topkmph);
}
static void run(){
latituteField.setText("Current Latitude: "+String.valueOf(lat));
longitudeField.setText("Current Longitude: "+String.valueOf(lon));
currentSpeedField.setText("Current Speed (m/s): "+String.valueOf(currentSpeed));
kmphSpeedField.setText("Cuttent Speed (kmph): "+String.valueOf(kmphSpeed));
avgSpeedField.setText("Average Speed (m/s): "+String.valueOf(avgSpeed));
avgKmphField.setText("Average Speed (kmph): "+String.valueOf(avgKmph));
topSpeedField.setText("Top Speed (m/s): "+String.valueOf(topSpeed));
topKmphField.setText("Top Speed (kmph): "+String.valueOf(topKmph));
}
}
and
package Hartford.gps;
import java.math.BigDecimal;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class Calculations extends Service implements LocationListener {
static LocationManager locationManager;
LocationListener locationListener;
private static final String TAG = "Calculations";
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
run();
}
private void run(){
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setSpeedRequired(true);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
//Acquire a reference to the system Location Manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location newLocation) {
GPSMain.counter++;
//current speed for the GPS device
GPSMain.currentSpeed = round(newLocation.getSpeed(),3,BigDecimal.ROUND_HALF_UP);
GPSMain.kmphSpeed = round((GPSMain.currentSpeed*3.6),3,BigDecimal.ROUND_HALF_UP);
if (GPSMain.currentSpeed>GPSMain.topSpeed) {
GPSMain.topSpeed=GPSMain.currentSpeed;
}
if (GPSMain.kmphSpeed>GPSMain.topKmph) {
GPSMain.topKmph=GPSMain.kmphSpeed;
}
//all speeds added together
GPSMain.totalSpeed = GPSMain.totalSpeed + GPSMain.currentSpeed;
GPSMain.totalKmph = GPSMain.totalKmph + GPSMain.kmphSpeed;
//calculates average speed
GPSMain.avgSpeed = round(GPSMain.totalSpeed/GPSMain.counter,3,BigDecimal.ROUND_HALF_UP);
GPSMain.avgKmph = round(GPSMain.totalKmph/GPSMain.counter,3,BigDecimal.ROUND_HALF_UP);
//gets position
GPSMain.lat = round(((double) (newLocation.getLatitude())),3,BigDecimal.ROUND_HALF_UP);
GPSMain.lon = round(((double) (newLocation.getLongitude())),3,BigDecimal.ROUND_HALF_UP);
GPSMain.run();
}
//not entirely sure what these do yet
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener);
}
//Method to round the doubles to a max of 3 decimal places
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
UPDATE FOR shababhsiddique
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class Calculations extends Service{
static LocationManager locationManager;
static LocationListener locationListener;
private static long timerTime = 1;
private static float timerFloatValue = 1.0f;
private Context context;
private int counter = 0;
#Override
public IBinder onBind(Intent intent) {return null;}
#Override
public void onCreate() {
context = this;
update();
}
protected void update(){
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setSpeedRequired(true);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
//Acquire a reference to the system Location Manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location newLocation) {
counter++;
if(GPSMain.GPSHasStarted==0){
GPSMain.previousLocation = newLocation;
//gets position
GPSMain.lat = round(((double) (GPSMain.previousLocation.getLatitude())),3,BigDecimal.ROUND_HALF_UP);
GPSMain.lon = round(((double) (GPSMain.previousLocation.getLongitude())),3,BigDecimal.ROUND_HALF_UP);
GPSMain.startingLocation = GPSMain.previousLocation;
GPSMain.routeLat.add(Double.toString(GPSMain.startingLocation.getLatitude()));
GPSMain.routeLon.add(Double.toString(GPSMain.startingLocation.getLongitude()));
GPSMain.startTime = System.currentTimeMillis();
GPSMain.GPSHasStarted++;
Toast.makeText(context, "GPS Connection Established", Toast.LENGTH_LONG).show();
startService(new Intent(context, AccelerometerReader.class));
Toast.makeText(context, "Accelerometer Calculating", Toast.LENGTH_LONG).show();
Toast.makeText(context, "Have A Safe Trip!", Toast.LENGTH_LONG).show();
}
//gets position
GPSMain.lat = round(((double) (newLocation.getLatitude())),3,BigDecimal.ROUND_HALF_UP);
GPSMain.lon = round(((double) (newLocation.getLongitude())),3,BigDecimal.ROUND_HALF_UP);
if (newLocation.distanceTo(GPSMain.previousLocation)>2.0f){
GPSMain.distanceBetweenPoints = GPSMain.distanceBetweenPoints + newLocation.distanceTo(GPSMain.previousLocation);
}
//current speed for the GPS device
GPSMain.mpsSpeed = newLocation.getSpeed();
if (GPSMain.mpsSpeed>GPSMain.topMps) {GPSMain.topMps=GPSMain.mpsSpeed;}
//store location in order to calculate distance during next iteration.
GPSMain.previousLocation = newLocation;
if (counter % 20 == 0){
GPSMain.routeLat.add(Double.toString(GPSMain.previousLocation.getLatitude()));
GPSMain.routeLon.add(Double.toString(GPSMain.previousLocation.getLongitude()));
}
}
//not entirely sure what these do yet
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 20, locationListener);
}
//Method to round the doubles to a max of 3 decimal places
public static double round(double unrounded, int precision, int roundingMode){
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
//formats the time taken in milliseconds into hours minutes and seconds
public static String getTimeTaken(long end, long start){
#SuppressWarnings("unused")
String formattedTime = "", hourHour = "", hourMin = ":", minSec = ":";
long timeTaken = end-start, hour = 0, min = 0, sec = 0;
timerTime = timeTaken;
timeTaken = (end-start)/1000;
if (timeTaken>9 ){
hourHour = "0";
hourMin = ":0";
if (timeTaken>=60){
if (timeTaken>= 3200){
hour = timeTaken/3200;
timeTaken = timeTaken%3200;
if (hour>9){
hourHour = "";
}
}
min = timeTaken/60;
timeTaken = timeTaken%60;
if (min >9){
hourMin = ":";
}
}
sec = timeTaken;
if(sec%60<10){
minSec = ":0";
}
return formattedTime = (hourHour+hour+hourMin+min+minSec+sec);
}
sec = timeTaken;
minSec = ":0";
hourMin = ":0";
hourHour = "0";
return formattedTime = (hourHour+hour+hourMin+min+minSec+sec);
}
public static double averageSpeed(){
//calculates average speed
if (timerTime==0){timerTime=1;}
timerFloatValue = (float) timerTime;
timerFloatValue = timerFloatValue/1000;
return GPSMain.avgMps = GPSMain.distanceBetweenPoints/timerFloatValue;
}
//rounds the float values from the accelerometer
static String roundTwoDecimalFloat(float a){
float b = a/9.8f;
String formattedNum;
NumberFormat nf = new DecimalFormat();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
formattedNum = nf.format(b);
return formattedNum;
}
}
Question 1: You must acquire a WakeLock . There are multiple types of wakelock, depending if you want only the cpu on or also the screen.
Question 2: You should do your collecting data stuff inside a Service and separate the graphical interface from the collecting data. The Service will continue to collect the data until you stop it if you implement it correctly.
Related
I'm working on an Android app which gets your current location upon clicking a button, and then prints it if you click another button.
Now, I've got all of the code done, yet I'm stuck into how to retrieve the info of the longitude and latitude to print it, because I earn it on another function.
I'll post my code below to explain what I mean in a clearer manner:
package com.example.geolocation;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener, LocationListener {
private LocationManager locationManager;
public String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button)findViewById(R.id.start);
start.setOnClickListener(this);
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(this);
Button show = (Button)findViewById(R.id.show);
show.setOnClickListener(this);
TextView location = (TextView)findViewById(R.id.location);
TextView providers = (TextView)findViewById(R.id.providers);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
//funcions boto start
case R.id.start:
locationManager.requestLocationUpdates(
provider,
10000, //temps em ms (10s)
500, //distancia (meters)
this);
//mostrar provider
TextView location = (TextView)findViewById(R.id.location);
location.setText("Provider: " + provider);
break;
//funcio boto stop
case R.id.stop:
locationManager.removeUpdates(this);
break;
//funcio boto show
case R.id.show:
Location locations = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(
provider,
10000, //temps em ms (10s)
1000, //distancia (meters)
this);
//show long & lat
TextView providers = (TextView)findViewById(R.id.providers);
providers.setText("Latitude & longitude: " + ""); //com traslladar valor loc aqui?
break;
}
}
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
int lat = (int) (loc.getLatitude());
int lng = (int) (loc.getLongitude());
loc.toString();
}
#Override
public void onProviderDisabled(String np) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String p) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
The segment where I get the desired info is this one:
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
int lat = (int) (loc.getLatitude());
int lng = (int) (loc.getLongitude());
loc.toString();
}
As you can see, I turn the information into a String.
Now, my problem is: how do I call this info in the main function to print it? In this segment:
//funcio boto show
case R.id.show:
Location locations = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(
provider,
10000, //temps em ms (10s)
1000, //distancia (meters)
this);
//show long & lat
TextView providers = (TextView)findViewById(R.id.providers);
providers.setText("Latitude & longitude: " + ""); //com traslladar valor loc aqui?
break;
what you have to do is the following :
1st - declare a String to store your lattitude and longitude :
private String lattitude , longitude;
2nd - in your get onLocationChanged do the following :
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
int lat = (int) (loc.getLatitude());
int lng = (int) (loc.getLongitude());
lattitude = "lattitude = "+ lat ;
longitude = "longitude = "+ lng;
}
3rd - use the lattitude and longitude to print them in any place you want .
Hope that helps .
I'm trying to make a trivial application in which the user clicks a button and a few text views display various information about the phone(model,battery %,location,signal strength etc). I'm having trouble getting the current latitude and longitude, since when I press the button the textview displays the previous latitude/longitude(first time it shows 0,0 and the second the position I was when I first pressed it).
What I'm trying to achieve is when I press the button, activate the location manager and location listener, and make the onClick() method wait until the latitude is not equal to the old latitude. I've tried Threads, handler, and asynctask but I haven't managed anything. Any tips? This is how my onClick() method looks right now: (Infogatherer is a class where I collect all the info)
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bMeasurements:
oldLat=InfoGatherer.getLatitude();
oldLong=InfoGatherer.getLongitude();
//SOMEWHERE HERE START A THREAD OR SOMETHING IN ORDER TO RETRIEVE CURRENT LOCATION
//Retrieval and Assignment of information to the corresponding text fields
DeviceName.setText(infogatherer.getDeviceName());
NetworkOp.setText(infogatherer.getNetworkOp());
Date.setText(infogatherer.getDate());
BatteryStatus.setText(String.valueOf(infogatherer.getBatteryStatus()));
Generation.setText(String.valueOf(infogatherer.getGeneration()));
infogatherer.getLocation();
Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));
infogatherer.getSignalStrength();
SignalStrength.setText(String.valueOf(infogatherer.getDbm()));
oldLat = InfoGatherer.getLatitude();
oldLong = InfoGatherer.getLongitude();
break;
}
This is my InfoGatherer class:
package com.example.netmap;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.CellInfoGsm;
import android.telephony.CellSignalStrengthGsm;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
public class InfoGatherer extends Application{
String address,city,country;
int cid,lac,generation=0,ipAddress=0,signalStrngth=0;
private GsmCellLocation location;
private WifiInfo wifiInfo;
private LocationManager lm;
private LocationListener ll;
Geocoder geoc;
static public double Longitude,Latitude=0;
List<Address> addresses;
Context context;
Intent batteryIntent;
TelephonyManager tm;
WifiManager wifimanager;
public InfoGatherer(){
}
public InfoGatherer(Context context){
this.context = context;
}
public String getDate(){
Calendar c = Calendar.getInstance();
return Integer.toString(c.get(Calendar.DAY_OF_MONTH))+"-"+Integer.toString(c.get(Calendar.MONTH))+"-"+Integer.toString(c.get(Calendar.YEAR))+" "+Integer.toString(c.get(Calendar.HOUR_OF_DAY))+":"+Integer.toString(c.get(Calendar.MINUTE))+":"+Integer.toString(c.get(Calendar.SECOND));
}
public String getDeviceName(){
return Build.MANUFACTURER +" "+Build.MODEL;
}
public String getNetworkOp(){
tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getNetworkOperatorName();
}
public float getBatteryStatus() {
batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
return ((float)batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) / (float)batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)) * 100.0f;
}
public int getGeneration(){
tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getNetworkType();
}
public int getCid(){
tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
location = (GsmCellLocation)tm.getCellLocation();
return location.getCid();
}
public int getLac(){
tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
location = (GsmCellLocation)tm.getCellLocation();
return location.getLac();
}
public String getIpAddress() {
// TODO Auto-generated method stub
wifimanager = (WifiManager) context.getSystemService(WIFI_SERVICE);
wifiInfo = wifimanager.getConnectionInfo();
ipAddress = wifiInfo.getIpAddress();
return String.format("%d.%d.%d.%d",(ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));
}
public void getLocation(){
/*Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
c.setPowerRequirement(Criteria.POWER_LOW);
String provider = lm.getBestProvider(c, true);*/
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
public class mylocationlistener implements LocationListener{
#Override
public void onLocationChanged(android.location.Location location) {
// TODO Auto-generated method stub
if(location!=null){
Longitude = location.getLongitude();
Latitude = location.getLatitude();
lm.removeUpdates(ll);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
//Pass views as parameters? DIscuss
//DeviceName.setText(String.valueOf(Latitude) +" "+String.valueOf(Longitude));
}
#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
}
}
public void getSignalStrength(){
tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener Listener = new phoneStateListener();
tm.listen(Listener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
public class phoneStateListener extends PhoneStateListener{
public void onSignalStrengthsChanged(SignalStrength signalStrength){
super.onSignalStrengthsChanged(signalStrength);
if (signalStrength.isGsm()) {
signalStrngth = -113 + 2 * signalStrength.getGsmSignalStrength();
}
else
signalStrngth = -113 + 2 * signalStrength.getCdmaDbm();
}
}
static public double getLatitude(){
return Latitude;
}
static public double getLongitude(){
return Longitude;
}
public String getAddress(){
return address;
}
public String getCity(){
return city;
}
public String getCountry(){
return country;
}
public int getDbm(){
return signalStrngth;
}
}
You donĀ“t provide enough time to Location service get the location.
You ask for latitude and longitude before the LocationManager have time to call onLocationChanged.
infogatherer.getLocation();
Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));
Call infogatherer.getLocation(); out of onClick event. Do that at Activity onResume() event.
Remove lm.removeUpdates(ll); from onLocationChanged. Call it at Activity onPause()event.
If you want see this example how to create a GPS Manager Class
EDIT
Try something like this: Note: Not tested!
private void updateLocationText(double oldLat, double oldLong) {
Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
boolean isPositionChanged = false;
double lat;
double long;
while (!isPositionChanged) {
lat = InfoGatherer.getLatitude();
long = InfoGatherer.getLongitude();
if(lat != oldLat || long != oldLong)isPositionChanged = true;
}
handler.post(new Runnable(){
public void run() {
Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));
});
}
}
};
new Thread(runnable).start();
}
Note that if you click on the button without having been no change of location, it will run forever.
EDIT AGAIN
Another approach more clean:
Replace
Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));
with this
Location.postDelayed(new Runnable() {
#Override
public void run() {
Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));
Location.postInvalidate();//Try without, may be not necessary
}
}, 3000);//Change if need
Create the LocationListener out of Aplication.
In the Ativity instantiate the class, override the onLocationChanged event and update Location TextView there.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.........
.........
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener(){
#Override
public void onLocationChanged(android.location.Location location) {
if(location!=null){
Location.setText(String.valueOf(location.getLatitude()+","+location.getLatitude()));
lm.removeUpdates(listener);
}
}
}
}
In onClick() event replace:
infogatherer.getLocation();
Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));
with
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
In the end I used AsyncTask, which helped me in order to sleep the app while I looked for the location.
private class LocationThread extends AsyncTask<Context, Void, Void> {
protected void onPreExecute() {
infogatherer.startLocationListener();
}
#Override
protected Void doInBackground(Context... params) {
while (!infogatherer.getGo()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(final Void unused) {
//Do whatever you wanna do after you get location
}
}
getGo is a boolean which whenever becomes true gives the location back
public class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(android.location.Location location) {
if(location != null){
Longitude = location.getLongitude();
Latitude = location.getLatitude();
lm.removeUpdates(ll);
go = true;
}
}
hope you understand the procedure. Cheers.
I am trying to get a location (latitude, longitude) on my Android smartphone (HTC Desire HD), using Wifi-network and GPS.
This is the code I use, only I keep getting "Location not available"
Iam working with Eclipse IDE.
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import com.example.shortsproject.R;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class LocationGetter extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
latituteField = (TextView) findViewById(R.id.locationtext);
longitudeField = (TextView) findViewById(R.id.locationtext2);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Can someone help me with this?
I have been trying to print my lang and long coordinates for the past two days, I have chopped and changed code in order to make it work, in a bit of a muddle now and don't understand why it won't work, I am new to Android Development whilst consulting a book (Beginning Android Development) but it doesn't touch on this subject, any help would be greatly appreciated.
It compiles and I don't get any errors, however it does not print out to the EditText boxes in the application, defined in main.xml.
Here is my code for the Java file:
package com.emergency;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;
import android.location.LocationManager;
import android.location.Criteria;
public class EmergencyLocation extends Activity implements LocationListener {
private TextView latitudeField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. **/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latitudeField = (TextView) findViewById(R.id.long_lat1);
longitudeField = (TextView) findViewById(R.id.long_lat2);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(provider, 0, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
onLocationChanged(location);
}
#Override
protected void onDestroy() {
super.onDestroy();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latitudeField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
/*Toast.makeText(EmergencyLocation.this,
"Longitude " + longitudeField + "Latitude " + latitudeField, Toast.LENGTH_LONG).show();*/
//getting longitude to display in an EditText box
/*EditText lngtude = (EditText) findViewById(R.id.longitudeField);
lngtude.setText(String.valueOf(lng));
EditText lattude = (EditText) findViewById(R.id.latitudeField);
lattude.setText(String.valueOf(lat)); */
EditText lngtude = (EditText) findViewById(R.id.longitudeField);
lngtude.setText(String.valueOf(lng), TextView.BufferType.EDITABLE);
EditText lattude = (EditText) findViewById(R.id.latitudeField);
lattude.setText(String.valueOf(lat), TextView.BufferType.EDITABLE);
} else {
latitudeField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
}
#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 onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button simpleBtn = (Button) findViewById(R.id.location);
simpleBtn.setOnClickListener(new View.OnClickListener() {*/
}
;
I don't believe you're using EditText.setText correctly. See this post as well.
EditText lngtude = (EditText) findViewById(R.id.longitudeField);
lngtude.setText(String.valueOf(lng), TextView.BufferType.EDITABLE);
EditText lattude = (EditText) findViewById(R.id.latitudeField);
lattude.setText(String.valueOf(lat), TextView.BufferType.EDITABLE);
You shouldn't call onLocationChanged() from code. That method runs when the location actually changes. On the emulator you have to simulate a location change, either by sending coordinates from the DDMS perspective or by using the geo fix command in a telnet session.
how can i pass latLongString to elhActivity and show it on the screen....both java files are under same package com.elh.whereami;
i used putExtra and getExtars with intent and still nothing is showing on the screen
this is the whereami.java code
package com.elh.database;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
//import android.widget.TextView;
public class whereami extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
}
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) {
}
};
public void updateWithNewLocation(Location location) {
String latLongString;
String addressString = "No address found";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else {
latLongString = "No location found";
}
Intent intent = new Intent(this, elhActivity.class);
intent.putExtra("the_latLongString", latLongString);
startActivity(intent);
}
}
and this is the elhActivity.java
package com.elh.database;
import android.app.Activity;
import android.widget.TextView;
public class elhActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String latlonginfo = getIntent().getStringExtra("the_latLongString");
TextView tv = new TextView(this);
tv.setText(latlonginfo);
setContentView(tv);
}
}
getIntent().getExtra() will return a Bundle object which contains the objects you place using putExtra().
For example:
Bundle arguments = getIntent().getExtras();
String latlonginfo = arguments.getString("the_latLongString");
TextView tv = new TextView(this);
tv.setText(latlonginfo);
setContentView(tv);
Intent myIntent = this.getIntent();
String latlonginfo = myIntent.getStringExtra("the_latLongString");
The problem might be you are using setContentView twice in your code.
setContentView(R.layout.main);
setContentView(tv);
You will probably have to do away with the 1st setContentView.
or better still add a TextView in the layout in design time and intialize your textview with latlonginfo.
Consider creating a separate XML layout, say child_dialog.xml for the second activity.
public class ChildActivity extends Activity {
private String pushedValue;
#Override
protected void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.child_dialog);
try {
pushValue= getIntent().getExtras().getString("the_latLongString");
}
catch(Exception e){
pushValue= "";
}
}
}