how to get current location through gps using android - android

I am trying to create an android program to get the location
but unfortunately its throwing the exception as unfortunately APP is stopped
Can you suggest me please .code is the following
package com.example.ngo;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to"+
" see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----Method to Check GPS is enable or disable ----- */
#SuppressLint("NewApi") private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#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
}
}
}

Related

Android GPS service returns 0.0 every time

I've been searching around for days but can't find what the problem can be. I want to know my current position when I'm clicking button A, and also know my position when I'm clicking button B. Problem is this, when I click B it seems to work fine, but not in A. I use the exact same code on both of them, but in some way it just wont work for A.
Here is my GetGPSLocation code
`
package com.example.eandl.gps;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class GetGPSLocation {
private Context context;
private static double lat;
private static double lang;
public GetGPSLocation(Context context){
this.context = context;
this.lat = 0.0;
this.lang = 0.0;
}
public void setLat(double lat) {
this.lat = lat;
}
public void setLang(double lang) {
this.lang = lang;
}
public Boolean displayGpsStatus() {
final LocationManager manager = (LocationManager) context.getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) ) {
return false;
}else{
return true;
}
}
public double[] getLatLong(){
double[] latLong = new double[2];
if(displayGpsStatus()){
LocationManager locationMangaer = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener(context, this);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions((Activity)context,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
if(checkLocationPermission()){
locationMangaer.requestLocationUpdates(LocationManager
.NETWORK_PROVIDER, 0, 0, locationListener);
}
Log.d("findError", getLang() + "");
latLong[0] = getLat();
latLong[1] = getLang();
}else{
alertbox("Gps status", "Your Device's GPS is Disable");
}
return latLong;
}
public boolean checkLocationPermission()
{
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = context.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(mymessage)
.setCancelable(false)
.setTitle(title)
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
`
And the Listiener
package com.example.eandl.gps;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MyLocationListener implements LocationListener {
private Context context;
private GetGPSLocation getGPSLocation;
public MyLocationListener(Context context, GetGPSLocation getGPSLocation) {
this.context = context;
this.getGPSLocation = getGPSLocation;
}
#Override
public void onLocationChanged(Location loc) {
if(loc != null){
getGPSLocation.setLat(loc.getLatitude());
getGPSLocation.setLang(loc.getLongitude());
}
}
#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
}
}
The way I'm trying to call it is by new GetGPSLocation(context).getLatLong but as I said, sometimes it returns my position and sometimes 0.0
Thank you!
Alright so first I'm setting it up when I create my view like this
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
//Fixa vit med blÄ text
myView = inflater.inflate(R.layout.fragment_signup, container, false);
placements = new ArrayList<CheckBox>();
GetPlacements getPlacements = new GetPlacements(this);
getPlacements.execute();
getGPSLocation = new GetGPSLocation(myView.getContext());
getGPSLocation.getLatLong();
Then this is the onclicklistener on the button A
getGPSLocation.getLatLong();
DatabasSender databasSender = new DatabasSender(myView.getContext());
User user = new User(name.getText().toString(), email.getText().toString(), 0);
user.setSignup(true);
user.setEdu(edu.getText().toString());
user.setPhone(phone.getText().toString());
user.setPlacements(places);
databasSender.execute(user);
That goes to my databassender that uses a AsyncTask
public DatabasSender(Context context) {
this.context = context;
getGPSLocation = new GetGPSLocation(context);
}
#Override
protected void onPreExecute() {
latLong = getGPSLocation.getLatLong();
}
#Override
protected Object doInBackground(Object[] objects) {
urlPatten = "..../"+latLong[0]+"&"+latLong[1];
}
And I use the exact same code for Button B.

Tracking Service won't work after uprading program's Android API

