insert into SQLite the location every 5 minutes - java

I want to insert into SQLite the location every 5 minutes, but the location is inserted every time it changes, I'm new with this, I know I have the insert inside the onlocationchange, but it's supposed to call every x time. I do not know what to do
public class GPS extends Service {
public static final int notify = 1000*60*5; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler();
private Timer mTimer = null;
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
if (mTimer != null)
mTimer.cancel();
else {
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);
}
locationMangaer = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver,LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
public class MyLocationListener implements LocationListener {
dbISMLock dbismlock = new dbISMLock(getBaseContext());
final SQLiteDatabase db =dbismlock.getWritableDatabase();
#Override
public void onLocationChanged(Location loc) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
Toast.makeText(getBaseContext(),"fecha: "+ currentDateandTime +"Location changed : Lat: " + loc.getLatitude()+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String phoneID = telephonyManager.getDeviceId();
//INSERT
db.execSQL("INSERT INTO GEOLOCATION( phoneId,Fecha,longitude, latitude) VALUES('"+phoneID+"','"+currentDateandTime+"','"+longitude+"','"+latitude+"')");
Log.d("insertamos "," geolocation" );
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel();
Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
}
class TimeDisplay extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(GPS.this, coordenadas(), Toast.LENGTH_SHORT).show();
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
locationListener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(GPS.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(GPS.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
} else {
Log.d("Gps Status!!", "Your GPS is: OFF");
}
}
});
}
}
}

You can use a Service to listen to location change in background and update it every 5 minutes. onLocationchange() is used to listen manually to changes. So you can ignore it for example and use the Service.

Related

Foreground service is sometimes restarting and sometimes never starts when app is removed from open apps

I am implementing location tracker from Android app by using foreground service.
The expectation is the foreground service should run even
when app is removed from recent open apps.
When app is in open/foreground.
When app is in background i.e. app is still open but went to background
The case 2 & 3 are working fine but case 1 is working weirdly.
In case 1, sometimes foreground service is getting restarted (notification is going off and coming back) after few seconds i.e. 1 to 3 seconds.
In some other times it is never restarted.
I want the foreground service to never go off. In short, I want it like whatsapp location tracking. The whatsapp tracking icon never goes off when the app is closed.
Please give any pointers on what else I am missing
Activity class
public void enableTracking(String planId, JSONArray trackList, CallbackContext callbackContext) {
Log.i(TAG,"In enableTracking");
Intent intent = new
Intent(cordova.getActivity().getApplicationContext(),LocationTracker.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
cordova.getActivity().startForegroundService(intent);
callbackContext.success("Location Tracking is enabled");
} else {
callbackContext.error("Build version is less than OREO");
}
}
public void disableTracking(CallbackContext callbackContext) {
Log.i(TAG,"In disableTracking");
Intent intent = new Intent(cordova.getActivity().getApplicationContext(),LocationTracker.class);
cordova.getActivity().stopService(intent);
callbackContext.success("Location Tracking is disabled");
}
Service class
public class LocationTracker extends Service {
private final IBinder mBinder = new MyBinder();
private static final String CHANNEL_ID = "2";
private static final String TAG = "LocationTracker";
private FusedLocationProviderClient mFusedLocationClient;
RequestQueue mRequestQueue;
public LocationTracker() {
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.i(TAG, "onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
#Override
public void onCreate() {
super.onCreate();
buildNotification();
// logic to start location tracking
}
#Override
public void onDestroy() {
super.onDestroy();
// logic to stop tracking
}
private void fetchAndSendLocation() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, "No permission to fetch location");
return;
}
// mFusedLocationClient.getCurrentLocation()
Task fetchLocTask = mFusedLocationClient.getLastLocation();
fetchLocTask.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
Location loc = (Location) o;
if (loc != null) {
Log.i(TAG, "Lat " + loc.getLatitude() + " lon " + loc.getLongitude() + " date " + (new Date()).toString());
postLocation(loc);
}
}
});
}
private void buildNotification() {
String stop = "stop";
PendingIntent broadcastIntent = PendingIntent.getBroadcast(
this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);
// Create the persistent notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText("Location tracking is working")
.setOngoing(true)
.setContentIntent(broadcastIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getString(R.string.app_name),
NotificationManager.IMPORTANCE_DEFAULT);
channel.setShowBadge(false);
channel.setDescription("Location tracking is in progress");
channel.setSound(null, null);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
}
startForeground(1, builder.build());
}
public class MyBinder extends Binder {
public LocationTracker getService() {
return LocationTracker.this;
}
}
}
AndroidManifest.xml
<service android:enabled="true" android:exported="true" android:foregroundServiceType="location" android:name=".LocationTracker" />
Using LocationManager as in code below has solved this similar situation for me.
public class MyLocationService extends Service {
private static final String TAG = "MyLocationService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.PASSIVE_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER,
LOCATION_INTERVAL,
LOCATION_DISTANCE,
mLocationListeners[0]
);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listener, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: "+ LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE);
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
You could modify this to suit your need.

