i am developing one application in that i am successfully getting location but but before getting location i want to check my gps settings and if it is not enable ,display settings of gps from my app ,i wrote but its not working please tell me where i made mistake
myCode
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(ContextAsync, "Loading data", "Please wait...");
locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);
if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
providerAsync = LocationManager.GPS_PROVIDER;
}else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerAsync = LocationManager.NETWORK_PROVIDER;
} else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
providerAsync = LocationManager.PASSIVE_PROVIDER;
//Toast.makeText(ContextAsync, "Switch On Data Connection!!!!",
Toast.LENGTH_LONG).show();
}
else
if(!locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)&&
!locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
buildAlertMessageNoGps();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
latlongDetails =new LatLongDetails();
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
providerAsync = locationManagerAsync.getBestProvider(criteria, false);
location = locationManagerAsync.getLastKnownLocation(providerAsync);
// Initialize the location fields
if (location != null) {
// System.out.println("Provider " + provider + " has been selected.");
latAsync = location.getLatitude();
lonAsync = location.getLongitude();
} else {
//Toast.makeText(ContextAsync, " Locationnot available",
Toast.LENGTH_SHORT).show();
}
List<Address> addresses = null;
GeocoderAsync = new Geocoder(ContextAsync, Locale.getDefault());
try {
addresses = GeocoderAsync.getFromLocation(latAsync, lonAsync, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getCountryName();
AddressAsync = Html.fromHtml(
address + ", " + city + ",<br>" + country).toString();
} catch (Exception e) {
e.printStackTrace();
AddressAsync = "Refresh for the address";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progress.dismiss();
onLocationChanged(location);
Log.v("latAsync_lonAsync",latAsync+"_"+lonAsync);
Intent intentAsync = new Intent(ContextAsync,Emerg.class);
intentAsync.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentAsync.putExtra("calculated_Lat", latAsync);
intentAsync.putExtra("calculated_Lon", lonAsync);
intentAsync.putExtra("calculated_address", AddressAsync);
ContextAsync.startActivity(intentAsync);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
locationManagerAsync.requestLocationUpdates(providerAsync, 0, 0, this);
}
#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
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(ContextAsync);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
ContextAsync.startActivity(new
Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
In onPreExecute() try using:
...
else
if(!locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
buildAlertMessageNoGps();
}
...
I think you are doing well, after viewing your code and problem, i got that you want only location from GPS.If that is enable then ok Otherwise show dialog for enable.
For achieve that you will remove two condition.
else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerAsync = LocationManager.NETWORK_PROVIDER;
}else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
providerAsync = LocationManager.PASSIVE_PROVIDER;
//Toast.makeText(ContextAsync, "Switch On Data Connection!!!!",
Toast.LENGTH_LONG).show();
}
because of this you will not get gps enable popup dialog.
i think it will work.
Related
I am using this code for fetching current location, this code is working fine but now need to put
this code on Asynctask class , I don't have any idea how can implement this code on Asynctask
Please help me How can do this
public class GetLoc implements LocationListener{
SharedPreferences preferences = null;
SharedPreferences.Editor editor = null;
Context context;
LocationManager locationManager ;
String provider;
double lati;
double logi;
ProgressDialog pd;
public static String state;
String zz;
public GetLoc(Context context)
{
this.context= context;
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
//Toast.makeText(context, "Location can't be retrieved", Toast.LENGTH_SHORT).show();
Criteria criteria = new Criteria();
// pd = ProgressDialog.show(context, "","Please wait... ");
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
else
Toast.makeText(context, "Location can't be retrieved", Toast.LENGTH_SHORT);
}else{
Toast.makeText(context, "No Provider Found", Toast.LENGTH_SHORT);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location.getLatitude()>0 && location.getLongitude()>0)
{
lati=location.getLatitude();
logi=location.getLongitude();
state= getAddress(context, lati, logi);
}
// Toast.makeText(context, "No"+zz, Toast.LENGTH_SHORT).show();
// pd.dismiss();
}
#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
}
public String getAddress(Context ctx, double latitude, double longitude) {
StringBuilder result = new StringBuilder();
try {
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
//String locality=address.getLocality();
//String city=address.getCountryName();
//String region_code=address.getCountryCode();
state= address.getAdminArea();
// zipcode=address.getPostalCode();
double lat =address.getLatitude();
double lon= address.getLongitude();
// result.append(locality+" ");
// result.append(city+" "+ region_code+" ");
//result.append(zipcode);
}
} catch (IOException e) {
// Log.e("tag", e.getMessage());
}
return state;
}
}
Try this way:
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
progDailog = new ProgressDialog(FastMainActivity.this);
progDailog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
FetchCordinates.this.cancel(true);
}
});
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(true);
progDailog.setCancelable(true);
progDailog.show();
}
#Override
protected void onCancelled(){
System.out.println("Cancelled by user!");
progDialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
progDailog.dismiss();
Toast.makeText(FastMainActivity.this,
"LATITUDE :" + lati + " LONGITUDE :" + longi,
Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) location.getLatitude(); // * 1E6);
int log = (int) location.getLongitude(); // * 1E6);
int acc = (int) (location.getAccuracy());
String info = location.getProvider();
try {
// LocatorService.myLatitude=location.getLatitude();
// LocatorService.myLongitude=location.getLongitude();
lati = location.getLatitude();
longi = location.getLongitude();
} catch (Exception e) {
// progDailog.dismiss();
// Toast.makeText(getApplicationContext(),"Unable to get Location"
// , Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.i("onStatusChanged", "onStatusChanged");
}
}
}
}
i tried a lot of "get current location" for android. But i think most of them are outdated, or i simply dont get it.
I DONT want to set a marker.addmarker(params..) i would like to use the blue default dot for my position on Gmaps. Here i've found somthing about that, but for my bad it also aint work.
Customize marker of myLocation Google Maps v2 Android
So in first line i need, my current Location with a Listener when my Location is updating. Im trying this right now (Testing on a real device). But myLocation is always =null.
//get GMaps Fragment
mMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true); //activate Blue dot
myLocation = mMap.getMyLocation(); //Testing, but not working = null
//Trying with LocationManager
locManager =(LocationManager)getSystemService(this.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locManager.getBestProvider(criteria, true);
myLocation = locManager.getLastKnownLocation(provider);
if(myLocation != null){
double lat = myLocation.getLatitude();
double lon = myLocation.getLongitude();
}
locManager.requestLocationUpdates(provider, 1000, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
myLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
Follow this http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ . Then just place the latitude and longitude you get(using gps.getLatitude(), gps.getLongitude()) in your google map and it will show your current location.
Try this code, it is worked in my application:
private LocationManager locationManager;
private String provider;
double lat,lon;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locate);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 1, this);
if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
gpsalert();
}
// Criteria to select location provider
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Toast.makeText(getApplicationContext(), "Provider is available", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Provider is not available", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String addr,city,country;
lat=location.getLatitude();
lon=location.getLongitude();
//Toast.makeText(getApplicationContext(), "lat"+lat+"long"+lon, Toast.LENGTH_LONG).show();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lon, 1);
addr = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getAddressLine(1);
country = addresses.get(0).getAddressLine(2);
t1.setText(addr+"\n"+city+"\n"+country);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_SHORT).show();
//t1.setText("");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Enabled provider " + provider, Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onResume() {
super.onResume();
//locationManager.requestLocationUpdates(provider, 400, 1, this);
}
// Remove LocationListener updates
#Override
protected void onPause() {
super.onPause();
//locationManager.removeUpdates(this);
}
public void gpsalert()
{
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to run application in background in android?
i am doing project using location manager if my location latitude and longitude equal to the same which is in database mobile profile should go to silent mode.so i need to keep on update my location using location manager.i did it .but if i close my app it's not working.
but my app should be working even though i close my app.i tried with async task its working when i close the app but after i switch to loud mode manually it's not changing to silent.i should also get notified when my app runs n background..please help.tks in advance
here is my code
public class ShowLocationActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
double lat,lng;
Location location;
AudioManager mobilemode ;
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
mobilemode = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
flag = displayGpsStatus();
if (flag) {
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
if((lat==12.905478)&&(lng==80.093358))
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(getBaseContext(),"VIBRATE profile activated ",Toast.LENGTH_SHORT).show();
}
else if ((lat==12.90080625)&&(lng==80.09210655))
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(getBaseContext(),"SILENT profile activated !",Toast.LENGTH_SHORT).show();
//notification.setLatestEventInfo(ShowLocationActivity.this, "changed to silent mode", "because u r in office", pendingIntent);
// notificationManager.notify(i, notification);
}
else
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(getBaseContext(),"LOUD profile activated !",Toast.LENGTH_SHORT).show();
}
}
else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.location, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_settings:
Intent intent = new Intent( ShowLocationActivity.this,SetPreference.class);
startActivityForResult(intent, 0);
checkPref();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void checkPref(){
SharedPreferences myPref
= PreferenceManager.getDefaultSharedPreferences(ShowLocationActivity.this);
String _pref =
"Option 1: " + myPref.getBoolean("pref_opt1", true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
checkPref();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
public void rrr(View v)
{
DownloadTask n= new DownloadTask();
n.doInBackground();
}
public void onDestroy()
{
super.onDestroy();
Log.v("hhh","on destroy");
DownloadTask n= new DownloadTask();
n.doInBackground();
}
public 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_LOCATION_SOURCE_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();
}
public class DownloadTask extends AsyncTask<Integer, Integer, Void> {
#Override
protected Void doInBackground(Integer... params) {
Log.v("hhh","back");
onCreate(null);
// onLocationChanged(location);
/*
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
if((lat==12.905478)&&(lng==80.093358))
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(getBaseContext(),"VIBRATE profile activated ",Toast.LENGTH_SHORT).show();
}
else if ((lat==12.90080625)&&(lng==80.09210655))
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(getBaseContext(),"SILENT profile activated !",Toast.LENGTH_SHORT).show();
//notification.setLatestEventInfo(ShowLocationActivity.this, "changed to silent mode", "because u r in office", pendingIntent);
// notificationManager.notify(i, notification);
}
else
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(getBaseContext(),"LOUD profile activated !",Toast.LENGTH_SHORT).show();
}
}
else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
// TODO Auto-generated method stub
*/
return null;
}
}
}
You have coded in Activity, I suggest you to changed it to Android Service. A Service is a component which runs in the background, without interacting with the user.
Have a look at Vogella's Service Example.
Just Convert your Activity code into Android Service and it will work in background without any GUI.
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);
}
I am not able to get the location even though the GPS is enabled and all location managers and listeners are set correctly. Here's what I have so far:
public class GpsTest extends Activity {
private TextView text;
private LocationManager manager;
private LocationListener listener;
private Location myLocation;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.textView1);
try
{
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
myLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //"gps"
text.setText(("Lat: " + myLocation.getLatitude()
+ "\nLLong: " + myLocation.getLongitude()));
listener = new MyLocationListener();
manager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
1,
listener);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is enable. ", Toast.LENGTH_SHORT).show();
}
else createGpsDisabledAlert();
}catch(Exception ex)
{
createGpsDisabledAlert();
}
}
public void onclicklistener(View v){
try
{
text.setText(("Lat: " + myLocation.getLatitude()
+ "\nLLong: " + myLocation.getLongitude()));
}catch(Exception ex)
{
Toast.makeText(this, "Error while getting locations. "+ex.toString(), Toast.LENGTH_SHORT).show();
}
}
private void createGpsDisabledAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("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("No Thanks",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
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) {
// TODO Auto-generated method stub
if (location != null){
text.setText(("Lat: " + location.getLatitude()
+ "\nLLong: " + location.getLongitude()));
}
Toast.makeText(GpsTest.this, ""+location, Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
}
You must to use a thread with his run() method like this (Is in spanish, i hope this not a problem for you)
#Override
public void run() {
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Looper.prepare();
mToast.Make(getContext(),"GPS",0);
mLocationListener = new MyLocationListener();
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
Looper.loop();
Looper.myLooper().quit();
} else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
Looper.prepare();
mToast.Make(getContext(),"Triangulacion",0);
mLocationListener = new MyLocationListener();
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
Looper.loop();
Looper.myLooper().quit();
}else{
mToast.Make(context,"No se encuentra seƱal se procede a mandar un mensaje normal",0);
Looper.prepare();
handlerNormal.sendEmptyMessage(0);
Looper.loop();
Looper.myLooper().quit();
}
}
Are you testing on emulator or real device? If you are testing on emulator, check this http://www.javacodegeeks.com/2010/09/android-location-based-services.html and read about DDMS section for location controls. You need to provide some dummy location data for first occurrence and after that it will grab your current location.