NullPointerException in location - java

I have a problem with Location variable in my Android app. On this screen GPSLocation works fine, but when I change screen to gpsLocation.getLastKnownLocation() this method always returns null.
First Screen:
public class MainActivity extends ActionBarActivity {
private TextView text;
private GPSLocation gpsLocation;
private Location targetLocation;
private EditText editLatitude;
private EditText editLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.textView);
gpsLocation = new GPSLocation(this);
editLatitude = (EditText)findViewById(R.id.editDlugosc);
editLongitude = (EditText)findViewById(R.id.editSzerokosc);
targetLocation = new Location("Bosch");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void click_rozpocznij(View view) {
targetLocation=gpsLocation.getLastKnownLocation();
text.setText("Your location: \n" + gpsLocation.getLatitude() + "\n" + gpsLocation.getLongitude());
}
public void click_end(View view)
{
gpsLocation.stopUsingGPS();
text.setText("Your location:");
}
public void click_pointer(View view) {
if(targetLocation !=null) {
Intent nextScreen = new Intent(getApplicationContext(), Pointer.class);
nextScreen.putExtra("location", targetLocation);
startActivity(nextScreen);
}
else
{
targetLocation.setLongitude(0);
targetLocation.setLatitude(0);
Intent nextScreen = new Intent(getApplicationContext(), Pointer.class);
nextScreen.putExtra("location", targetLocation);
startActivity(nextScreen);
}
}
public void click_show(View view) {
gpsLocation.getLastKnownLocation();
text.setText("Your location: \n" + gpsLocation.getLatitude() + "\n" + gpsLocation.getLongitude());
}
public void click_SaveTarget(View view) {
if(targetLocation !=null)
{
try{
targetLocation.setLatitude(Double.parseDouble(editLatitude.getText().toString()));
targetLocation.setLongitude(Double.parseDouble(editLongitude.getText().toString()));
}
catch(Exception e)
{
targetLocation.setLatitude(0);
targetLocation.setLongitude(0);
editLatitude.setText("0");
editLongitude.setText("0");
}
}
}
Second Screen:
public class Pointer extends ActionBarActivity implements SensorEventListener{
private Location cel;
private TextView textLocation;
private TextView textDistance;
private TextView textAngle;
private TextView textAccuracy;
private ImageView obrazek;
private SensorManager sensorManager;
private float[] lastCompass= new float[3];
private float[] lastAccelero = new float[3];
private float[] orientation = new float[3];
private boolean lastCompassSet = false;
private boolean lastAcceleroSet = false;
private float[] rotation = new float[9];
private float degree = 0f;
private Sensor compass;
private Sensor accelerometer;
private GPSLocation gpsLocation;
private Location locationFirst;
private Location locationNow;
private GeomagneticField magneticField;
private float azimuthDegress;
private float azimuthCel;
private Long timeStart;
private Long timeEnd;
private void sprawdzPolozenie()
{
if (gpsLocation.location.distanceTo(locationFirst) > 10000)
{
magneticField = new GeomagneticField(Double.valueOf(gpsLocation.getLatitude()).floatValue(),Double.valueOf(gpsLocation.getLongitude()).floatValue(),Double.valueOf(gpsLocation.getAltitude()).floatValue(),System.currentTimeMillis());
locationFirst = gpsLocation.getLastKnownLocation();
}
SensorManager.getRotationMatrix(rotation,null,lastAccelero,lastCompass);
SensorManager.getOrientation(rotation,orientation);
float azimuthRadians = orientation[0];
azimuthDegress = (float)(Math.toDegrees(azimuthRadians));
azimuthDegress += magneticField.getDeclination();
azimuthCel= locationNow.bearingTo(cel);
azimuthDegress=azimuthDegress-azimuthCel;
RotateAnimation ra = new RotateAnimation(degree,-azimuthDegress, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
ra.setDuration(400);
ra.setFillAfter(true);
obrazek.startAnimation(ra);
degree=-azimuthDegress;
}
#Override
public void onSensorChanged(SensorEvent event) {
locationNow=gpsLocation.getLastKnownLocation();
if(locationNow!=null) {
if (event.sensor == compass) {
/*event.values[0]=lastCompass[0];
event.values[1]=lastCompass[1];
event.values[2]=lastCompass[2];*/
System.arraycopy(event.values, 0, lastCompass, 0, event.values.length);
lastCompassSet = true;
} else if (event.sensor == accelerometer) {
/*event.values[0]=lastAccelero[0];
event.values[1]=lastAccelero[1];
event.values[2]=lastAccelero[2];*/
System.arraycopy(event.values, 0, lastAccelero, 0, event.values.length);
lastAcceleroSet = true;
}
if (lastCompassSet) {
timeStart = System.currentTimeMillis();
if (timeStart > timeEnd + 500) {
sprawdzPolozenie();
timeEnd = timeStart;
}
}
textDistance.setText("Distanse: " + locationNow.distanceTo(cel));
textAccuracy.setText("Accuracy: " + locationNow.getAccuracy());
textAngle.setText("Angle: " + azimuthDegress);
}
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener(this, compass, SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause(){
super.onPause();
sensorManager.unregisterListener(this,accelerometer);
sensorManager.unregisterListener(this,compass);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gpsLocation = new GPSLocation(this);
locationFirst = new Location("Bosch");
locationNow = new Location("Bosch");
cel = new Location("Bosch");
locationNow=gpsLocation.getLastKnownLocation();
locationFirst= gpsLocation.getLastKnownLocation();
setContentView(R.layout.activity_wskaznik);
timeEnd =System.currentTimeMillis();
sensorManager = (SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
compass = sensorManager.getDefaultSensor(TYPE_MAGNETIC_FIELD);
accelerometer = sensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
obrazek =(ImageView)findViewById(R.id.wskaznik_imageView);
textLocation = (TextView)findViewById(R.id.wskaznikTekstCel);
textDistance = (TextView)findViewById(R.id.wskaznikTekstOdleglosc);
textAngle = (TextView)findViewById(R.id.wskaznikTekstKat);
textAccuracy =(TextView)findViewById(R.id.wskaznikTekstDokladnosc);
Bundle extras = getIntent().getExtras();
magneticField = new GeomagneticField(Double.valueOf(gpsLocation.getLatitude()).floatValue(),Double.valueOf(gpsLocation.getLongitude()).floatValue(),Double.valueOf(gpsLocation.getAltitude()).floatValue(),System.currentTimeMillis());
if(extras!=null)
{
cel = (Location)extras.get("location");
}
textLocation.setText(cel.getLatitude() + "," + cel.getLongitude());
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void click_wroc(View view) {
finish();
}
GPSLocation itself:
public class GPSLocation extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
public boolean canGetLocation = false;
//czas i dystans pomiedzy pomiarami
private static final long MIN_DISTANCE = 10;
private static final long MIN_TIME = 1000 * 60 * 1;
double latitude;
double longitude;
double altitude;
public Location location;
protected LocationManager locationManager;
public GPSLocation(Context context)
{
this.mContext = context;
getLocation();
}
public void requestLocation() {
//network
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
altitude = location.getAltitude();
}
}
//gps
if(isGPSEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(location!=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
altitude = location.getAltitude();
}
}
}
public Location getLastKnownLocation()
{
try
{
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
this.canGetLocation=false;
this.showSettingsAlert();
}
else
{
requestLocation();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
public Location getLocation()
{
try
{
locationManager=(LocationManager)mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
this.canGetLocation=false;
this.showSettingsAlert();
}
else
{
this.canGetLocation=true;
requestLocation();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
public double getLatitude()
{
if(location!=null)
{
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location!=null)
{
latitude = location.getLatitude();
}
return longitude;
}
public double getAltitude(){
if(location!=null)
{
latitude=location.getAltitude();
}
return altitude;
}
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Przejdź do ustawień");
alertDialog.setMessage("Lokalizacja wyłączona");
// On pressing Settings button
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();
}
});
alertDialog.show();
}
public void stopUsingGPS()
{
if(locationManager!=null)
{
locationManager.removeUpdates(GPSLocation.this);
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}

I ran your Pointer Activity code in isolation, and it worked fine for me.
It looks like your main issue is how you're passing the Location through the Intent to the Pointer Activity from MainActivity.
Location implements Parcelable, so you can pass it though the Intent as you are already doing, and retrieve it like this:
if(extras!=null)
{
//cel = (Location)extras.get("location"); //this is not correct
cel = (Location) extras.getParcelable("location");
}
if (cel != null){
textLocation.setText(cel.getLatitude() + "," + cel.getLongitude());
}
Documentation: http://developer.android.com/reference/android/os/Bundle.html#getParcelable(java.lang.String)
http://developer.android.com/reference/android/location/Location.html

Sory for everyone who wanted help me for problem. I solved this by myself.
Problem was in GPSLocation class. I had to add new constructor at start and change way of getting location from locationManager
public GPSLocation(Context context)
{
this.mContext = context;
location = new Location("Bosch");
getLocation();
}
When I use this code location stay nullpointer.
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
But creating copy of location from locationManager solved problem.
location = new Location(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
Maybe locationManager is creating data of location only not Location itself and that was causing creating nullpointer.

Related

How to save coordinates in a csv file from an android app?

I am working on a project where I want to collect sensor data with coordinates and save them to a csv file.
The app was working perfectly before I started coding for getting the location.
I am using location manager but every time I install this app on my device the application just doesn't seem to work. I disappears after few seconds of installation.
Also note that I am saving the sensor data in every 20 milliseconds so should I collect the coordinate data in the same rate?
Sorry to put the whole code but I need help! Please let me know where should I make changes?
public class MainActivity extends AppCompatActivity implements SensorEventListener, LocationListener {
private SensorManager sensorManager;
private Sensor magnetic;
//Location
LocationManager locationManager;
Handler handler;
Location location;
double latitude;
double longitude;
// --o
private int counter = 1;
private boolean recording = false;
private boolean counterOn = false;
private float magValues[] = new float[3];
private Context context;
private static final int REQUESTCODE_STORAGE_PERMISSION = 1;
Collection<String[]> magneticData = new ArrayList<>();
private CsvWriter csvWriter = null;
public static DecimalFormat DECIMAL_FORMATTER;
TextView stateText;
EditText fileIDEdit;
//Location
TextView lat;
TextView lon;
//--o
TextView magText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Location
handler = new Handler();
lat = (TextView) findViewById(R.id.latitudeTextView);
lon = (TextView) findViewById(R.id.longitudeTextView);
//--o
findViewById(R.id.button).setOnClickListener(listenerStartButton);
findViewById(R.id.button2).setOnClickListener(listenerStopButton);
fileIDEdit = (EditText)findViewById(R.id.editText);
magText = (TextView) findViewById(R.id.textView3);
stateText = (TextView) findViewById(R.id.textView);
stateText.setText("Stand by");
context = this;
// Sensor
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
magnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
symbols.setDecimalSeparator('.');
DECIMAL_FORMATTER = new DecimalFormat("#.000", symbols);
//Location
handler.postDelayed(runLocation, 1000);
}
public Runnable runLocation = new Runnable() {
#Override
public void run() {
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();
MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
}
};
private View.OnClickListener listenerStartButton = new View.OnClickListener() {
#Override
public void onClick(View v) {
recording = true;
stateText.setText("Recording started");
stateText.setTextColor(Color.parseColor("#FF0000"));
}
};
#Override
public void onSensorChanged(SensorEvent event) {
long timeInMillisec = (new Date()).getTime() + (event.timestamp - System.nanoTime()) / 1000000L;
// Some sensor operations
}
//magneticData.add(new String[]{String.valueOf(timeInMillisec), String.valueOf(magValues[0]), String.valueOf(magValues[1]), String.valueOf(magValues[2])});
#SuppressLint("SimpleDateFormat") SimpleDateFormat logLineStamp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS", Locale.getDefault());
//logLineStamp.setTimeZone(TimeZone.getTimeZone("UTC"));
magneticData.add(new String[]{logLineStamp.format(new Date(timeInMillisec)), String.valueOf(x), String.valueOf(y), String.valueOf(z), String.valueOf(magnitude), String.valueOf(latitude), String.valueOf(longitude)});
counter++;
}
}
// Checks if the the storage permissions are given or not by the user
// It will request the use if not
private static boolean storagePermitted(Activity activity){
// Check read write permission
}
//Check Location
private void getLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
} else {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// Added Later
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location changed: "+latitude+" "+longitude, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}

How do I get the coordinates of my current location in yandex mapkit?

How do I get the coordinates of my current location in yandex mapkit ?
There is very little information on the Internet, please help, can you have projects ?
public class MapActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final double DESIRED_ACCURACY = 0;
private static final long MINIMAL_TIME = 1000;
private static final double MINIMAL_DISTANCE = 1;
private static final boolean USE_IN_BACKGROUND = false;
public static final int COMFORTABLE_ZOOM_LEVEL = 18;
private final String MAPKIT_API_KEY = "";
private MapView mapView;
private CoordinatorLayout rootCoordinatorLayout;
private LocationManager locationManager;
private LocationListener myLocationListener;
private Point myLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapKitFactory.setApiKey(MAPKIT_API_KEY);
MapKitFactory.initialize(this);
setContentView(R.layout.map);
mapView = (MapView) findViewById(R.id.mapview);
locationManager = MapKitFactory.getInstance().createLocationManager();
myLocationListener = new LocationListener() {
#Override
public void onLocationUpdated(Location location) {
if (myLocation == null) {
moveCamera(location.getPosition(), COMFORTABLE_ZOOM_LEVEL);
}
myLocation = location.getPosition(); //this user point
Log.w(TAG, "my location - " + myLocation.getLatitude() + "," + myLocation.getLongitude());
}
#Override
public void onLocationStatusUpdated(LocationStatus locationStatus) {
if (locationStatus == LocationStatus.NOT_AVAILABLE) {
System.out.println("sdncvoadsjv");
}
}
};
}
#Override
protected void onStart() {
super.onStart();
MapKitFactory.getInstance().onStart();
mapView.onStart();
subscribeToLocationUpdate();
}
#Override
protected void onStop() {
super.onStop();
MapKitFactory.getInstance().onStop();
locationManager.unsubscribe(myLocationListener);
mapView.onStop();
}
public void onFabCurrentLocationClick(View view) {
if (myLocation == null) {
return;
}
moveCamera(myLocation, COMFORTABLE_ZOOM_LEVEL);
}
private void subscribeToLocationUpdate() {
if (locationManager != null && myLocationListener != null) {
locationManager.subscribeForLocationUpdates(DESIRED_ACCURACY, MINIMAL_TIME, MINIMAL_DISTANCE, USE_IN_BACKGROUND, FilteringMode.OFF, myLocationListener);
}
}
private void moveCamera(Point point, float zoom) {
mapView.getMap().move(
new CameraPosition(point, zoom, 0.0f, 0.0f),
new Animation(Animation.Type.SMOOTH, 1),
null);
}
}

didn't show geofense circle in another device,circle show only in one device

In this app i will genrate geofense circle for current user , if one device have at latlong A,B then this will genrate geofense circle at A,B center and other device is at latlong C,D then this will genrate geofense circle at C,D in another device, In this app one device have only one geofense circle which genrate at device current location
But in this app circle show in only one device
Here is my mapactivity
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
OnMapReadyCallback,
ResultCallback<Status> {
private static final String TAG = "MapsActivity";
private Integer j=0;
private Marker mark;
private LatLng location,l1;
private GoogleMap map;
private Toolbar mTopToolbar;
private List<String> ids = new ArrayList<>();
private FirebaseAuth mAuth;
private Double current_lat, current_long, current_geoloc, lat, lon, geoloc;
private String current_name,current_names, name, currentuserid;
private BitmapDescriptor vnrPoint, banPoint;
private LocationRequest locationRequest;
private final int UPDATE_INTERVAL = 6000;
private final int FASTEST_INTERVAL = 3000;
private User users,user,n;
private Marker geoFenceMarker;
private Circle circle,circle2;
private List<MarkerOptions> markerList;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference myCollection = db.collection("users");
private GeoFire geoFire = new GeoFire(myCollection);
private GoogleApiClient googleApiClient;
private Location lastLocation;
private TextView textLat, textLong;
private MapFragment mapFragment;
private String idd;
private SeekBar volumeControl = null;
private PendingIntent geoFencePendingIntent;
private static final float GEOFENCE_RADIUS = 100.0f; // in meter
private final int REQ_PERMISSION = 999;
private final int GEOFENCE_REQ_CODE = 0;
private final String KEY_GEOFENCE_LAT = "GEOFENCE LATITUDE";
private final String KEY_GEOFENCE_LON = "GEOFENCE LONGITUDE";
private static final String NOTIFICATION_MSG = "NOTIFICATION MSG";
// Create a Intent send by the notification
public static Intent makeNotificationIntent(Context context, String msg) {
Intent intent = new Intent( context, MapsActivity.class );
intent.putExtra( NOTIFICATION_MSG, msg );
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
volumeControl = (SeekBar) findViewById(R.id.verticalseekbar);
volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(), "seek bar progress:" + progressChanged,
Toast.LENGTH_SHORT).show();
}
});
textLat = (TextView) findViewById(R.id.lat);
textLong = (TextView) findViewById(R.id.lon);
mAuth = FirebaseAuth.getInstance();
getdata();
mTopToolbar = findViewById(R.id.my_toolbar);
setActionBar(mTopToolbar);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
createGoogleApi();
}
#Override
protected void onStart() {
super.onStart();
// Call GoogleApiClient connection when starting the Activity
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
// Disconnect GoogleApiClient when stopping Activity
googleApiClient.disconnect();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.main_logout_option) {
mAuth.signOut();
LoginManager.getInstance().logOut();
gotologinactivity();
}
if (item.getItemId() == R.id.clear) {
clearGeofence();
return true;
}
if (item.getItemId() == R.id.geofence) {
startGeofence();
return true;
}
if (item.getItemId() == R.id.Refresh) {
finish();
startActivity(getIntent());
return true;
}
return true;
}
private void createGoogleApi()
{
Log.d(TAG, "createGoogleApi()");
if ( googleApiClient == null ) {
googleApiClient = new GoogleApiClient.Builder( this )
.addConnectionCallbacks(this)
.addOnConnectionFailedListener( this )
.addApi( LocationServices.API )
.build();
}
}
// Check for permission to access Location
private boolean checkPermission() {
Log.d(TAG, "checkPermission()");
// Ask for permission if it wasn't granted yet
return (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED );
}
// Asks for permission
private void askPermission() {
Log.d(TAG, "askPermission()");
ActivityCompat.requestPermissions(
this,
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
REQ_PERMISSION
);
}
// Verify user's response of the permission requested
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult()");
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch ( requestCode ) {
case REQ_PERMISSION: {
if ( grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED ){
// Permission granted
getLastKnownLocation();
} else {
// Permission denied
permissionsDenied();
}
break;
}
}
}
// App cannot work without the permissions
private void permissionsDenied() {
Log.w(TAG, "permissionsDenied()");
// TODO close app and warn user
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
}
// Start location Updates
private void startLocationUpdates(){
Log.i(TAG, "startLocationUpdates()");
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL)
.setSmallestDisplacement(30);
//movement in meter
if ( checkPermission() )
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged ["+location+"]");
lastLocation = location;
clearGeofence();
startGeofence();
writeActualLocation(location);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "onConnected()");
getLastKnownLocation();
recoverGeofenceMarker();
}
// GoogleApiClient.ConnectionCallbacks suspended
#Override
public void onConnectionSuspended(int i) {
Log.w(TAG, "onConnectionSuspended()");
}
// GoogleApiClient.OnConnectionFailedListener fail
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.w(TAG, "onConnectionFailed()");
}
// Get last known location
private void getLastKnownLocation() {
Log.d(TAG, "getLastKnownLocation()");
if ( checkPermission() ) {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if ( lastLocation != null ) {
Log.i(TAG, "LasKnown location. " +
"Long: " + lastLocation.getLongitude() +
" | Lat: " + lastLocation.getLatitude());
writeLastLocation();
startLocationUpdates();
} else {
Log.w(TAG, "No location retrieved yet");
startLocationUpdates();
}
}
else askPermission();
}
private void writeActualLocation(Location location) {
textLat.setText( "Lat: " + location.getLatitude() );
textLong.setText( "Long: " + location.getLongitude() );
geoloc = (location.getLatitude() + 90) * 180 + location.getLongitude();
markerLocation(new LatLng(location.getLatitude(), location.getLongitude()));
markerForGeofence(new LatLng(location.getLatitude(), location.getLongitude()));
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("latitude",location.getLatitude());
profileMap.put("longtitude", location.getLongitude());
profileMap.put("geoFireLocation", geoloc);
idd = mAuth.getCurrentUser().getUid();
db.collection("users").document(idd)
.update(profileMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid)
{
Log.d(TAG,"save");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG,"not save");
}
});
}
private void writeLastLocation() {
writeActualLocation(lastLocation);
}
private Marker locationMarker;
private void markerLocation(LatLng latLng) {
Log.i(TAG, "markerLocation("+latLng+")");
String title = latLng.latitude + ", " + latLng.longitude;
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.title(title);
if ( map!=null ) {
if ( locationMarker != null )
locationMarker.remove();
locationMarker = map.addMarker(markerOptions);
float zoom = 14f;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
//map.animateCamera(cameraUpdate);
}
}
private void markerForGeofence(LatLng latLng) {
Log.i(TAG, "markerForGeofence("+latLng+")");
String title = latLng.latitude + ", " + latLng.longitude;
// Define marker options
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
.title(title);
Log.e("marker",name+""+latLng.toString());
if ( map!=null ) {
// Remove last geoFenceMarker
if (geoFenceMarker != null)
geoFenceMarker.remove();
geoFenceMarker = map.addMarker(markerOptions);
Log.e("geomarker",title+""+geoFenceMarker);
}
}
// Start Geofence creation process
private void startGeofence() {
Log.i(TAG, "startGeofence()");
if( geoFenceMarker != null ) {
a( );
} else {
Log.e(TAG, "Geofence marker is null");
}
}
private void a()
{
for (int i=0;i<j;i++)
{
Geofence geofence = createGeofence( geoFenceMarker.getPosition(), GEOFENCE_RADIUS,ids.get(i));
GeofencingRequest geofenceRequest = createGeofenceRequest( geofence );
addGeofence( geofenceRequest );
}
}
private Geofence createGeofence( LatLng latLng, float radius,String id) {
Log.d(TAG, "createGeofence");
return new Geofence.Builder()
.setRequestId(id)
.setCircularRegion( latLng.latitude,latLng.longitude, radius)
.setTransitionTypes( Geofence.GEOFENCE_TRANSITION_ENTER
| Geofence.GEOFENCE_TRANSITION_EXIT )
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setNotificationResponsiveness(1000)
.build();
}
// Create a Geofence Request
private GeofencingRequest createGeofenceRequest( Geofence geofence ) {
Log.d(TAG, "createGeofenceRequest");
return new GeofencingRequest.Builder()
.setInitialTrigger( GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_EXIT )
.addGeofence( geofence )
.build();
}
private PendingIntent createGeofencePendingIntent() {
Log.d(TAG, "createGeofencePendingIntent");
if ( geoFencePendingIntent != null )
return geoFencePendingIntent;
Intent intent = new Intent( this, GeofenseTrasitionService.class);
return PendingIntent.getService(
this, GEOFENCE_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT );
}
// Add the created GeofenceRequest to the device's monitoring list
private void addGeofence(GeofencingRequest request) {
Log.d(TAG, "addGeofence");
if (checkPermission())
LocationServices.GeofencingApi.addGeofences(
googleApiClient,
request,
createGeofencePendingIntent()
).setResultCallback(this);
}
#Override
public void onResult(#NonNull Status status) {
Log.i(TAG, "onResult: " + status);
if ( status.isSuccess() ) {
saveGeofence();
drawGeofence();
} else {
// inform about fail
}
}
private Circle geoFenceLimits;
private void drawGeofence() {
Log.e("circle", "draw");
if ( circle2 != null )
circle2.remove();
// LatLng last = new LatLng(22.28,73.19);
circle2 = map.addCircle(new CircleOptions()
.center(geoFenceMarker.getPosition())
.radius(GEOFENCE_RADIUS)
.strokeColor(Color.argb(50, 70,70,70))
.fillColor(Color.argb(100, 150,150,150))
.strokeWidth(5.0f));
// map.moveCamera(CameraUpdateFactory.newLatLng(geoFenceMarker.getPosition()));
}
// Saving GeoFence marker with prefs mng
private void saveGeofence() {
Log.d(TAG, "saveGeofence()");
SharedPreferences sharedPref = getPreferences( Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPref.edit();
editor.putLong( KEY_GEOFENCE_LAT, Double.doubleToRawLongBits( geoFenceMarker.getPosition().latitude ));
editor.putLong( KEY_GEOFENCE_LON, Double.doubleToRawLongBits( geoFenceMarker.getPosition().longitude ));
editor.apply();
}
// Recovering last Geofence marker
private void recoverGeofenceMarker() {
Log.d(TAG, "recoverGeofenceMarker");
SharedPreferences sharedPref = getPreferences( Context.MODE_PRIVATE );
if ( sharedPref.contains( KEY_GEOFENCE_LAT ) && sharedPref.contains( KEY_GEOFENCE_LON )) {
double lat = Double.longBitsToDouble( sharedPref.getLong( KEY_GEOFENCE_LAT, -1 ));
double lon = Double.longBitsToDouble( sharedPref.getLong( KEY_GEOFENCE_LON, -1 ));
LatLng latLng = new LatLng( lat, lon );
markerForGeofence(latLng);
drawGeofence();
}
}
// Clear Geofence
private void clearGeofence() {
Log.d(TAG, "clearGeofence()");
LocationServices.GeofencingApi.removeGeofences(
googleApiClient,
createGeofencePendingIntent()
).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if ( status.isSuccess() ) {
// remove drawing
removeGeofenceDraw();
}
}
});
}
private void removeGeofenceDraw() {
Log.d(TAG, "removeGeofenceDraw()");
if ( geoFenceMarker != null)
geoFenceMarker.remove();
if ( circle2 != null )
circle2.remove();
}
private void getdata() {
currentuserid = FirebaseAuth.getInstance().getCurrentUser().getUid();
db.collection("users").document(currentuserid).addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if(documentSnapshot.exists())
{
current_name = documentSnapshot.getString("name");
current_lat = documentSnapshot.getDouble("latitude");
Log.e("lat",current_lat.toString());
current_long = documentSnapshot.getDouble("longtitude");
Log.e("lat",current_long.toString());
location = new LatLng(current_lat, current_long);
if(circle!=null){
circle.remove();
}
try {
circle = map.addCircle(new CircleOptions()
.center(location)
.radius(3000)
.strokeColor(Color.BLUE)
.fillColor(0x220000FF)
.strokeWidth(5.0f)
);
}
catch (Exception e1)
{
Log.e("ex",e1.getMessage());
}
// map.addMarker(new MarkerOptions().position(location).title(current_name));
// map.moveCamera(CameraUpdateFactory.newLatLng(location));
Log.d(TAG,"data"+current_lat+" "+current_long+" "+current_name);
j=0;
getalluser();
}
}
});
}
private void getalluser()
{
QueryLocation queryLocation = QueryLocation.fromDegrees(current_lat, current_long);
Distance searchDistance = new Distance(3, DistanceUnit.KILOMETERS);
geoFire.query()
.whereNearTo(queryLocation, searchDistance)
.build()
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if(mark != null)
{
mark.remove();
}
for(final QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots)
{
user = documentSnapshot.toObject(User.class);
current_names = user.getName();
LatLng all = new LatLng(user.getLatitude(),user.getLongtitude());
showmark(all,current_names,documentSnapshot.getId());
}
}
});
}
private void showmark(LatLng all, String current_n,String id)
{
if(!id.equals(currentuserid))
{
j++;
ids.add(id);
Log.d(TAG, "location"+" "+id+" "+currentuserid+" "+ all + " " + current_n);
vnrPoint = BitmapDescriptorFactory.fromResource(R.drawable.marker_a);
mark = map.addMarker(new MarkerOptions().position(all).icon(vnrPoint).title(current_n));
// map.moveCamera(CameraUpdateFactory.newLatLng(all));
//getnotification();
}
}
private void gotologinactivity() {
Intent intent = new Intent(MapsActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
I don't have any error but geofense circle is not genrate in another device that is the problem it show circle only in one device

Android GPS works at first but later returns null values

This is a simple GPS logger. The latitude and longitude values get logged into an SQLite database every 10 seconds.
This works when my app is run for the first time, but when the app is run again the location values are null and my table never gets updated with the values.
public class GPSService extends Service {
public static final String TAG = GPSService.class.getSimpleName();
private static final int ONGOING_NOTIFICATION_ID = 1000;
public static final String GPS_WAKE_LOCK = "GPSWakeLock";
public static final int GPS_TIME_THRESHOLD = 10000; // 10 sec
public static final int GPS_DISTANCE_THRESHOLD = 10; // 10 meters
public static EventBus bus = EventBus.getDefault();
private LocationManager lm;
private LocationManager locationManager2;
private LocationListener locationListener;
private Location location = null;
private Timer timer;
private DumpTask dumpTask = null;
private DatabaseHelper myDb = null;
private static boolean active = false;
private PowerManager.WakeLock wakeLock = null;
public static Double Latitude;
public static Double Longitude;
public static int TotalNoOfStations;
public float[] result = new float[2];
public int k;
public static Boolean SwitchOffAlarmService=false;
#Override
public void onCreate() {
super.onCreate();
bus.register(this);
timer = new Timer();
myDb = DatabaseHelper.getInstance(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager2 = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
Log.d(TAG, "onCreate ");
k=0;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Log.d(TAG, "destroyed");
bus.unregister(this);
timer.cancel();
stopService(new Intent(this,GPSService.class));
super.onDestroy();
}
#SuppressWarnings("unused")
public void onEvent(GPSLoggerCommand e) {
if (e.command == GPSLoggerCommand.START && !active) {
Log.d(TAG, "start gps logger");
getRouteDetails();
MainActivity.LocationServiceStarted=true;
getLatLonFromDB();
try {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_TIME_THRESHOLD, GPS_DISTANCE_THRESHOLD, locationListener);
}catch (SecurityException ex){
Log.e(TAG, "onEvent " + ex.toString());
}
dumpTask = new DumpTask();
timer.schedule(dumpTask, GPS_TIME_THRESHOLD, GPS_TIME_THRESHOLD);
active = true;
} else if (e.command == GPSLoggerCommand.STOP && active) {
Log.d(TAG, "stop gps logger");
dumpTask.cancel();
try {
lm.removeUpdates(locationListener);
}catch(SecurityException ex){
Log.e(TAG, "onEvent " + ex);
}
bus.post(new StatusReply("total rows " + myDb.getRowsCount()));
stopForeground(true);
active = false;
locationManager2.sendExtraCommand(LocationManager.GPS_PROVIDER,"delete_aiding_data",null);
Bundle bundle = new Bundle();
locationManager2.sendExtraCommand("gps","force_xtra_injection",bundle);
locationManager2.sendExtraCommand("gps","fource_time_injection",bundle);
stopService(new Intent(this,GPSService.class));
} else if (e.command == GPSLoggerCommand.STATUS) {
Log.d(TAG, "onEvent send message " + active);
bus.post(new GPSLoggerStatus(active));
}
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
Log.d(TAG, "onLocationChanged " + loc.getLatitude() + ":" + loc.getLongitude());
location = loc;
}
}
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled");
Toast.makeText(GPSService.this, "Service Canceled due to GPS being Disabled!!", Toast.LENGTH_SHORT).show();
GPSLoggerCommand c;
c = new GPSLoggerCommand(GPSLoggerCommand.STOP);
bus.post(c);
MainActivity.GPServiceStarted=false;
MainActivity.LocationServiceStarted=false;
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
String showStatus = null;
if (status == LocationProvider.AVAILABLE)
showStatus = "Available";
if (status == LocationProvider.TEMPORARILY_UNAVAILABLE)
showStatus = "Temporarily Unavailable";
if (status == LocationProvider.OUT_OF_SERVICE)
showStatus = "Out of Service";
Log.d(TAG, "onStatusChanged " + showStatus);
}
}
public class DumpTask extends TimerTask {
#Override
public void run() {
Log.d(TAG, "dump to base");
if (location != null) {
// write to database
}
}
}
public static void StopServiceFunction()
{
GPSLoggerCommand c;
c = new GPSLoggerCommand(GPSLoggerCommand.STOP);
bus.post(c);
MainActivity.GPServiceStarted=false;
MainActivity.LocationServiceStarted=false;
active = false;
}
}
implement GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
in your activity and past below code in override methods
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
} else {
mCurrentLatitude = location.getLatitude();
mCurrentLongitude = location.getLongitude();
Toast.makeText(this, mCurrentLongitude + " * ********"+mCurrentLatitude, Toast.LENGTH_LONG).show();
}
}

