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)
Related
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.
I am fetching latitude and longitude of current location but onLocationChanged returns same location on mobile data I am using PRIORITY_BALANCED_POWER_ACCURACY mode.
Please tell me where is it misbehaving here's my code
public class Latlng_Service extends Service implements
com.google.android.gms.location.LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
public static String STOP_USER_SERVICE = "STOP_USER_SERVICE";
private static final long INTERVAL = 3000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
private WakeLock wl;
int distance = 0;
List<Address> address_list;
String add_String,cat_id,module_id = "3";
LocationRequest locationRequest;
GoogleApiClient googleApiClient;
Location mloLocation, lastlocation;
String lat, lng, accuracy, name;
String battery_level;
String signal_strength;
Handler fivemiuntesHandler,thirtysecHandler;
Start_latlng_service start_latlng_service;
String login_id, gcm_id, url, response,responseArray[];
boolean flag = false;
List<LatLng> lisLatLngs = new ArrayList<LatLng>();
// public static final String BROADCAST_ACTION =
// "com.xsinfosol.smart_crm.attndance.location";
Intent intent;
String count;
#SuppressWarnings("deprecation")
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
createLocationRequest();
flag = false;
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
start_latlng_service = new Start_latlng_service();
this.registerReceiver(this.broadcastReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
this.registerReceiver(this.stop_service_at_time, new IntentFilter(
STOP_USER_SERVICE));
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "whatever");
wl.acquire();
return START_STICKY;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mloLocation = location;
lat = String.valueOf(location.getLatitude());
lng = String.valueOf(location.getLongitude());
accuracy = String.valueOf(location.getAccuracy());
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
myConnection.logs_onlocation_insert(currentDateTimeString, String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
AtendenceAutoManualFunction(location);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
System.out.println("Connection Falied " + arg0.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
startLocationUpdates();
this.registerReceiver(this.broadcastReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
protected void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationRequest.setInterval(INTERVAL).setFastestInterval(
FASTEST_INTERVAL);
// .setSmallestDisplacement(10);
// .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
protected void startLocationUpdates() {
#SuppressWarnings("unused")
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, this);
Log.d(TAG, "Location update started ..............: ");
if (fivemiuntesHandler == null) {
Log.d(TAG, "Location update started five minutes ..............: ");
fivemiuntesHandler = new Handler();
fivemiuntesHandler.postDelayed(fiveminutes, 300000);
}
if (thirtysecHandler == null) {
Log.d(TAG, "Location update started five minutes ..............: ");
thirtysecHandler = new Handler();
thirtysecHandler.postDelayed(thirtySec, 0);
}
}
protected void stopLocationUpdates() {
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(
googleApiClient, this);
}
Log.d(TAG, "Location update stopped .......................");
}
#SuppressWarnings("deprecation")
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopLocationUpdates();
googleApiClient.disconnect();
unregisterReceiver(broadcastReceiver);
unregisterReceiver(stop_service_at_time);
sharedPreferences = getSharedPreferences("user_detail",
MODE_WORLD_WRITEABLE);
login_id = sharedPreferences.getString("login_id", "");
gcm_id = sharedPreferences.getString("reg_id", "");
if (!login_id.contentEquals("") && !gcm_id.contentEquals("")
&& flag == false) {
sendBroadcast(new Intent("CantKillMe"));
} else {
wl.release();
stopSelf();
}
}
}
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 user to Stackoverflow and this is my first question...
Question is...
How to get the periodic updates of location details? I have tried with Service class and run thread inside it but,This is called only once.
Can any one suggest me what I am doing wrong? Thank you.
Here is my code
public class MyService extends Service
{
String GPS_FILTER = "";
Thread triggerService;
LocationManager lm;
GpsListener gpsLocationListener;
boolean isRunning = true;
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(getApplicationContext(), "Hello",Toast.LENGTH_LONG).show();
GPS_FILTER = "MyGPSLocation";
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
triggerService = new Thread(new Runnable(){
public void run(){
try{
Looper.prepare();//Initialize the current thread as a looper.
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Toast.makeText(getApplicationContext(), "Hello1",Toast.LENGTH_LONG).show();
gpsLocationListener = new GpsListener();
long minTime = 30000; // 5 sec...
float minDistance = 10;
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime,
minDistance, gpsLocationListener);
Looper.loop();
}catch(Exception ex){
System.out.println("Exception in triggerService Thread -- "+ex);
}
}
}, "myLocationThread");
triggerService.start();
}
#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(gpsLocationListener);
}
catch(Exception ex){
System.out.println("Exception in GPSService --- "+ex);
}
}
class GpsListener implements LocationListener{
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
double latitude = location.getLatitude();
double longitude = location.getLongitude();
sendBroadcast(filterRes);
postdata();
}**
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
}
}
}
My updated answer
This Call to service class
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(login.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
public class MyService extends Service
{
String GPS_FILTER = "";
Thread triggerService;
LocationListener locationListener;
LocationManager lm;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1000; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000*60; // in Milliseconds
protected LocationManager locationManager;
boolean isRunning = true;
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
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());
}
#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(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
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();
turnGPSOnOff();
}
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();
}
}
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cur_cal.getTimeInMillis(), 60*1000, pintent);
Try Puuting things that you want to do inside run of this class,
This thread runs every 5 Seconds,
You can modify it as you want.
public class PeriodicChecker extends Thread
{
#Override
public void run()
{
while(true) {
System.out.println("Thread is doing something");
//Put Your code here
Thread.sleep(5000);
}
}
}
public OtherClass {
public static void main(String args[]) {
Thread t = new PeriodicChecker();
t.start();
}
}
I am using service class which gives a call to my inner class that implements Location Listener which provides me my location details... but I need to do this in regular interval.. I have used Thread with looper but it executes only once Please help
This is my udated answer
Updated answer
public class MyService extends Service
{
String GPS_FILTER = "";
Thread triggerService;
LocationListener locationListener;
LocationManager lm;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1000; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000*60; // in Milliseconds
protected LocationManager locationManager;
boolean isRunning = true;
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
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());
}
#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(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
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();
turnGPSOnOff();
}
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();
}
}
also call service using
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(login.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cur_cal.getTimeInMillis(), 60*1000, pintent);
try this...
TimerTask doAsynchronousTask;
long timerCall = 5000;
final Handler handler = new Handler();
Timer timer = new Timer();
public static int times = 0;
// For tracking
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
performBackgroundTask.execute();//In this function add your code which you want to call repeatedly. OR ADD lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Toast.makeText(getApplicationContext(), "Hello1",Toast.LENGTH_LONG).show();
gpsLocationListener = new GpsListener();
long minTime = 30000; // 5 sec...
float minDistance = 10;
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, gpsLocationListener);
Log.d("BGT", "BGT=" + times++);//how many time it called
} catch (Exception e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, timerCall);// execute in every 50000 ms
`