My professor has a program that I am trying to help hime upgrade, unfortunately I am extremely new to Android. It a program that is supposed to grab your Android's location and periodically send it to a server (about every 5 seconds). But after upgrading it to use API 21 (it was on 10-14), it will only return my location as 0.0. Does anyone know what might have caused this?
Here is the Main
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
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
{
protected Button panic;
protected Button track;
private TextView latText;
private TextView lngText;
private TextView addressText;
private boolean panicking;
private boolean tracking;
protected Context mContext;
private Timer locTimer;
private final String TAG = "MainActivity";
protected Sender send;
private int trackingOn;
private int trackingOff;
private int panicOn;
private int panicOff;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tracking = false;
panicking = false;
//colors
trackingOff = Color.rgb(100, 255, 100);
trackingOn = Color.rgb(255, 255, 100);
panicOff = Color.rgb(255, 50, 50);
panicOn = Color.rgb(255, 127, 0);
setupSender();
setupView();
//createGPS();
checkGPS();
//create GPS service
Intent trackIntent = new Intent(MainActivity.this, TrackingService.class);
startService(trackIntent);
createTimer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onDestroy()
{
locTimer.cancel();
super.onDestroy();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
Log.d(TAG, "Back pressed");
//create dialog to turn off GPS
//if not then ask the user to turn it on
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Would you like to turn off the GPS?");
builder.setCancelable(false);
//yes
builder.setPositiveButton("Disable GPS in device settings", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
finish();
}
});
//no
builder.setNegativeButton("No", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
finish();
}
});
AlertDialog gpsAlert = builder.create();
gpsAlert.show();
}
return super.onKeyDown(keyCode, event);
}
private void setupSender()
{
//get MAC address
WifiManager wifiMan = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
String macAddr = wifiInf.getMacAddress();
//get phone Number
TelephonyManager teleMan = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = teleMan.getLine1Number();
Log.d(TAG, "My mac: " + macAddr + " My number: " + phoneNumber);
send = new Sender(macAddr, phoneNumber);
}
private class SendTracking extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... arg0)
{
send.sendTrack(Values.lat, Values.lng, Values.myAddress, Values.acc);
return null;
}
}
private class SendPanic extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... arg0)
{
send.sendPanic(Values.lat, Values.lng, Values.myAddress, Values.acc);
return null;
}
}
private void setupView()
{
latText = (TextView)findViewById(R.id.lattitude);
lngText = (TextView)findViewById(R.id.longitude);
addressText = (TextView)findViewById(R.id.address);
// create tracking button
track = (Button)findViewById(R.id.trackMe);
track.setBackgroundColor(trackingOff);
track.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
tracking = !tracking;
Log.w(TAG, "Tracking button pressed");
if(tracking)
{
track.setBackgroundColor(trackingOn);
track.setText(getResources().getString(R.string.stopTrack));
Values.interval = Values.TRACK_INTERVAL; //set it so it sends right away
}
else
{
new SendTracking().execute();
track.setBackgroundColor(trackingOff);
track.setText(getResources().getString(R.string.tracker));
}
}
});
// create panic button
panic = (Button) findViewById(R.id.panic);
panic.setBackgroundColor(panicOff);
panic.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
Log.w(TAG, "Panic Pressed");
panicking = !panicking;
//send.sendPanic(Values.lat, Values.lng, Values.myAddress, Values.acc);
if(panicking)
{
panic.setBackgroundColor(panicOn);
panic.setText(getResources().getString(R.string.stopPanic));
Values.interval = Values.TRACK_INTERVAL; //set it so it sends right away
}
else
{
panic.setBackgroundColor(panicOff);
panic.setText(getResources().getString(R.string.panic));
}
}
});
}
private void createTimer()
{
//decimal formatter
final DecimalFormat format = new DecimalFormat("#.###");
// create runnable for timer
final Runnable updateLoc = new Runnable()
{
#Override
public void run()
{
Log.i(TAG, "Updating loc");
latText.setText("" + format.format(Values.lat));
lngText.setText("" + format.format(Values.lng));
addressText.setText(Values.myAddress);
//send to DB if tracking is on and enough time has passed since last update
if(tracking)
{
if (Values.interval >= Values.TRACK_INTERVAL)
{
new SendTracking().execute();
Values.interval = 0;
}
else
{
Values.interval++;
}
}
else if(panicking)
{
if (Values.interval >= Values.TRACK_INTERVAL)
{
new SendPanic().execute();
Values.interval = 0;
}
else
{
Values.interval++;
}
}
}
};
// create timer that will check for location
locTimer = new Timer("LocTimer");
locTimer.scheduleAtFixedRate(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(updateLoc);
}
}, Values.UPDATE_TIMER / 2, Values.UPDATE_TIMER);
}
private void checkGPS()
{
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//check to see if GPS is enabled
if(!manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
//if not then ask the user to turn it on
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS is currently disabled. Please turn it on");
builder.setCancelable(false);
//yes
builder.setPositiveButton("Enabled GPS in device settings", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
//no
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog gpsAlert = builder.create();
gpsAlert.show();
}
}
}
And this is the Tracking Service
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
public class TrackingService extends Service {
private LocationManager manager;
private LocationListener listener;
private final String TAG = "TrackingService";
public class LocalBinder extends Binder {
TrackingService getService() {
return TrackingService.this;
}
}
public IBinder onBind(Intent arg0) {
return new LocalBinder();
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
public void onStart(Intent intent, int startId) {
Log.d(TAG, "Starting service");
this.onStart(intent, startId);
}
public void onCreate() {
Log.d(TAG, "Creating service");
this.createGPS();
}
public void onDestroy() {
Log.d(TAG, "Killing service");
manager.removeUpdates(listener);
super.onDestroy();
}
private LocationManager createGPS() {
// create GPS service
manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//context
final Context context = this;
// make listener
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "GPS udpate");
Values.lat = location.getLatitude();
Values.lng = location.getLongitude();
Values.acc = location.getAccuracy();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Geocoder.isPresent()) {
// Since the geocoding API is synchronous and may take a while. You don't want to lock
// up the UI thread. Invoking reverse geocoding in an AsyncTask.
(new ReverseGeocodingTask(context)).execute(new Location[]{location});
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
// register listener
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Values.UPDATE_TIMER, 10f, listener);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, Values.UPDATE_TIMER, 10f, listener);
return manager;
}
// AsyncTask encapsulating the reverse-geocoding API. Since the geocoder API is blocked,
// we do not want to invoke it from the UI thread.
private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void>
{
Context mContext;
public ReverseGeocodingTask(Context context)
{
super();
mContext = context;
}
#Override
protected Void doInBackground(Location... params)
{
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
Location loc = params[0];
List<Address> addresses = null;
try
{
// Call the synchronous getFromLocation() method by passing in the lat/long values.
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
// Update UI field with the exception.
//Message.obtain(mHandler, UPDATE_ADDRESS, e.toString()).sendToTarget();
Log.e("ReverseGeoCoder", "error: " + e.toString());
}
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
// Update the UI via a message handler.
//Message.obtain(mHandler, UPDATE_ADDRESS, addressText).sendToTarget();
Log.d("ReverseGeoCoder", "address: " + addressText);
Values.myAddress = addressText;
}
return null;
}
}
}
It worked just fine before, I've seen the tracking logs, but now it only returns 0.0.

