Using AsyncTask to get location information - android

I'm trying to get user's current location coordinates and address using reverse geocoding.
As This process takes some time, I want to show a progress bar during that time, so I'm using AsyncTask. So, what basically I'm doing is, from one activity's onClick event I start the AsyncTask which finds me the location informations and then from that AsyncTask I start another activity which uses that Information.
This is my First Activity where onClick event starts the AsyncTask:
public void onClickGirl(View view)
{
(new MyAsyncTask(MainActivity.this)).execute();
}
This is the AsyncTask:
public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
private Context ContextAsync;
public MyAsyncTask (Context context){
this.ContextAsync = context.getApplicationContext();
}
Dialog progress;
private String providerAsync;
private LocationManager locationManagerAsync;
double latAsync=0.0;
double lonAsync=0.0;
String thikanaAsync="Scan sms for location";
String AddressAsync="";
Geocoder GeocoderAsync;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(null, "Loading data", "Please wait...");
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
providerAsync = locationManagerAsync.getBestProvider(criteria, false);
if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
providerAsync = LocationManager.GPS_PROVIDER;
} else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerAsync = LocationManager.NETWORK_PROVIDER;
/*AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("GPS is disabled in the settings!");
alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
alert.setPositiveButton("OK", null);
alert.show();*/
} else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
providerAsync = LocationManager.PASSIVE_PROVIDER;
Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
}
Location 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();
onLocationChanged(location);
} 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();
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
}
}
This is the Second Activity which run after AsyncTask:`
Intent ixx = getIntent();
elat = Double.parseDouble(ixx.getStringExtra("calculated_Lat"));
elon = Double.parseDouble(ixx.getStringExtra("calculated_Lon"));
eAddress1 = ixx.getStringExtra("calculated_address");
And This is the LogCat:
02-01 17:15:26.734: E/AndroidRuntime(2587): java.lang.IllegalStateException: Could not execute method of the activity
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.view.View$1.onClick(View.java:3814)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.view.View.performClick(View.java:4424)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Handler.handleCallback(Handler.java:733)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Handler.dispatchMessage(Handler.java:95)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Looper.loop(Looper.java:137)
I have spent hours after this but can't find the problem. Can anyone please help me finding out what I'm missing??

Please find the updated code and test it at your end and let me know in case you have any query:
package com.example.tabhost;
import java.util.List;
import java.util.Locale;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
private Context ContextAsync;
public MyAsyncTask (Context context){
this.ContextAsync = context;
}
Dialog progress;
private String providerAsync;
private LocationManager locationManagerAsync;
double latAsync=0.0;
double lonAsync=0.0;
String thikanaAsync="Scan sms for location";
String AddressAsync="";
Geocoder GeocoderAsync;
Location location;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(ContextAsync, "Loading data", "Please wait...");
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
providerAsync = locationManagerAsync.getBestProvider(criteria, false);
if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
providerAsync = LocationManager.GPS_PROVIDER;
} else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerAsync = LocationManager.NETWORK_PROVIDER;
/*AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("GPS is disabled in the settings!");
alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
alert.setPositiveButton("OK", null);
alert.show();*/
} else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
providerAsync = LocationManager.PASSIVE_PROVIDER;
//Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
}
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
}
}

instead of using this.ContextAsync = context.getApplicationContext();
ContextAsync should have Activity instance, no ApplicationContext so use this.ContextAsync = context

Related

Android:reverse geocoding-how to save the address for later use?

I am building a project which needs users current location.I am using reverse geocoding to get the exact address of the user.I am using asynctask to run the thread finding the exact address in background.This is my code:
package com.prince.geolocationtest;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements LocationListener {
TextView text, text2, text3;
LocationManager location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String bestProvider = location.getBestProvider(criteria, true);
try {
location.requestLocationUpdates(bestProvider, 0, 0, this);
} catch (SecurityException e) {
Log.e("Permission_Exception", "Permission Not granted");
}
// text=(TextView)findViewById(R.id.textView);
text2 = (TextView) findViewById(R.id.textView2);
Toast.makeText(getApplicationContext(), "Provider=" + bestProvider, Toast.LENGTH_SHORT).show();
}
public void AddDisp(String add) {
text3 = (TextView) findViewById(R.id.textView3);
text3.setText(add);
}
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
AsyncTry obj = new AsyncTry(this);
obj.execute(lat, lon);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case 0:
Toast.makeText(getApplicationContext(), "Out Of Service", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "Temporarily Unavailable", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "Available", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS is off", 3).show();
Intent GPSIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(GPSIntent);
}
public class AsyncTry extends AsyncTask<Double, Integer, String> {
Context context;
String add;
public AsyncTry(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Double... params) {
try {
StringBuilder str = new StringBuilder();
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
str.append("Latitude:" + params[0] + "\nLongitude:" + params[1] + "\n");
if (geocoder.isPresent()) {
List<Address> addresses = geocoder.getFromLocation(params[0], params[1], 1);
// str.append("Address:"+addresses.get(0).getLocality());
// str.append("\n"+addresses.get(0).getAdminArea());
// //String zip = addresses.get(0).getPostalCode();
// str.append("\n"+addresses.get(0).getCountryName());
if (addresses != null) {
Address fetchedAddress = addresses.get(0);
for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++) {
str.append(fetchedAddress.getAddressLine(i)).append("\n");
}
}
add = str.toString();
//str.toString();
} else {
add = "Geocoder implementation doesnt exists";
}
} catch (Exception e) {
Log.d("Exception:", e.toString());
}
MainActivity.this.runOnUiThread(new Runnable() {
Location loc;
#Override
public void run() {
// TODO Auto-generated method stub
text2.setText(add);
}
});
return add;
}
protected void onpostExecute(String result) {
// super.onPostExecute(result);
if (result != null) {
text = (TextView) findViewById(R.id.textView);
text.setText(result);
AddDisp(result);
// Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Though the program returns the address and displays it in the main thread using runOnUiThread, I am not able to send the address to onPostExecute method of asyncTask. I need to use the address for later use rather than just displaying it.. how can I do that? I am using android studio IDE.
Use SharedPreferences:
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit()
.putString("ADDRESS", add)
.apply();
To get it from SharedPreferences:
String address = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("ADDRESS", "");
You declared onPostExecute incorrectly. It should be like this:
#Override
protected void onPostExecute (String result);
Just rewrote your AsyncTask a little bit. You should pass the TexView you want to display the address to the AsyncTask. Does it work now ?
public class AsyncTry extends AsyncTask<Double, Integer, String> {
Context context;
TextView textView;
String add;
public AsyncTry(Context context, TextView textView) {
this.context = context;
this.textView = textView;
}
#Override
protected String doInBackground(Double... params) {
try {
StringBuilder str = new StringBuilder();
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
str.append("Latitude:" + params[0] + "\nLongitude:" + params[1] + "\n");
if (geocoder.isPresent()) {
List<Address> addresses = geocoder.getFromLocation(params[0], params[1], 1);
if (addresses != null) {
Address fetchedAddress = addresses.get(0);
for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++) {
str.append(fetchedAddress.getAddressLine(i)).append("\n");
}
}
add = str.toString();
} else {
add = "Geocoder implementation doesnt exists";
}
} catch (Exception e) {
Log.d("Exception:", e.toString());
}
return add;
}
protected void onPostExecute(String result) {
if (result != null) {
textView.setText(result);
}
}
}

Android get location on asynctask

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

getting "java.lang.RuntimeException" when sending latitude and longitude to remote mysql database within service in android"

i've created an android application which there are two buttons start stop. when start button is clicked then on every 1 seconds current latitude and longitude values are send to the usl as post to insert into a remote mysl database.
within start button i wrote a service MyService for sending latitude and longitude.
within the onStartCommand(..) method of MyService i have wrote a timer for sending latitude and longitude at 1 second.
But i'm getting the following exception
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Can anyone please tell me some solution for this
My Code is as given below
iLoadPage.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class iLoadPage extends Activity {
Button start,stop;
boolean flag=true;
double latin,longin,longitude,latitude;
Activity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.iloadpage);
start = (Button) findViewById(R.id.startapp);
stop = (Button) findViewById(R.id.stop);
stop.setEnabled(false);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
start.setEnabled(false);
stop.setEnabled(true);
String trackid= getIntent().getExtras().getString("trackid");
MyService.setTrackid(trackid);
startService(new Intent(getBaseContext(),MyService.class));
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
start.setEnabled(true);
stop.setEnabled(false);
stopService(new Intent(getBaseContext(),MyService.class));
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
}
public double getLatin() {
return latin;
}
public void setLatin(double latin) {
this.latin = latin;
}
public double getLongin() {
return longin;
}
public void setLongin(double longin) {
this.longin = longin;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
}
MyService .java
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.text.Html;
import android.widget.Toast;
public class MyService extends Service {
public static String trackid;
ScheduledExecutorService scheduler ;
GPSTracker gps;
boolean flag=false;
DownloadFile ss;
Handler handler = new Handler();
double latin,longin,longitude,latitude;
private final int TEN_SECONDS = 3000;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
String errors="notnull";
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
try
{
Toast.makeText(this, "Application Service Started!!!...", Toast.LENGTH_LONG).show();
try {
TimerTask myTimerTask = new TimerTask() {
#Override
public void run() {
flag=true;
DownloadFile sd=new DownloadFile();
sd.execute("");
} };
Timer timer = new Timer();
timer.schedule(myTimerTask, 1000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
Toast.makeText(this, "Service Error->"+e, Toast.LENGTH_LONG).show();}
return START_STICKY;
}
#Override
public void onDestroy()
{
flag=false;
super.onDestroy();
Toast.makeText(this, "Application Service Stopped!!!...", Toast.LENGTH_LONG).show();
}
public double getLatin() {
return latin;
}
public void setLatin(double latin) {
this.latin = latin;
}
public double getLongin() {
return longin;
}
public void setLongin(double longin) {
this.longin = longin;
}
public static String getTrackid() {
return trackid;
}
public static void setTrackid(String trackid) {
CopyOfMyService.trackid = trackid;
}
String pass;
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
gps = new GPSTracker(CopyOfMyService.this);
latin = gps.getLatitude();
longin = gps.getLongitude();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://iloadlogistics.com.au/insert1.jsp");
String trackid= CopyOfMyService.getTrackid();
List<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>(2);
namevaluepairs.add(new BasicNameValuePair("trackid",trackid));
namevaluepairs.add(new BasicNameValuePair("lat",""+latin));
namevaluepairs.add(new BasicNameValuePair("lon",""+longin));
httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity rp = response.getEntity();
String origresponseText = EntityUtils.toString(rp);
String htmlTextStr = Html.fromHtml(origresponseText).toString();
pass=htmlTextStr.trim();
if(htmlTextStr.trim().equals("success"))
{
}else if(htmlTextStr.trim().equals("failure")){
}
} catch (Exception e) {
pass=""+e;
// TODO Auto-generated catch block
System.out.println("ERRRRRRRRRRRRRRRRRROR:"+e);
e.printStackTrace();
}
return pass;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(flag)
{
Toast.makeText(getApplicationContext(), "Inserted!!!...", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Asyntask is Destroying!!!...", Toast.LENGTH_LONG).show();
onDestroy();
}
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
}
}
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public IBinder onBind(Intent arg0) {
return null;
}
}
UPDATION 2
Instead of Timer i used to call the method scheduleSendLocation() which has the following definition given below
Runnable r=new Runnable() {
public void run() {
flag=true;
DownloadFile sd=new DownloadFile();
sd.execute("");
handler.postDelayed(this, TEN_SECONDS);
}
};
public void scheduleSendLocation() {
handler.postDelayed(r, TEN_SECONDS);
}
I don't really see what you need this handler for, but I see at least 2 problems:
you call new Handler() in the UI thread which has no prepared looper
you create a handler without overriding handleMessage() (what does this handler do then?)
When you create a new Handler with the constructor that has no parameter, the handler is associated with the message queue of the current thread (calling new Handler()). It means the thread needs a looper. You can do it by calling Looper.prepare() before creating the handler.
However, you can't do it yet because new Handler() is called as a field initialization. You should move this call somewhere else, such as in onCreate() and then add Looper.prepare() before it.

Requesting Location updates in oncreate method

I am trying to implement a location alarm kind of application.
But whenever my application opens. my current location shows as null.
Below is my code.
package com.hrupin;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class HelloAndroidGpsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener, LocationListener {
private TextView setLat, setLong, destLat, destLong, currLat, currLong, tjd, fromhome, toward;
private Button setmyLoc, setDest;
private EditText editLat, editLong;
private LocationManager orgManager;
//private LocationListener orgListener;
// private LocationListener destListener = new destListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
private String bestProvider;
double orginLongitude, orginLatitude, destLongtitude, destLatitude, currLatitude, currLongtitude;
float firstLat, firstLang, secLat, secLang;
Location destinationLocation = new Location("gps");
Location originLocation = new Location("gps");
Location currLocation = new Location("gps");
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setLat = (TextView) findViewById(R.id.setLat);
setLong = (TextView) findViewById(R.id.setLong);
destLat = (TextView) findViewById(R.id.destLat);
destLong = (TextView) findViewById(R.id.destLong);
currLat = (TextView) findViewById(R.id.currLat);
currLong = (TextView)findViewById(R.id.currLong);
tjd = (TextView)findViewById(R.id.setmeter);
fromhome = (TextView)findViewById(R.id.destmeter);
toward = (TextView)findViewById(R.id.currmeter);
setDest = (Button)findViewById(R.id.SetLocation);
editLat = (EditText)findViewById(R.id.editLat);
editLong = (EditText)findViewById(R.id.editLong);
orgManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = orgManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.i("gps_enabled", ex.toString());
}
try {
network_enabled = orgManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.i("network_enabled", ex.toString());
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder builder = new Builder(
HelloAndroidGpsActivity.this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please enable location providers");
builder.setPositiveButton("OK",
HelloAndroidGpsActivity.this);
builder.setNeutralButton("Cancel",
HelloAndroidGpsActivity.this);
builder.create().show();
}
Criteria criteria = new Criteria();
bestProvider = orgManager.getBestProvider(criteria, false);
orgManager.requestLocationUpdates(bestProvider, 0, 0, this);
Location location = orgManager.getLastKnownLocation(bestProvider);
if (location!=null){
setLat.setText("Latitude:" + currLatitude);
setLong.setText("Longitude:" + currLongtitude);
originLocation.setLatitude(currLatitude);
originLocation.setLongitude(currLongtitude);
}
//else Toast.makeText(getBaseContext(), "Error in GPS", Toast.LENGTH_SHORT).show();
setDest.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
destLat.setText("Lat:"+editLat.getText().toString().trim());
destLong.setText("Long"+editLong.getText().toString().trim());
destLatitude = Double.parseDouble(String.valueOf(editLat.getText().toString().trim()));
destLongtitude = Double.parseDouble(String.valueOf(editLong.getText().toString().trim()));
destinationLocation.setLatitude(destLatitude);
destinationLocation.setLongitude(destLongtitude);
float distance = originLocation.distanceTo(destinationLocation);
tjd.setText(String.valueOf(distance/1000)+ " Kms ");
}
});
}
/** Register for the updates when Activity is in foreground */
#Override
protected void onResume() {
super.onResume();
orgManager.requestLocationUpdates(bestProvider, 60000, 1, this);
}
/** Stop the updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
orgManager.removeUpdates(this);
}
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEUTRAL) {
setLat.setText("Sorry, location is not determined. To fix this please enable location providers");
} else if (which == DialogInterface.BUTTON_POSITIVE) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
// This needs to stop getting the location data and save the
// battery power.
//orgManager.removeUpdates(orgListener);
currLatitude = location.getLatitude();
currLongtitude = location.getLongitude();
currLocation.setLatitude(currLatitude);
currLocation.setLongitude(currLongtitude);
currLat.setText(String.valueOf(currLatitude));
currLong.setText(String.valueOf(currLongtitude));
float fromhome = originLocation.distanceTo(currLocation);
float toward = currLocation.distanceTo(destinationLocation);
HelloAndroidGpsActivity.this.fromhome.setText(String.valueOf(fromhome/1000)+ " Kms ");
HelloAndroidGpsActivity.this.toward.setText(String.valueOf(toward/1000) + " Kms ");
if (toward/1000 <= 14 ){
Toast.makeText(getBaseContext(), "You are "+ toward/1000 + " Kms towards Destination ", Toast.LENGTH_SHORT).show();
}
}
}
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
}
}
I know this kind of question has been million times. I have tried all methods which has been specified in answers. But i havent got any output. Please help.
You should not call requestLocationUpdates on onCreate as it is redundant since your code will call it on onResume. The flow is onCreate --> onStart --> onResume.
To get Current Location, this is working pretty fine with me check this out.
our Activity is like this
public class MainActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {
/** Called when the activity is first created. */
private EditText showLocation;
private Button btnGetLocation;
private ProgressBar progress;
private LocationManager locManager;
private LocationListener locListener = new myLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showLocation = (EditText) findViewById(R.id.txtShowLoc);
showLocation.setEnabled(false);
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
btnGetLocation = (Button) findViewById(R.id.btnGetLoc);
btnGetLocation.setOnClickListener(this);
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progress.setVisibility(View.VISIBLE);
try{
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception ex){
}
try{
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch(Exception ex){
}
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please enable location providers");
builder.setPositiveButton("OK", this);
builder.setNeutralButton("Cancel", this);
builder.create().show();
progress.setVisibility(View.GONE);
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
}
private class myLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location!=null){
locManager.removeUpdates(locListener);
String Speed = "Device Speed: " +location.getSpeed();
String longitude = "Longitude: " +location.getLongitude();
String latitude = "Latitude: " +location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
//public List<Address> addresses= gcd.getFromLocation (double latitude1, double longitude1, int maxResults)
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
showLocation.setText("City Name: "+cityName+"\n"+Speed + "\n"+longitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
progress.setVisibility(View.GONE);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(which == DialogInterface.BUTTON_NEUTRAL){
showLocation.setText("location is not getting due to location provider");
}
else if (which == DialogInterface.BUTTON_POSITIVE){
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}}
and main.xml is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView android:id="#+id/textView1" android:layout_width="match_parent" android:text="My Location is:" android:textSize="25sp" android:layout_height="wrap_content"></TextView>
<EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="0.24" android:lines="5" android:id="#+id/txtShowLoc">
<requestFocus></requestFocus>
</EditText>
<LinearLayout android:id="#+id/linearLayout2" android:layout_height="wrap_content" android:layout_width="match_parent" android:gravity="center">
<ProgressBar android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="#+id/progressBar"></ProgressBar>
</LinearLayout>
<LinearLayout android:id="#+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center">
<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Get Current Location" android:id="#+id/btnGetLoc"></Button>
</LinearLayout>
and my manifest file is
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="rdc.getCurrentLocaion"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name" android:debuggable="true">
<activity android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
let me know if you get any trouble!!
#Ramdhan Thanks for your code. But i corrected a mistake made in my code.
Criteria criteria = new Criteria();
bestProvider = orgManager.getBestProvider(criteria, false);
orgManager.requestLocationUpdates(bestProvider, 0, 0, this);
Location location = orgManager.getLastKnownLocation(bestProvider);
if (location!=null){
setLat.setText("Latitude:" + currLatitude);
setLong.setText("Longitude:" + currLongtitude);
originLocation.setLatitude(currLatitude);
originLocation.setLongitude(currLongtitude);
}
Cheanged code:
if (location != null) {
setLat.setText("Latitude:" + location.getLatitude());
setLong.setText("Longitude:" + location.getLongitude());
originLocation.setLatitude(location.getLatitude());
originLocation.setLongitude(location.getLongitude());
}

getting force close application if GPS disabled

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

Categories

Resources