How to Stop extand Thread class In android?

i using call function to javascript to android . i using my android code below how to stop android mthread.i used for MyBackgroudMethod mThread but i want to stop this thread in sendCheckOutBackgroundKill();how to possible.please help me!!!
public class EmployeeManager extends CordovaActivity implements
LocationListener{
JavaScriptInterface jsInterface;
LocationManager locationManager;
boolean isGPSEnabled = false;
boolean network_enabled = false;
String provider;
String lati = "";
String latlong = "";
String accuracy = "";
Location currentLocation;
LocationManager mLocationManager;
String devieID = "";
boolean backgroundtask = false;
String iSGps = "";
String mTime="";
String mEmployeeId="";
String mAttendanceId="";
MyBackgroudMethod mThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_employee_manager_main);
super.loadUrl("file:///android_asset/www/index.html");
//mThread = new MyBackgroudMethod();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/**/
jsInterface = new JavaScriptInterface(EmployeeManager.this);
appView.addJavascriptInterface(jsInterface, "JSInterface");
appView.getSettings().setJavaScriptEnabled(true);
appView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
devieID = getUniquePsuedoID();
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// 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);
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
} else if (network_enabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
// locationManager.requestLocationUpdates(provider, 1000, 0, this);
if (location != null) {
onLocationChanged(location);
} else {
Toast.makeText(getBaseContext(), "Location can't be retrieved",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getBaseContext(), "No Provider Found",Toast.LENGTH_SHORT).show();
}
}
public static String getUniquePsuedoID()
{
String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
String serial = null;
try
{
serial = android.os.Build.class.getField("SERIAL").get(null).toString();
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
catch (Exception e)
{
serial = "serial"; // some value
}
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
public class JavaScriptInterface {
public Activity mContext;
public JavaScriptInterface(Activity c) {
this.mContext = c;
}
#JavascriptInterface
public void sendToAndroid(boolean deviceID) {
Log.v("log", "Sent TO android");
runOnUiThread(new Runnable() {
public void run() {
appView.loadUrl("javascript:passLatLong(\"" + lati + "\",\"" + latlong + "\",\"" + accuracy + "\");");
appView.setEnabled(false);
}
});
}
#JavascriptInterface
public void sendToDeviceId() {
runOnUiThread(new Runnable() {
public void run() {
appView.loadUrl("javascript:passDevieId(\"" + devieID + "\");");
}
});
}
#JavascriptInterface
public void sendCheckInBackground(String time, String employeeId, String attendanceId) {
mTime= time;
mEmployeeId = employeeId;
mAttendanceId = attendanceId;
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EmployeeManager.this, "Check In Background Native", 3000).show();
mThread = new MyBackgroudMethod();
mThread.setDaemon(true);
mThread.start();
}
});
}
public void sendCheckOutBackgroundKill() {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EmployeeManager.this, "Check Out Background Native Kill", 3000).show();
mThread.interrupt();
}
});
}
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
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(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private class MyBackgroudMethod extends Thread {
#Override
public void run() {
while (true) {
checkInternetConnection();
try {
Thread.sleep(Integer.parseInt(mTime)*60*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
new JSONTask().execute(mTime,mEmployeeId,mAttendanceId);
} else {
Log.v(TAG, "Internet Connection Not Present");
}
}
#Override
public void onLocationChanged(Location location) {
if(location.getAccuracy() < 400) {
lati = Double.toString(location.getLatitude());
latlong = Double.toString(location.getLongitude());
accuracy = Double.toString(location.getAccuracy());
}
}
#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
}
public class JSONTask extends AsyncTask<String, Void, String> {
public void onPreExecute() {
// progress.show();
}
protected String doInBackground(String... arg) {
// This value will be returned to your
// onPostExecute(result) method
String time1 = arg[0];
String employeeId2 = arg[1];
String attendenceId2 = arg[2];
String img_url = DBAdpter.onFieldCheckIn(employeeId2, attendenceId2, lati, latlong, accuracy);
return img_url;
}
protected void onPostExecute(String result) {
Toast.makeText(EmployeeManager.this, "JSON TASK", 4000).show();
}
}
}
The loop isn't exiting after the interruption. Put a "break;" inside the catch-clause. That's all.

Categories

Resources