I use the Below code to get the Long Lat and its works fine when GPS location is on. But Issue is. when i turned Off the GPS location and then turn it On again. It didnt Show me the Any Log Lat.
public class GetGPSlocation implements LocationListener {
Context context;
public GetGPSlocation(Context c) {
context = c;
}
public Location getLocation() {
if (ActivityCompat.checkSelfPermission(this.context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "Permision Not Granted", Toast.LENGTH_SHORT).show();
return null;
}
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGPSenabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSenabled) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 10, this);
Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return l;
} else {
Toast.makeText(context, "Please Enable GPS", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
i use this code on button CLick Listner...
btnSaveAttd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GetGPSlocation g = new GetGPSlocation(v.getContext());
Location l = g.getLocation();
if (l!=null){
LAT = l.getLatitude();
LON = l.getLongitude();
}
AlertDialog.Builder alertDialog = new AlertDialog.Builder(v.getContext());
alertDialog.setTitle("Confirmation");
alertDialog.setMessage("Are you sure you want to Call this doctor?\n\n" +
"DocID: " +DocID.getText().toString()+ "\n"+
"EmpName: " + empName.getText().toString() + "\n"+
"DateTime: " + date +"\n" +
"Time: "+time+"\n"+
"Status : " + spinner.getSelectedItem()+"\n"+
"Location: "+LON +" , " +LAT);
alertDialog.setIcon(R.drawable.ic_menu_camera);
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
//endregion
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
});
And Any one can tell me is there any way to enable GPS location automatically if GPS is disabled?
You can listen to changes of providers (i.e GPS) using Broadcast Receiver:
registerReceiver(mReceiverCallback, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
private BroadcastReceiver mReceiverCallback = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
// Do whatever you want here
}
}
};
Related
My phone xiaomi redmi note 2, have a lollipop operating system (API 21).
How to take the coordinates of my points and translate them to the corresponding address? Why in my gadget can not run and error "reverse geo fail" appears, but in other gadgets run very well.
I have minSdkVersion 21 in settings gradle.
the following code
public class Emergency extends AppCompatActivity implements LocationListener {
protected LocationManager locationManager;
ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emergency);
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
}
//onClick button
public void btn_pick_up(View view) {
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
loading = ProgressDialog.show(Emergency.this, "Loading", "Please wait", false, false);
getLocation();
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {}
});
android.support.v7.app.AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
assert locationManager != null;
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, this);
} catch(SecurityException e) {
e.printStackTrace();
loading.dismiss();
}
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(Emergency.this, "Latitude: " + location.getLatitude() + "\n Longitude: " + location.getLongitude(), Toast.LENGTH_LONG).show();
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
Toast.makeText(Emergency.this,
addresses.get(0).getAddressLine(0) +", "+
addresses.get(0).getAddressLine(1) +", "+
addresses.get(0).getAddressLine(2),
Toast.LENGTH_LONG).show();
locationManager.removeUpdates(this);
loading.dismiss();
} catch(Exception e) {
Toast.makeText(Emergency.this, e.getMessage(), Toast.LENGTH_LONG).show();
loading.dismiss();
}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(Emergency.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(Emergency.this, "GPS Enable", Toast.LENGTH_SHORT).show();
}
}
Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
OnCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_location_main);
//All textView
textViewNetLat = (TextView)findViewById(R.id.textViewNetLat);
textViewNetLng = (TextView)findViewById(R.id.textViewNetLng);
textViewGpsLat = (TextView)findViewById(R.id.textViewGpsLat);
textViewGpsLng = (TextView)findViewById(R.id.textViewGpsLng);
}
public void onDestroy() {
//Remove GPS location update
if(glocManager != null){
glocManager.removeUpdates(glocListener);
Log.d("ServiceForLatLng", "GPS Update Released");
}
//Remove Network location update
if(nlocManager != null){
nlocManager.removeUpdates(nlocListener);
Log.d("ServiceForLatLng", "Network Update Released");
}
super.onDestroy();
}
//This is for Lat lng which is determine by your wireless or mobile network
public class MyLocationListenerNetWork implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
nlat = loc.getLatitude();
nlng = loc.getLongitude();
//Setting the Network Lat, Lng into the textView
textViewNetLat.setText("Network Latitude: " + nlat);
textViewNetLng.setText("Network Longitude: " + nlng);
Log.d("LAT & LNG Network:", nlat + " " + nlng);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d("LOG", "Network is OFF!");
}
#Override
public void onProviderEnabled(String provider)
{
Log.d("LOG", "Thanks for enabling Network !");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
//This is for Lat lng which is determine by your device GPS
public class MyLocationListenerGPS implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
glat = loc.getLatitude();
glng = loc.getLongitude();
//Setting the GPS Lat, Lng into the textView
textViewGpsLat.setText("GPS Latitude: " + glat);
textViewGpsLng.setText("GPS Longitude: " + glng);
Log.d("LAT & LNG GPS:", glat + " " + glng);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d("LOG", "GPS is OFF!");
}
#Override
public void onProviderEnabled(String provider)
{
Log.d("LOG", "Thanks for enabling GPS !");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public void showLoc(View v) {
//Location access ON or OFF checking
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
boolean networkWifiStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.NETWORK_PROVIDER);
//If GPS and Network location is not accessible show an alert and ask user to enable both
if(!gpsStatus || !networkWifiStatus)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(GetLocationMainActivity.this);
alertDialog.setTitle("Make your location accessible ...");
alertDialog.setMessage("Your Location is not accessible to us.To show location you have to enable it.");
alertDialog.setIcon(R.drawable.warning);
alertDialog.setNegativeButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
});
alertDialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Toast.makeText(getApplicationContext(), "Remember to show location you have to enable it !", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
alertDialog.show();
}
//IF GPS and Network location is accessible
else
{
nlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
nlocListener = new MyLocationListenerNetWork();
nlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 1, 0, nlocListener);
glocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
glocListener = new MyLocationListenerGPS();
glocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 1, 0, glocListener);
}
}
}
This Looks similar:
Google api
It is javasript, but you can use the Google api in andriod as well :-)
What am i trying to do is to get the GPS location from 2 providers, the first one is the GPS which is the most accurate, the second one is the aGPS which is a combination of GPS and network. I am doing that because aGPS can get location even in tall buildings when normal gps takes more time to get.
What i want is to try getting location from the first provider(GPS) for 10 seconds, if in those 10 seconds i get a location!=null, i break the timed loop and take the result to the main thread, which is the main activity. ELSE ill take the location from the second provider(aGPS) if available. If none of the provider where able to get a location, i will return null after the 10 seconds.
The problem i am facing is, when i do a timed loop, the app freezes for 10 seconds so im not able to get the location to the main activity.
Here i am trying to get the location on the HomeActivity class that extends Activity:
Button btnRedCross = (Button) this.findViewById(R.id.btnRedCross);
btnRedCross.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
OutRequestsDatabaseHandler db =new OutRequestsDatabaseHandler();
OutRequest outreq = new OutRequest();
outreq.setName("Red Cross");
//TODO get the message from LocalUser db
Calendar cal = Calendar.getInstance();
outreq.setDate(cal.getTimeInMillis());
outreq.setMessage("My Message");
outreq.setType("RedCross");
//outreq.setLongitude(12.123456);
//outreq.setLatitude(12.123456);
db.addOutRequest(HomeActivity.this, outreq);
//HERE I AM TRYING TO GET THE LOCATION
GPSTracker locationtracker=new GPSTracker(HomeActivity.this);
location=locationtracker.getLocation();
Log.i("LocationGetter","Result: Longitude:"+location[0]+" Latitude:"+location[1]);
}
});
}
This is the GPSTracker Class where the 2 providers try to get location:
public class GPSTracker{
Context con;
LocationManager locMgr;
private double longgps;
private double latgps;
private double longnetwork;
private double latnetwork;
private LocationListener gpsLocationListener;
private LocationListener networkLocationListener;
public GPSTracker(final Context context){
con = context;
locMgr = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
LocationProvider high = locMgr.getProvider(locMgr.getBestProvider(
createFineCriteria(), true));
LocationProvider low = locMgr.getProvider(locMgr.getBestProvider(
createCoarseCriteria(), true));
//GET LOCATION FROM GPS
gpsLocationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder
.setMessage(
"Please Enable GPS and Network For Accurate Result")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public void onLocationChanged(Location location) {
longgps = location.getLongitude();
latgps = location.getLatitude();
//Log.i("LocationGetter", "GPS: Longitude:" + longgps+ " Latitude:" + latgps);
}
};
locMgr.requestLocationUpdates(high.getName(), 0, 0f,gpsLocationListener);
//GET LOCATION FROM GPS + NETWORK
networkLocationListener=new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
longnetwork = location.getLongitude();
latnetwork = location.getLatitude();
//Log.i("LocationGetter", "Network: Longitude:"+ longnetwork + " Latitude:" + latnetwork);
}
};
locMgr.requestLocationUpdates(low.getName(), 0, 0f,networkLocationListener);
}
public static Criteria createFineCriteria() {
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
return c;
}
public static Criteria createCoarseCriteria() {
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
return c;
}
public double[] getLocation() {
double location[] = new double[2];
Calendar cal = Calendar.getInstance();
Long endtime = cal.getTimeInMillis() + 10000;
while (Calendar.getInstance().getTimeInMillis() < endtime) {
if (longgps != 0 && latgps != 0) {
location[0] = longgps;
location[1] = latgps;
Log.i("LocationGetter", "GPS: Longitude:" + location[0]
+ " Latitude:" + location[1]);
break;
} else if (longnetwork != 0 && latnetwork != 0) {
location[0] = longnetwork;
location[1] = latnetwork;
Log.i("LocationGetter", "Network: Longitude:" + location[0]
+ " Latitude:" + location[1]);
}
}
locMgr.removeUpdates(networkLocationListener);
locMgr.removeUpdates(gpsLocationListener);
networkLocationListener = null;
gpsLocationListener = null;
return location;
}
}
Isn't this just a multithreading problem. Instead of doing the work on the main thread, one could create a second thread so that it doesn't matter if that thread is idle for 10 seconds.
Incidentally, instead of relying on any single provider, I think it's better to use all providers and trust them according to their accuracy using a Kalman filter. See my answer here for a simple Kalman filter that seems to work in the context of Android location providers.
Make your GPSTracker class abstract by declaring the method updatedLocation(Location loc) without body. In code
public abstract class GPSTracker{
.......
private Location mLocation;
public void updateLocation(Location loc);
private CountDownTimer mNetworkCountDown = new CountDownTimer(10000, 10000)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#Override
public void onFinish()
{
// this onFinish() will be called if not cancel by Gps
locMgr.removeUpdates(networkLocationListener);
updateLocation(mLocation);
}
};
private CountDownTimer mGpsCountDown = new CountDownTimer(10000, 10000)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#Override
public void onFinish()
{
locMgr.removeUpdates(gpsLocationListener);
}
};
.........
gpsLocationListener = new LocationListener() {
..........
#Override
public void onLocationChanged(Location location) {
// Get a gps fix cancel both countdowns and listeners
mGpsCountDown.cancel();
mNetworkCountDown.cancel();
locMgr.removeUpdates(gpsLocationListener);
locMgr.removeUpdates(networkLocationListener);
// The calling class will get the fix
updateLocation(location);
longgps = location.getLongitude();
latgps = location.getLatitude();
//Log.i("LocationGetter", "GPS: Longitude:" + longgps+ " Latitude:" + latgps);
}
};
locMgr.requestLocationUpdates(high.getName(), 0, 0f,gpsLocationListener);
mGpsCountDown.start();
.......
networkLocationListener=new LocationListener() {
..........
#Override
public void onLocationChanged(Location location) {
// No cancelation here, Gps will cancel if it gets a fix
mLocation = location;
longnetwork = location.getLongitude();
latnetwork = location.getLatitude();
//Log.i("LocationGetter", "Network: Longitude:"+ longnetwork + " Latitude:" + latnetwork);
}
};
locMgr.requestLocationUpdates(low.getName(), 0, 0f,networkLocationListener);
mNetworkCountDown.start();
.........
// remove the getLocation()
}
In HomeActivity class create a class that extends GPSTracker
public class HomeActivity extends Activity {
.........
public class MyGPSTracker extends GPSTracker
{
public void updateLocation(Location location)
{
// location would be null if both Gps and Network did not
// get a fix in 10 seconds
if (location != null)
{
// do whatever you want with this location fix
// If you want to know if this fix is from GPS or Network
// just use String provider = location.getProvider()
Log.i("LocationGetter","Result: Longitude:"+location.getLongitude()+" Latitude:"+location.getLatitude);
}
}
}
Button btnRedCross = (Button) this.findViewById(R.id.btnRedCross);
btnRedCross.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
OutRequestsDatabaseHandler db =new OutRequestsDatabaseHandler();
OutRequest outreq = new OutRequest();
outreq.setName("Red Cross");
//TODO get the message from LocalUser db
Calendar cal = Calendar.getInstance();
outreq.setDate(cal.getTimeInMillis());
outreq.setMessage("My Message");
outreq.setType("RedCross");
//outreq.setLongitude(12.123456);
//outreq.setLatitude(12.123456);
db.addOutRequest(HomeActivity.this, outreq);
//HERE I AM TRYING TO GET THE LOCATION
GPSTracker locationtracker=new MyGPSTracker(HomeActivity.this);
// You will get the location when updateLocation is called by the
// MyGPSTracker class
Log.i("LocationGetter","Result: Longitude:"+location[0]+" Latitude:"+location[1]);
}
});
}
I have application to get location from gps
but if GPS disabled my application getting force close
in emulator it's fine not error,but if run in device it's force close
how can i do this??
this is my code:
public class Track extends Activity implements LocationListener{
String curTime;
double lat;
double lng;
double alt;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final 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);
final String provider = locationManager.getBestProvider(criteria, true);
Dbhelper helper = new Dbhelper(this);
final SQLiteDatabase db = helper.getWritableDatabase();
updateWithNewLocation(null);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
db.isOpen();
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
//db.close();
}
}, 10*60*1000, 10*60*1000);
locationManager.requestLocationUpdates(provider, (10*60*1000), 10,
locationListener);
PackageManager manager = this.getPackageManager();
PackageInfo info = null;
try {
info = manager.getPackageInfo(this.getPackageName(), 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(this,
"PackageName = " + info.packageName + "\nVersionCode = "
+ info.versionCode + "\nVersionName = "
+ info.versionName + "\nPermissions = "+info.permissions, Toast.LENGTH_SHORT).show();
System.out.println("PackageName = " + info.packageName + "\nVersionCode = "
+ info.versionCode + "\nVersionName = "
+ info.versionName + "\nPermissions = "+info.permissions);
}
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) {
if (location != null) {
Dbhelper helper = new Dbhelper(this);
final SQLiteDatabase db = helper.getWritableDatabase();
long time = System.currentTimeMillis();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
curTime = df.format(time);
lat = location.getLatitude();
lng = location.getLongitude();
alt = location.getAltitude();
System.out.println(lat);
System.out.println(lng);
System.out.println(alt);
/*db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
db.close();*/
/*Timer timer = new Timer();
timer.schedule(new TimerTask(){
#Override
public void run(){
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
db.close();
}
}, 10*60*1000, 10*60*1000);*/
}
}
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
}
}
please give me a solution..thank you for feed back :)
If you want to turn on GPS enabled automatically in your app, I'm afraid there is no way other than prompt the user.
You can achieve that easily with modifying onProviderDisabled() method in your LocationListener. The idea is to open a dialog asking user to turn on GPS:
public void onProviderDisabled(String arg0)
{
showDialog(CHOICE_GPS_ENABLE);
}
add in your activity:
protected final static int CHOICE_GPS_ENABLE = 1; //or any other number
#Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
switch (id)
{
case CHOICE_GPS_ENABLE:
dialog = createGPSEnableDialog();
break;
default:
dialog = super.onCreateDialog(id);
break;
}
return dialog;
}
protected Dialog createGPSEnableDialog()
{
Dialog toReturnGPS;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You don't have GPS enabled. Go to Settings and enable GPS?");
builder.setTitle("GPS failed");
builder.setPositiveButton("Yes, enable GPS",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
builder.setNegativeButton("No, quit application",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
onDestroy();
}
});
toReturnGPS = builder.create();
return toReturnGPS;
}
Hope it helps.
i want GPS turn on automatically if my application running
how can i do this??
I don't think you can do anything beyond prompt the user to turn it on. So Im afraid you are going to be unable to make your application work how you'd like.
use
Location locationtest;
public void onLocationChanged(Location location) {
locationtest=location;
updateWithNewLocation(locationtest);
}
public void onProviderDisabled(String provider){
locationtest= null;
updateWithNewLocation(locationtest);
}
instead of
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
When, I test this code on my android mobile phone the current location doesn't show up. Should I configure my mobile or increment new code into the code to allow it run on my mobile properly. A hint will be much appreciated. the code is as follows
public class GetLocation extends Activity {
TextView tv;
double latitude,longitude,accuracy;
private LocationManager lm;
private LocationListener lo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)this.findViewById(R.id.txtLocation);
lm=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
lo = new mylocationlistener();
tv.setText("waiting for location");
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
createGpsDisabledAlert();
}
}
//dialog to check if gps enabled or not
private void createGpsDisabledAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS is disabled! Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
showGpsOptions();
}
});
builder.setNegativeButton("Do nothing",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
}); //close negative builder
AlertDialog alert = builder.create();
alert.show();
}
private void showGpsOptions(){
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
private class mylocationlistener implements LocationListener {
public void onLocationChanged(Location location) {
if (location !=null){
longitude = location.getLongitude();
latitude = location.getLatitude();
accuracy = location.getAccuracy();
/*
Log.d("LOCATION CHANGED", latitude + "");
Log.d("LOCATION CHANGED", longitude + "");
*/ String str = "\n CurrentLocation: "+
"\n Latitude: "+ latitude +
"\n Longitude: " + longitude +
"\n Accuracy: " + accuracy;
Toast.makeText(GetLocation.this,str,Toast.LENGTH_LONG).show();
tv.append(str);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(GetLocation.this,"Error onProviderDisabled",Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(GetLocation.this,"onProviderEnabled",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(GetLocation.this,"onStatusChanged",Toast.LENGTH_LONG).show();
}
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void onResume(){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, lo);
super.onResume();
}
}
In your onCreate you need to call lm.requestLocationUpdates() to get your location listener working . See Requesting Location Updates