getting force close application if GPS disabled - android

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);
}

Related

Get Current Location GMaps

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();
}

Android Try Getting location for X seconds without freezing the app

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]);
}
});
}

How to run android application in background [duplicate]

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.

Testing GPS current location on Android mobile phone

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

Why is this code to get the location via GPS not working?

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.

Categories

Resources