Android Location service

RESOLVED
Singleton pattern was suggested. Not the most elegant way to solve the problem but it works. Here is the code I used. Just have to get the instance in the main and LocationService class to use. See answer for how you are suppose to do it.
import android.location.Location;
public class LocationSingleton {
private Location location;
private static LocationSingleton singleton = new LocationSingleton();
private LocationSingleton(){
}
public static LocationSingleton getInstance( ) {
return singleton;
}
protected void setLocation(Location newLocation) {
this.location = newLocation;
}
protected Location getLocation(){
return this.location;
}
}
Attempting to use a background service to handle Location updates. I create a service in Main that updates the data (working correctly I believe) but I also have a button in main that whenever pressed does some work with the location data. I can't figure out though how to pass the Location from the service back to main. I've tried passing Main to the service but that didn't work and always created the service using the constructor without main passed. I've also tried creating a method in the service that returns the location but that kept getting a null pointer exception. How does one go about doing this.
Service Class
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import java.util.Locale;
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private String TAG = "LocationService";
private GoogleApiClient mGoogleApiClient;
private static final long INTERVAL = 1000 * 15;
private static final long FATEST_INTERVAL = 1000 * 30;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
private Geocoder geocoder;
AddressStringOperations addressOps;
TimerUpdate timerUpdate;
Context mainContext;
MainActivity act;
public LocationService(MainActivity act) {
this.mainContext = mainContext;
Log.e(TAG, "Correct Constructor");
}
public LocationService(){
Log.e(TAG, "Shouldn't use");
}
#Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
this.geocoder = new Geocoder(this, Locale.getDefault());
addressOps = new AddressStringOperations(this.geocoder);
this.timerUpdate = new TimerUpdate(this, addressOps);
timerUpdate.startTimer();
mGoogleApiClient = new GoogleApiClient.Builder(LocationService.this)
.addApi(LocationServices.API).addConnectionCallbacks(LocationService.this)
.addOnConnectionFailedListener(LocationService.this).build();
mGoogleApiClient.connect();
createLocationRequest();
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Log.e(TAG, "Service Started");
return super.onStartCommand(intent, flags, startId);
}
protected void createLocationRequest(){
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public Location getLocation(){
Log.e(TAG, "Latitude: "+ mCurrentLocation.getLatitude() + "\n" + "Longitude: " + mCurrentLocation.getLatitude());
return this.mCurrentLocation;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onConnected(Bundle bundle) {
Log.e(TAG, "Connection Successful");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.e(TAG, "Connection Lost");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "Connection Failed");
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "Firing onLocationChanged.........");
//Log.e(TAG, "Latitude: "+ location.getLatitude() + "\n" + "Longitude: " + location.getLatitude());
timerUpdate.location = location;
mCurrentLocation = location;
}
}
Main Class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.location.Geocoder;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import java.util.Locale;
public class MainActivity extends Activity {
private Button bLogout, bWebsite;
private ImageButton bLogData;
private TextView etLabel;
private UserLocalStore userLocalStore;
private static final String TAG = "MainActivity";
TimerUpdate timerUpdate;
Geocoder geocoder;
Location location;
AddressStringOperations addressOps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e(TAG, "On Create . . . . .");
if(!isGooglePlayServicesAvailable()){
startActivity(new Intent(MainActivity.this, login.class));
Log.e(TAG, "No GooglePlayServices");
finish();
Toast.makeText(getApplicationContext(), "Please update GooglePlay Servies to use this Application", Toast.LENGTH_LONG).show();
}else{
userLocalStore = new UserLocalStore(this);
this.geocoder = new Geocoder(this, Locale.getDefault());
addressOps = new AddressStringOperations(this.geocoder);
this.timerUpdate = new TimerUpdate(this, addressOps, false);
if (authenticate() != true) {
startActivity(new Intent(MainActivity.this, login.class));
Log.e(TAG, "Authenticate is not true");
finish();
} else {
etLabel = (TextView) findViewById(R.id.etEmailLabel);
bLogout = (Button) findViewById(R.id.bLogout);
bLogData = (ImageButton) findViewById(R.id.DataLog);
bWebsite = (Button) findViewById(R.id.website);
LocationService service = new LocationService(MainActivity.this);
Intent start = new Intent(MainActivity.this, LocationService.class);
MainActivity.this.startService(start);
bLogData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String pressStatus = "3";
Log.e(TAG, "Latitude: "+ location.getLatitude() + "\n" + "Longitude: " + location.getLatitude());
timerUpdate.update(pressStatus);
}
});
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
userLocalStore.clearuserData();
userLocalStore.setUserLoggedIn(false);
startActivity(new Intent(MainActivity.this, login.class));
finish();
}
});
bWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("temp"));
startActivity(browserIntent);
}
});
}
}
}
public void setLocation(Location newLocation){
this.location = newLocation;
}
}
You can do that in multiple ways. You can create a Receiver and broadcast and intent from there or you can use an EventBus ( https://github.com/greenrobot/EventBus ).
In this case I think it's more appropriate the Service/Receiver model, you can find here an example: http://www.truiton.com/2014/09/android-service-broadcastreceiver-example/
If you need it only in one activity, consider to use an AsyncTask and handle the output in the postExecute method, it would be a lot easier.

Toast is not working

So i am just trying to get location of user and show it in a toast...but its not working at all...i also tried just to show toast when activity starts but it is not working even at that time
Here's my code
package com.example.alert;
import com.example.alert.CurrentLocation.MyLocationListener;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class ViewAlerters extends Activity{
private Button addButton;
private Button removeButton;
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.view_alerters);
Toast.makeText( ViewAlerters.this,"Hello",Toast.LENGTH_SHORT).show();
LocationListener ll=new MyLocationListener();
//lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5*60*10000, 0, ll);
lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll);
setUpViews();
}
private void setUpViews() {
Toast.makeText( getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
addButton = (Button) findViewById(R.id.add_button);
//alerterText = (TextView) findViewById(R.id.alert_list_text);
removeButton = (Button)findViewById(R.id.remove_button);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ViewAlerters.this,AddAlerter.class);
startActivity(intent);
}
});
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
if(loc!=null)
{
double x;
String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
/* cr.moveToFirst();
while(!cr.isAfterLast()) {
al.add(cr.getString(cr.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
cr.moveToNext();
}*/
// lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 10009,, intent)
//for loop, alerters retrieving one by one
// x= calcDistance(loc.getLatitude(),loc.getLongitude(),z,y);
// if(x<1){
// Intent myIntent = new Intent(ViewAlerters.this,CallMode.class);
// startActivity(myIntent);
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled - #From :Alert Me",Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Enabled - #From :Alert Me",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
public double calcDistance(double latA, double longA, double latB, double longB) {
double theDistance = (Math.sin(Math.toRadians(latA)) * Math.sin(Math.toRadians(latB)) + Math.cos(Math.toRadians(latA)) * Math.cos(Math.toRadians(latB)) * Math.cos(Math.toRadians(longA - longB)));
return new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09*1.6093);
}
}
Don't use getApplicationContext:
Toast.makeText( this,"Hello",Toast.LENGTH_SHORT).show();
Refer to this question about the differences in the Contexts: difference and when to use getApplication(), getApplicationContext(), getBaseContext() and someClass.this
Toast.makeText( ViewAlerters.this,"Hello",Toast.LENGTH_SHORT).show();