Location Listener - Not starting from a Service but it works from an Activity

I'm trying to call a LocationListener class from a Service, but It seems that the listener doesn't start.
It worked well when I called it from an Activity.
When I tryed the same (only deleting "this" parameter) it doesn't work.
It seems to be something wrong with the context parameter but I don't know how to solve it.
Calling from Activity (working):
LocationTest2 locationListener = new LocationTest2(getApplicationContext());
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Calling from Service (Not working):
LocationTest2 locationListener = new LocationTest2(getApplicationContext());
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Class: LocationTest2:
public class LocationTest2 extends Thread implements LocationListener {
private String TAG = "LocationTest2";
private Context context;
private boolean isOnline = false;
private LocationManager locationManager;
public LocationTest2(Context context) {
LogSys.e(TAG, "Serviço criado!");
this.context = context;
}
public void startListening() {
isOnline = true;
LogSys.e(TAG, "Ligando serviço");
Toast.makeText(context, "Ligando serviço!", Toast.LENGTH_SHORT).show();
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
public void stopListening() {
if(locationManager != null)
{
Toast.makeText(context, "Desligando serviço!", Toast.LENGTH_SHORT).show();
locationManager.removeUpdates(this);
}
isOnline = false;
}
public boolean isOnline()
{
return isOnline;
}
//=================================
#Override
public void onLocationChanged(Location location) {
String locationStr = "LOCATION WORKED 33!!! " + location.getLatitude() + " | " + location.getLongitude();
LogSys.e(TAG, locationStr);
Toast.makeText(context, locationStr, Toast.LENGTH_SHORT).show();
setLocationToFirebase(location);
}
public void setLocationToFirebase(Location location)
{
String tbl_cliente = GlobalVars.SQL_TABELA_CLIENTE_DEVICE_NAME;
String tbl_dispositivo = GlobalVars.SQL_TABELA_DISPOSITIVO_NAME;
String tbl_coordinates = GlobalVars.SQL_TABELA_COORDINATES_NAME;
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
firebaseDatabase = FirebaseDatabase.getInstance();
try {
firebaseDatabase.setPersistenceEnabled(true);
}catch(DatabaseException e){
LogSys.e(TAG, "DatabaseException: " + e.getMessage());
}
databaseReference = firebaseDatabase.getReference();
Cliente clienteSQLite = Cliente.getClienteSQLite(context);
Dispositivo dispositivoSQLite = Dispositivo.getDispositivoSQLite(context);
DatabaseReference dbRef = databaseReference.child(tbl_cliente)
.child(clienteSQLite.getId())
.child(tbl_dispositivo)
.child(dispositivoSQLite.getId())
.child(tbl_coordinates).push();
String key = dbRef.getKey();
Coordenadas coords = new Coordenadas();
coords.setId(key);
coords.setLatitude(location.getLatitude());
coords.setLongitude(location.getLongitude());
coords.setData(DataHoraAtual.getData());
coords.setHora(DataHoraAtual.getHora());
dbRef.setValue(coords);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
Does someone has any idea? Thanks.
I've found the solution!
If you're trying to execute into a Thread something that depends on
the context/activity param, maybe, it could not work. For example,
Toasts don't work into common Threads if you use getApplicationContext()
function.
Solution: Use a handler or runOnUiThread() function. They will execute your command lines on the main thread. See my example:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable()
{
#Override
public void run() {
//Here I can use getApplicationContext() because I'm on the UI Thread Context (I'm using a handler to do so).
Toast.makeText(getApplicationContext(), "Starting listener...", Toast.LENGTH_SHORT).show();
startListening();
}
});

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

Service and activity communication....update UI when data is received from service

I am trying to implement a app which updates user location at every 15 seconds,stores data to database and show it to listview in my activity.
Location should always update even activity destroys,for that i have created LocationService class.
The problem is I am able to get updates and also able to store into database but i am unable to show these updates in listview at runtime means i want list should refresh at every 15 sec and show it to UI..
Also when I get details from database I am unable to get latest detail instead i get whole arraylist every time which affects my activity response.I want that only newly added data will be fetch from database so that it will take less time in loading but I want to display all data to list everytime.
I have implement a thread (Commented code)which fetch data and show to listview but this is not right way to update UI..please suggest me a way so that i can refresh my list when new data is added into database
This is my activity
public class MainActivity extends Activity {
List<MyLocation> locationList = new ArrayList();
ListView mList;
LocationAdapter adapter;
BroadcastReceiver receiver;
LocationService mService;
boolean mBound = false;
private DbHelper dbHelper;
private Button updateLocation;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
LocationService.LocalBinder binder = (LocationService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateLocation = (Button) findViewById(R.id.update_location);
mList = (ListView) findViewById(R.id.listView);
dbHelper = new DbHelper(this);
updateLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationList = mService.displayLocation();
adapter = new LocationAdapter(MainActivity.this, locationList);
mList.setAdapter(adapter);
}
});
/*
Thread mThread = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(500);
runOnUiThread(new Runnable() {
#Override
public void run() {
locationList = dbHelper.getLocationDetails();
Collections.reverse(locationList);
adapter = new LocationAdapter(MainActivity.this, locationList);
mList.setAdapter(adapter);
}
});
}
} catch (InterruptedException e) {
}
}
};
mThread.start();*/
}
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, LocationService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
}
LocationService
public class LocationService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks {
private final IBinder mBinder = new LocalBinder();
ArrayList<MyLocation> locationList = new ArrayList<>();
private DbHelper dbHelper;
private Location mLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private String TAG = "Service";
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
dbHelper = new DbHelper(this);
createLocationRequest();
displayLocation();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "service destroy");
}
public List<MyLocation> displayLocation() {
mLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
String lastUpdateTime = DateFormat.getTimeInstance().format(new Date());
dbHelper.insertLocationDetails(longitude, latitude, lastUpdateTime);
locationList = dbHelper.getLocationDetails();
return locationList;
} else {
return null;
}
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Connected to update");
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void onLocationChanged(Location location) {
mLocation = location;
Toast.makeText(getApplicationContext(), "Location changed",
Toast.LENGTH_SHORT).show();
displayLocation();
}
public void onConnected(Bundle arg0) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
public class LocalBinder extends Binder {
public LocationService getService() {
return LocationService.this;
}
}
}
Dbhelper
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String LONGITUDE = "longitude";
private static final String LATITUDE = "latitude";
private static final String LOCATION_CHANGE_TIME = "location_change_time";
private static final String LOCATION_DETAIL_TABLE = "location_detail_table";
private static final String CREATE_TABLE_LOCATION = "CREATE TABLE "
+ LOCATION_DETAIL_TABLE + " (" + LONGITUDE + " TEXT,"
+ LOCATION_CHANGE_TIME + " TEXT,"
+ LATITUDE + " TEXT)";
public static String DATABASE_NAME = "Location_database";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(CREATE_TABLE_LOCATION);
}
public void insertLocationDetails(double longitude, double latitude, String time) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(LONGITUDE, longitude);
values.put(LATITUDE, latitude);
values.put(LOCATION_CHANGE_TIME, time);
long id= database.insert(LOCATION_DETAIL_TABLE, null, values);
System.out.println("Newly added item id "+id);
database.close();
}
public ArrayList<MyLocation> getLocationDetails() {
ArrayList<MyLocation> locationList = new ArrayList();
String selectQuery = "SELECT * FROM " + LOCATION_DETAIL_TABLE;
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToNext()) {
do {
MyLocation location = new MyLocation();
String longitude = cursor.getString(cursor
.getColumnIndexOrThrow(LONGITUDE));
String latitude = cursor.getString(cursor.getColumnIndexOrThrow(LATITUDE));
String time = cursor.getString(cursor
.getColumnIndexOrThrow(LOCATION_CHANGE_TIME));
location.setLatitude(latitude);
location.setLongitude(longitude);
location.setLastUpdatedTime(time);
locationList.add(location);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
database.close();
return locationList;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
In your case, you can use ContentProvider and implements LoaderManager.LoaderCallbacks in your activity.
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
db = dbHelper.getWritableDatabase();
String table = uri.getLastPathSegment();
long rowID = db.insert(table, null, values);
Uri CONTENT_URI = Uri.parse("content://"
+ AUTHORITY + "/" + table);
Uri resultUri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(resultUri, null);
return resultUri;
}
Line
getContext().getContentResolver().notifyChange(resultUri, null);
in ContentProvider will cause requery data. And using SimpleAdapter in activity will update your UI.
You can use Callback for this purpose.
Define some interface like
public class LocationInterface(){
public void sendLocationDetails(Long lat, Long lon, String time);
}
Now let your Activity implement this interface.
public class MyActivity implements LocationInterface {
#Override
public void sendLocationDetails(Long lat, Long lon, String time){
//At this point, you have the required details
}
}
Now in LocationService.java you need to pass this interface as an argument.
public class LocationService {
private LocationInterface locationInterface;
LocationInterface(LocationInterface locationInterface){
this.locationInterface = locationInterface;
}
}
Now whenever you call displayLocation() method, you can call this interface and send data to the activity.
public List<MyLocation> displayLocation() {
mLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
String lastUpdateTime = DateFormat.getTimeInstance().format(new Date());
//At this point, you are calling the interface.
locationInterface.sendDetails(latitude,longitude,lastUpdateTime);
dbHelper.insertLocationDetails(longitude, latitude, lastUpdateTime);
locationList = dbHelper.getLocationDetails();
return locationList;
} else {
return null;
}
}

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