I am a beginner, and I have 2 question :-
I with below code get gps location now want add a timer to code for any 10 Min get gps and save file GPS.json
How can share file gps.json for use in other class this project ?
My code don't problem i tested and for save string used Json format.
Please help me
MyLocationListener class
private class myLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location!=null){
locManager.removeUpdates(locListener);
String longitude = "Longitude: " +location.getLongitude();
String latitude = "Latitude: " +location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String ACRY ="ACR:" + location.getAccuracy();
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject record = new JSONObject();
record.put("longitude", longitude);
record.put("latitude", latitude);
record.put("altitiude", altitiude);
record.put("ACRY", ACRY);
jsonArray.put(record);
jsonObject.put("location", jsonArray);
File root = new File(Environment.getExternalStorageDirectory() + "/Android/test/data");
File gpxfile = new File(root((" Gps.json")));
FileOutputStream fileOutputStream = new FileOutputStream(gpxfile);
byte[] in = (jsonArray.toString().getBytes() );
fileOutputStream.write(in);
fileOutputStream.close();
} catch (Exception e) {
Toast.makeText(context,e.getMessage(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
#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
}
}
I prvoide some you can change according your needs.
public void turnGPSOn() {
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) {
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
private class MyTimerTask extends TimerTask {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// code to get and send location information
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
turnGPSOn();
}
try {
locManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 10,
locationListener);
} catch (Exception ex) {
turnGPSOff();
}
}
});
}
}
private void updateWithNewLocation(Location location) {
String latLongString = "";
try {
if (location != null) {
Log.e("test", "gps is on send");
latitude = Double.toString(location.getLatitude());
longitude = Double.toString(location.getLongitude());
Log.e("test", "location send");
locManager.removeUpdates(locationListener);
latLongString = "Lat:" + latitude + "\nLong:" + longitude;
Log.w("CurrentLocLatLong", latLongString);
} else {
latLongString = "No location found";
}
} catch (Exception e) {
}
}
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) {
}
};
Calling the timer :
long gpsTimeInterval=2000;
void startTimer()
{
myTimer = new Timer();
myTimerTask = new MyTimerTask();
myTimer.scheduleAtFixedRate(myTimerTask, 0,
gpsTimeInterval);
}
and i hope you add internet permission into android manifest file.
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 am new in android and recently start learning about Android and I am trying to get location of any android device by its unique android id. By that I can track the approx or exact location either by GPS or network provider. In detail I mean to say that whenever i enter any Android id in my app i can get device location in my application. Thanks for your kind help.
Finally I am able to do with this code:
public class MyService extends Service implements LocationListener{
String GPS_FILTER = "";
Thread triggerService;
LocationListener locationListener;
LocationManager lm;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meter
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000 * 60 * 3; // 1 minute
protected LocationManager locationManager;
boolean isRunning = true;
Calendar cur_cal = Calendar.getInstance();
Location location;
double latitude; // latitude
double longitude;
UserFunctions userFunction;
private JSONObject json;
private AlertDialogManager alert = new AlertDialogManager();
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_FLAG = "flag";
String android_id ;
String userName;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(getApplicationContext(),
0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
android_id = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
if (getAccount() != null) {
userName = getAccount();
}
GPS_FILTER = "MyGPSLocation";
// locationManager = (LocationManager)
// getSystemService(Context.LOCATION_SERVICE);
// locationManager.requestLocationUpdates(
// LocationManager.GPS_PROVIDER,
// MINIMUM_TIME_BETWEEN_UPDATES,
// MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
// new MyLocationListener());
cur_cal.setTimeInMillis(System.currentTimeMillis());
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cur_cal.getTimeInMillis(),
60 * 1000*3, pintent);
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
//turnGPSOn();
/*Toast.makeText(getApplicationContext(), "Hello1", Toast.LENGTH_LONG)
.show();*/
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
/*Toast.makeText(getApplicationContext(), latitude + ", ll" + longitude, Toast.LENGTH_LONG)
.show();*/
userFunction = new UserFunctions();
new YourAsyncTaskLogin().execute();
}
}
location =locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES, 1.0f, locationListener);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// removeGpsListener();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
// private void removeGpsListener(){
// try{
// lm.removeUpdates(locationManager);
// }
// catch(Exception ex){
// System.out.println("Exception in GPSService --- "+ex);
// }
// }
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
postdata(location.getLatitude(), location.getLongitude());
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
/*Toast.makeText(MyService.this, message, Toast.LENGTH_LONG).show();
turnGPSOff();*/
}
private void postdata(double latitude, double longitude) {
// TODO Auto-generated method stub
/*Toast.makeText(getApplicationContext(),
latitude + ", " + longitude, Toast.LENGTH_LONG).show();*/
}
public void onStatusChanged(String s, int i, Bundle b) {
// Toast.makeText(MyService.this, "Provider status changed",
// Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
// Toast.makeText(MyService.this,
// "Provider disabled by the user. GPS turned off",
// Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
// Toast.makeText(MyService.this,
// "Provider enabled by the user. GPS turned on",
// Toast.LENGTH_LONG).show();
}
}
public void turnGPSOn() {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
}
// automatic turn off the gps
public void turnGPSOff() {
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
class YourAsyncTaskLogin extends AsyncTask<Void, Void, Void> {
//private ProgressDialog _ProgressDialog;
#Override
protected void onPreExecute() {
// show your dialog here
/*_ProgressDialog = ProgressDialog.show(getApplicationContext(), "",
"Loading", true);*/
}
#Override
protected Void doInBackground(Void... params) {
json = userFunction.sendLocations(android_id, userName,latitude+"", longitude+"");
return null;
}
protected void onPostExecute(Void result) {
try {
Log.e("Key_Success:",
json.getString(KEY_SUCCESS));
if (json.getString(KEY_SUCCESS) != null) {
// loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
} else {
// Error in login
// loginErrorMsg.setText("Incorrect username/password");
//_ProgressDialog.cancel();
}
} else {
// Error in login
// loginErrorMsg.setText("Incorrect username/password");
//_ProgressDialog.cancel();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", e.getMessage());
}
//_ProgressDialog.dismiss();
}
}
public String getAccount() {
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccountsByType("com.google");
if (list.length != 0) {
String email = list[0].name;
return email;
} else {
return null;
}
}
}
if you want to get location of any device who has your app in their mobile , you can get it ,
firstly in your app you can upload locations to your server with memberid(you can set it , unique for every device) for every x time(you can set it how many times you update the location).
And then you can check your db on your server which device in where.
(my advice you can use webservice to update db on your server)
I'm able to get location update from network provider but when it comes to gps it takes a lot of time for the data to be picked. I want to keep a particular time for which only the GPS listener will work and then move on to network provider after sometime. How to fix this issue ?
This is my code..
public void gpslocation()
{
final LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location)
{
updateLocationForGeo(location);
//update(location);
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
private void makeUseOfNewLocation(Location location) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
System.out.println(provider+ "enabled provider");
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println(provider+ "disabled provider");
networklocation();
}
};
String locationProvider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, 10 * 1000, (float) 10.0,locationListener);
}
public void networklocation()
{
final LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location)
{
updateLocationForGeo(location);
//update(location);
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
private void makeUseOfNewLocation(Location location) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
System.out.println(provider+ "enabled provider");
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println(provider+ "disabled provider");
isGpsProvidersDisabled=true;
}
};
String timeProvider = LocationManager.NETWORK_PROVIDER;
locationManager.requestLocationUpdates(timeProvider, 1 * 1000, (float) 10.0, locationListener);
}
public void updateLocationForGeo(Location location){
System.out.println("location updated");
double dev_lat = location.getLatitude();
double dev_lang = location.getLongitude();
boolean out_of_range=false;
for(int i=0; i<arrayLength; i++){
double lattDiff = Math.toRadians(latarr[i]-dev_lat);
double longDiff = Math.toRadians(lonarr[i]-dev_lang);
double distance=(Math.sin(lattDiff/2)*Math.sin(lattDiff/2))+(Math.sin(longDiff/2)*Math.sin(longDiff/2)*Math.cos( Math.toRadians(latarr[i]))*Math.cos( Math.toRadians(dev_lat)));
System.out.println(distance+" distance" );
double c= (2 * Math.atan2(Math.sqrt(distance), Math.sqrt(1-distance)));
double radius=radarr[i]* 1.60934;
double d = 6371 * c;
if(d>radius)
{
out_of_range=true;
continue;
}
else{
System.out.println("enjoy");
out_of_range=false;
break;
}
}
Any help would be greatly appreciated.
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mlocListener);
public class MyLocationListener implements LocationListener {
private Address mAddresses;
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
Geocoder gcd = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
mAddresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e) {
}
String cityName = (mAddresses != null) ? mAddresses.get(0)
.getLocality() : TimeZone.getDefault().getID();
String countryName = (mAddresses != null) ? mAddresses.get(0)
.getCountryName() : Locale.getDefault().getDisplayCountry()
.toString();
mCurrentSpeed.setText("Longitude"+loc.getLongitude()+" Latitude"+loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
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);
}
Am working on an app, which toasts the latitude and longitude using LocationManager and LocationListener. On running the app, an error shows up saying "Sorry, Process system is not responding.". This happens when I supply the lat and long either manually from emulator control under DDMS or from command prompt using telnet.
Java Code:
public class LocationFinder extends Activity {
private LocationManager locManager;
private LocationListener locListener;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locListener = new MyLocationListener();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(loc != null){
Toast.makeText(getBaseContext(), "Latitude: " + loc.getLatitude() + "Longitude: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
}
}
#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
}
}
}
And I have set the following permissions in manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
The emulator is also hw.gps enabled.
I would like to know if there is anything wrong with my code.
Thanks
Check by using Log that you are getting Values for Latitude and longitude..
Then in Toast put this
Toast.makeText(LocationFinder.this, "Latitude: " + loc.getLatitude() + "Longitude: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
instead of
Toast.makeText(getBaseContext(), "Latitude: " + loc.getLatitude() + "Longitude: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
// Des: Start Device's GPS and get current latitude and longitude
public void GPS() throws IOException {
// Des: This is a background service and called after every 10 minutes and fetch latitude-longitude values
background = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < j; i++) {
if (ProjectStaticVariable.GPSExit == true ) {
try {
Thread.sleep(600000); //10 minutes
mainhandler.sendMessage(mainhandler.obtainMessage());
j++;
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
});
background.start();
mainhandler = new Handler() {
public void handleMessage(Message msg) {
// Check Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
lat_long_Service_flag = true;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener(getApplicationContext());
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, mlocListener);
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
}
};
}
// Des: Location Listener through which we get current latitude and longitude
public class MyLocationListener implements LocationListener {
public MyLocationListener(Context mContext) {}
public MyLocationListener(Runnable runnable) {}
#Override
public void onLocationChanged(Location loc) {
longitude = loc.getLongitude();
latitude = loc.getLatitude();
final_latitude = Double.toString(latitude);
final_longitude = Double.toString(longitude);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}