Gps Notification Icon Not Blinking

i am trying google maps api on my android phone via following code. My app locating my phone and working great but gps notification icon not blinking. How can i blink gps icon when locating my phone.
Thanks For Replies.
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
And The Code :
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
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.provider.Settings;
import android.widget.EditText;
import android.widget.Toast;
public class main extends MapActivity {
MapController mControl;
GeoPoint geoP;
MapView mapV;
MyLocationOverlay compass;
EditText etext;
String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etext = (EditText) findViewById(R.id.latLong);
mapV = (MapView) findViewById(R.id.mapView);
mapV.displayZoomControls(true);
mapV.setBuiltInZoomControls(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean enable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enable) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
Criteria criteria = new Criteria();
//criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Double lat = location.getLatitude() * 1E6;
Double longi = location.getLongitude() * 1E6;
geoP = new GeoPoint(lat.intValue(), longi.intValue());
List<Overlay> mapOverlays = mapV.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
compass = new MyLocationOverlay(this, mapV);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(geoP, "Hola, Mundo!","I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapV.getOverlays().add(compass);
mapOverlays.add(itemizedoverlay);
mControl = mapV.getController();
mControl.animateTo(geoP);
mControl.setZoom(5);
mControl.setCenter(geoP);
locationManager.requestLocationUpdates(provider, 0, 0,
new LocationListener() {
public void onStatusChanged(String provider, int status,
Bundle extras) {
if (status == LocationProvider.AVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.AVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.OUT_OF_SERVICE",
Toast.LENGTH_SHORT).show();
}
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(),
"Location Changed", Toast.LENGTH_SHORT).show();
}
});
//etext.setText(String.valueOf(lat) + "," + String.valueOf(longi));
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
compass.disableCompass();
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
compass.enableCompass();
}
protected boolean isRouteDisplayed() {
return false;
}
t0mm13b, working on my handset but GPS notification icon not blinking. Virtual Device means Emulator. I solved problem.
Code :
package com.yunusoksuz.gmapstest;
import android.app.Activity;
import android.location.Criteria;
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 YnsmapsActivity extends Activity implements LocationListener {
/** Called when the activity is first created. */
private LocationManager locationManager;
private Location location;
private String provider;
private Double lat, longi;
private Criteria criteria;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv1);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
public void onLocationChanged(Location location) {
Toast.makeText(
this,
"Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude(), Toast.LENGTH_SHORT).show();
tv.setText("Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude());
}
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
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
}
Now gps notification blinking.

Categories

Resources