Android onLocationChanged does not called - java

I am trying to implement a background GPS location service in android using Service and LocationListener. The service is started (-> the onCreate and onStartCommand methods are called), but the onLocationChanged method never called.
Here is the code of my Service:
public class GpsHandler extends Service implements LocationListener{
private static final String TAG = "GpsHandler";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private final String LOCATION_BROADCAST_TAG = "android.LOCATION";
private final String LOCATION_EXTRA_TAG = "Location";
private Location mLastLocation = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Toast.makeText(this, "Service Started, onCreate", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started, onStartCommand", Toast.LENGTH_LONG).show();
if (mLocationManager == null)
{
mLocationManager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
mLastLocation = new Location(LocationManager.GPS_PROVIDER);
try {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, this);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mLocationManager != null)
{
try {
mLocationManager.removeUpdates(this);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getBaseContext(), "Gps is turned off!! ",
Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location)
{
Toast.makeText(this, "Location Changed", Toast.LENGTH_LONG).show();
if(isBetterLocation(location,mLastLocation))
{
mLastLocation.set(location);
Intent intent = new Intent(LOCATION_BROADCAST_TAG).putExtra(LOCATION_EXTRA_TAG, location);
sendBroadcast(intent);
}
}
#Override
public void onProviderEnabled(String provider){}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){}
private boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > 1000*30;//30000ms = 30 sec
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer)
{
return true;
// If the new location is more than two minutes older, it must be worse
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
}

Finally I have found the solution. I have tried to debug it with an other emulator (Originally I have used Pixel C emulator) and now it works flawless. So it is just a Studio Bug, the code is working.I have also restructured the code a bit, removing some useless functions:
Working code:
public class GpsHandler extends Service implements LocationListener{
private static final String TAG = "GpsHandler";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0f;
private final String LOCATION_BROADCAST_TAG = "android.LOCATION";
private final String LOCATION_EXTRA_TAG = "Location";
private Location mLastLocation = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Toast.makeText(this, "Service Started, onCreate", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started, onStartCommand", Toast.LENGTH_LONG).show();
if (mLocationManager == null)
{
mLocationManager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
mLastLocation = new Location(LocationManager.GPS_PROVIDER);
try {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, this);
mLastLocation.set(mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mLocationManager != null)
{
try {
mLocationManager.removeUpdates(this);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getBaseContext(), "Gps is turned off!! ",
Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location)
{
Toast.makeText(this, "Location Changed", Toast.LENGTH_LONG).show();
if(location.getAccuracy()<4*mLastLocation.getAccuracy())
{
mLastLocation.set(location);
Intent intent = new Intent(LOCATION_BROADCAST_TAG).putExtra(LOCATION_EXTRA_TAG, location);
sendBroadcast(intent);
}
}
#Override
public void onProviderEnabled(String provider){}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){}
}

Related

Call the method when the device is within 10 meters of the marker

In my app, I get the coordinates of my device. Now I'm trying to make it so that when the device is within a radius of 10 meters, the method is called. Found the addProximityAlert method. But there you need to pass the coordinates of the point I need, but I do not know how to link the marker I need and the position of the device. I have already created a broadcastreceiver. Please help with advice or an article.
public void getlocate() {
if (flag) {
Intent intent = new Intent("com.runline.workertrack");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, -1, intent, 0);
try {
enable = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception e) {
e.printStackTrace();
}
if (enable) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 5, listener);
manager.addProximityAlert(0,0 , 100, -1, pendingIntent);
}
}
}
public boolean checkLocationPermission()
{
int loc1 = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listper = new ArrayList<>();
if(loc1 != PackageManager.PERMISSION_GRANTED)
listper.add(Manifest.permission.ACCESS_FINE_LOCATION);
if(!listper.isEmpty()) {
ActivityCompat.requestPermissions(this, listper.toArray(new String[listper.size()]), 1);
}
return true;
}
class Locate implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
manager.removeUpdates(listener);
shirota = "" + location.getLatitude();
dolgota = "" + location.getLongitude();
shir.setText(shirota);
dolg.setText(dolgota);
final Map<String, Object> hashMap = new HashMap<>();
hashMap.put("shirota", shirota);
hashMap.put("dolgota", dolgota);
hashMap.put("id", "1");
reference.setValue(hashMap);
IntentFilter filter = new IntentFilter("com.runline.workertrack");
registerReceiver(new ProximityIntentReceiver(), filter);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
public class ProximityIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive (Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if(entering){
Toast.makeText(getApplicationContext(), "You are here!", Toast.LENGTH_LONG).show();
}
}
}

How to receive location updates in background? (API 26)

I need to get continuous location updates from the application for my application. To do so, I followed the Android Developer Guide to get location updates. Because location updates can't be received in background in API 26, I added a foreground service (Background location limits). However, I still only receive updates when an other activity which requests location updates is in the foreground.
Location Service:
public class LocationUpdateService extends Service {
private static final String TAG = LocationUpdateService.class.getSimpleName();
private static final String NOTIFICATION_CHANNEL_ID = "TrackNotification";
private static final int FOREGROUND_SERVICE_ID = 1;
private static final int NOTIFICATION_ID = 1;
public static final String STATUS_INTENT = "status";
private static final int CONFIG_CACHE_EXPIRY = 600;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mNotificationBuilder;
private DatabaseReference mDatabaseReference;
private FusedLocationProviderClient mFusedLocationProviderClient;
private LocationRequest mLocationRequest;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
private String uid;
#Override
public void onCreate() {
super.onCreate();
uid = FirebaseAuth.getInstance().getUid();
if(uid == null)
stopSelf();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder().build();
mFirebaseRemoteConfig.setConfigSettings(configSettings);
mFirebaseRemoteConfig.setDefaults(R.xml.remode_config_defaults);
fetchRemoteConfig();
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mLocationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setFastestInterval(mFirebaseRemoteConfig.getLong("LOCATION_REQUEST_INTERVAL"))
.setFastestInterval(mFirebaseRemoteConfig.getLong("LOCATION_REQUEST_INTERVAL_FASTEST"));
bindNotification();
setStatusMessage(R.string.connecting);
startLocationTracking();
}
private LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Log.d(TAG,"Got location update!");
if(locationResult == null)
return;
for(Location location : locationResult.getLocations()) {
CustomLocation customLocation = LocationAdapter.toDatabaseLocation(location);
mDatabaseReference.child("locations").child(uid).setValue(customLocation);
}
}
#Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
locationAvailability.isLocationAvailable();
// TODO handle no location here
super.onLocationAvailability(locationAvailability);
}
};
#SuppressWarnings({"MissingPermission"})
private void startLocationTracking() {
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest,mLocationCallback, Looper.myLooper());
}
private void fetchRemoteConfig() {
mFirebaseRemoteConfig.fetch(CONFIG_CACHE_EXPIRY)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.i(TAG,"Remote config fetched");
mFirebaseRemoteConfig.activateFetched();
}
});
}
#Override
public void onDestroy() {
setStatusMessage(R.string.not_tracking);
mNotificationManager.cancel(NOTIFICATION_ID);
mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) { return null; }
private void bindNotification() {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,
new Intent(this, MainActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);
mNotificationBuilder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID)
.setCategory(NotificationCompat.CATEGORY_STATUS)
.setShowWhen(false)
.setSmallIcon(R.drawable.ic_car)
// .setColor(getColor(R.color.colorPrimary))
.setContentTitle(getString(R.string.app_name))
.setOngoing(true)
.setContentIntent(resultPendingIntent);
startForeground(FOREGROUND_SERVICE_ID, mNotificationBuilder.build());
}
/**
*
* #param message Status message to display
*/
private void setStatusMessage(String message) {
mNotificationBuilder.setContentText(message);
mNotificationManager.notify(NOTIFICATION_ID, mNotificationBuilder.build());
Intent intent = new Intent(STATUS_INTENT);
intent.putExtra(getString(R.string.status),message);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void setStatusMessage(int resID) {
setStatusMessage(getString(resID));
}
}
And I gets started with
startService(new Intent(this,LocationUpdateService.class));
Android Manifest:
<service android:name=".LocationUpdateService" />
EDIT1: I now tested it on older API versions (22) and the problem is still the same: As long as some app with location requests is in the foreground it works, otherwise not.
Maybe it's a problem with the FusedLocationProviderClient but I don't know what. I only found code examples with the old FusedLocationProvider API which is now deprecated.
Have you tried debugging to make sure your service is being hit?
This might sound silly, but have you checked if your service is registered in your manifest? I know I've definitely run into that issue.
<service android:name=".LocationService"
android:label="Location Service"
android:exported="true"
android:enabled="true"
android:process=":location_background_service"/>
For getting the location, when I set mine up, I created a class that implemented android.location.LocationListener.
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);
}
}
You can create multiple instances for different providers. In my case, I ended up using 2.
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
Then I initialized a LocationManager that can set a polling rate for each a LocationListener.
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
Then in your Service onCreate function, initialize your LocationManager, and use one of the listeners as your main source and the other as a fallback.
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
5 * 60 * 1000, //5 Minutes
1F /*METERS*/,
mLocationListeners[0]
);
} catch (java.lang.SecurityException ex) {
Log.e(TAG, "failed to request location update. Insufficient permissions. ", ex);
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
5 * 60 * 1000, //5 Minutes
1F /*METERS*/,
mLocationListeners[1]
);
} catch (java.lang.SecurityException e) {
Log.e(TAG, "failed to request location update. Insufficient permissions. ", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Network provider does not exist.", e);
}
} catch (IllegalArgumentException ex) {
Log.e(TAG, "Network provider does not exist.", ex);
}
}
(Sorry if this code is gross, it's a quick and dirty example.)

Get ride of 0.0 location using google locationManager

I am using google location to get the location based on the best provider, so i am running that on a service, the service is responsable to update location based on a defined distance and time.
Everything is working well when i update my location, but i wanna get ride of the 0.0 location, when i doesn't update the location i need to get the current location, or to use the lastknowlocation how can i do it using my code below?
public class MyService extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private final IBinder mBinder = new LocalBinder();
private Intent intent;
Context context;
Location mLastLocation;
public class LocalBinder extends Binder {
public MyService getServerInstance() {
return MyService.this;
}
}
public Location getLocation(){
return mLastLocation;
}
private class LocationListener implements android.location.LocationListener
{
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.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
context = getApplicationContext();
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
//mLastLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} 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());
}
try {
//mLastLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mLocationManager.requestLocationUpdates(
LocationManager.GPS_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, "gps 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 {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
**main activity call of the service**
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askPermission();
}
public void nextAct(View view){
Intent i = new Intent(this,GpsGetCoordinates.class);
startActivity(i);
}
public static final int REQ_PERMISSION = 99;
private boolean checkPermission() {
// PEDE PERMISSÃO SE A MESMA AINDA NÃO TIVER SIDO CONCEDIDA
return (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED );
}
// PEDIDO DE PERMISSÃO
private void askPermission() {
ActivityCompat.requestPermissions(
this,
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
REQ_PERMISSION);
}
// VERIFICAÇÃO DA RESPOSTA DO UTILIZADOR AO PEDIDO DE PERMISSÃO
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull
String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch ( requestCode ) {
case REQ_PERMISSION: {
if ( grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED ){
Log.d("PERMISSAO","DADA");
startService(new Intent(this, MyService.class));
} else {
// PERMISSÃO NEGADA
Log.w("fail", "permissionsDenied()");
}
break;
}
}
}
public void onResume() {
super.onResume();
}
}
When you get a location that is !=0.0, store it in a variable, or in Shared Preferences, or anywhere else you want. Then the next time you get 0.0 from locationManager, just use the latest real value that you stored previously.

Android - Service takes a long time to restart when forcibly killed

When I kill all the apps (including my app) running using a task killer, the service shows Restarting for a long time.
How do I improve on this ?
The best case scenario would be like, as soon as the app/service is killed, the service would spring up immediately or within the slightest delay possible.
WLANSrvice.java
public class WLANService extends Service {
String username, password, ssid, url;
private static final String CREDENTIALS = "Credentials";
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = getSharedPreferences(CREDENTIALS, 0);
if(sharedPreferences.contains("username")) {
username = sharedPreferences.getString("username", "UNDEFINED");
}
if(sharedPreferences.contains("password")) {
password = sharedPreferences.getString("password", "UNDEFINED");
}
if(sharedPreferences.contains("ssid")) {
ssid = sharedPreferences.getString("ssid", "UNDEFINED");
}
if(sharedPreferences.contains("url")) {
url = sharedPreferences.getString("url", "UNDEFINED");
}
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
boolean connected = info.isConnected();
if(connected) {
Toast.makeText(context, "WIFI CONNECTED!", Toast.LENGTH_LONG).show();
Log.i("Wi-Fi-State", "Wi-Fi is On!");
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if(wifiInfo.getSSID().contains(ssid) == true) {
try {
String output = new Connection().execute().get().toString();
Log.i("LoginState", new Connection().execute().get().toString());
if(output.contains("Address")) {
Toast.makeText(WLANService.this, "Login Success!", Toast.LENGTH_SHORT).show();
Intent account_info_intent = new Intent(WLANService.this, AccountInfo.class);
account_info_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(account_info_intent);
}else {
if(output.contains("n/a")) {
Toast.makeText(WLANService.this, "Login Failed!", Toast.LENGTH_SHORT).show();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(context, "WIFI DISCONNECTED!", Toast.LENGTH_SHORT).show();
//Log.i("Wi-Fi-State", "Wi-Fi is Off!");
}
}
};
public WLANService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Auto-Login Enabled!", Toast.LENGTH_SHORT).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// registering your receiver
registerReceiver(receiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Auto-Login Disabled!", Toast.LENGTH_SHORT).show();
unregisterReceiver(receiver);
super.onDestroy();
}
private class Connection extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
String formatted_url = url.replace("http://", "");
String true_url;
if(formatted_url.charAt((formatted_url.length()-1)) != '/') {
true_url = formatted_url.concat("/");
}else {
true_url = formatted_url;
}
Log.i("formatted_url", formatted_url);
Log.i("true_url", true_url);
return LoginHelper.doLogin(username, password, "http://".concat(true_url));
}
}
}

Android: Firebase Update Issue When the app is in background

Hey I m going to develop an location tracker app in which, this app in client device which constantly send it location to the firebase db.
Here the problem is that it will send the data to firebase only first 3 minutes then it wont. I don't know whats happening. ?
For that even i put a log message that log message is printed perfectly even after three minutes
Any one please help on this........!
Here i attached 3 file One BackgroundLocation: Which is the service in background which will extract the device location and call the LocationReceiver which extends broadcast receiver where it will print log message and send the data to firebase through FBSender.
Thanks in advance
BackgroundLocation.java
Which runs in Background to get the location details and call the broadcast Reveiver. LocationReveiver.java
/**
* Created by geekyint on 1/7/16.
*/
public class BackgroundLocation extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
IBinder mBinder = new LocalBinder();
private GoogleApiClient mGoogleApiClient;
private PowerManager.WakeLock mWakeLock;
private LocationRequest mlocationRequest;
//Flag for boolean request
private boolean mInProgress;
private boolean serviceAvailabe = false;
public class LocalBinder extends Binder {
public BackgroundLocation getServerInstance() {
return BackgroundLocation.this;
}
}
#Override
public void onCreate() {
super.onCreate();
mInProgress = false;
//Create the lcoation request object
mlocationRequest = LocationRequest.create();
//Use the acurecy
mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//The INTERVAL
mlocationRequest.setInterval(Constants.UPDATE_INTERVAL);
//The FAST INTERVAL
mlocationRequest.setFastestInterval(Constants.FAST_INTERVAL);
serviceAvailabe = serviceConnected();
setUpALocationClientIfNeeded();
ComponentName receiver = new ComponentName(this, LocationReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
/*ComponentName receiver1 = new ComponentName(this, FireBaseSender.class);
PackageManager pm1 = this.getPackageManager();
pm1.setComponentEnabledSetting(receiver1,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);*/
}
private void setUpALocationClientIfNeeded() {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
}
//Create the new Connection to the client
private void buildGoogleApiClient() {
this.mGoogleApiClient = new GoogleApiClient.Builder(this)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
private boolean serviceConnected() {
//Check the google Play service availibility
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
//IF AVAILABLE
if (resultCode == ConnectionResult.SUCCESS) {
return true;
} else {
return false;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (this.mWakeLock == null) {
this.mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
}
if (!this.mWakeLock.isHeld()) {
this.mWakeLock.acquire();
}
if (!serviceAvailabe || mGoogleApiClient.isConnected() || mInProgress) {
return START_STICKY;
}
setUpALocationClientIfNeeded();
if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting() || !mInProgress) {
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Started", Constants.LOG_FILE);
mInProgress = true;
mGoogleApiClient.connect();
}
return START_STICKY;
}
#Override
public void onLocationChanged(Location location) {
String msg = Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Log.d("debug", msg);
// Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ":" + msg, Constants.LOCATION_FILE);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public String getTime() {
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return mDateFormat.format(new Date());
}
public void appendLog(String text, String filename) {
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDestroy() {
// Turn off the request flag
this.mInProgress = false;
if (this.serviceAvailabe && this.mGoogleApiClient != null) {
this.mGoogleApiClient.unregisterConnectionCallbacks(this);
this.mGoogleApiClient.unregisterConnectionFailedListener(this);
this.mGoogleApiClient.disconnect();
// Destroy the current location client
this.mGoogleApiClient = null;
}
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ":
// Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
if (this.mWakeLock != null) {
this.mWakeLock.release();
this.mWakeLock = null;
}
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Stopped", Constants.LOG_FILE);
ComponentName receiver = new ComponentName(this, LocationReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
/*
ComponentName receiver1 = new ComponentName(this, FireBaseSender.class);
PackageManager pm1 = this.getPackageManager();
pm1.setComponentEnabledSetting(receiver1,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);*/
super.onDestroy();
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
#Override
public void onConnected(Bundle bundle) {
// Request location updates using static settings
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;
}
Intent intent = new Intent (this, LocationReceiver.class);
PendingIntent pendingIntent = PendingIntent
.getBroadcast(this, 54321, intent, PendingIntent.FLAG_CANCEL_CURRENT);
LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient,
mlocationRequest, pendingIntent);
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
#Override
public void onConnectionSuspended(int i) {
// Turn off the request flag
mInProgress = false;
// Destroy the current location client
mGoogleApiClient = null;
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected", Constants.LOG_FILE);
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
mInProgress = false;
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
// If no resolution is available, display an error dialog
} else {
}
}
}
Here The LocationReceiver Code:
public class LocationReceiver extends BroadcastReceiver {
private String TAG = this.getClass().getSimpleName();
private LocationResult mLocationResult;
private double latitude;
private double longitude;
private double speed;
private String time;
#Override
public void onReceive(Context context, Intent intent) {
// Need to check and grab the Intent's extras like so
if(LocationResult.hasResult(intent)) {
this.mLocationResult = LocationResult.extractResult(intent);
//new SaveToFireB().insertToFireBase(mLocationResult.getLastLocation());
new FBSender().put(mLocationResult.getLastLocation());
Log.i(TAG, "Location Received: " + this.mLocationResult.toString());
String msg = String.valueOf(mLocationResult.getLastLocation().getLongitude()) + " " +
String.valueOf(mLocationResult.getLastLocation().getLatitude());
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ":" + msg, Constants.LOCATION_FILE);
}
}
public void appendLog(String text, String filename) {
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here Which will call FBSender to send the data to firebase.
Ther real problems comes here.
It will send the data only in first three minutes then it wont send the data to firebase
For confirmation whether the control going there or not i put log message there that log message will be printed perfectly even after 3 minutes from the start of the app
Here is FBSender.Java
public class FBSender extends Service {
private String TAG = "FBSender";
private double latitude;
private double longitude;
private double speed;
private String time;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void put (Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
speed = location.getSpeed();
time = DateFormat.getTimeInstance().format(new Date());
Log.e(TAG, "Entering the run ()");
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference reference = database.getReference("users/" + user.getUid() + "/vehicles");
Log.e(TAG, "I M in the middle");
Map mLocations = new HashMap();
mLocations.put("latitude", latitude);
mLocations.put("longitude", longitude);
mLocations.put("speed", speed);
mLocations.put("time", time);
reference.setValue(mLocations);
Log.e(TAG, "Exiting The run ()");
}
}
To get more information about why the database writes are not completing after 3 minutes, add a CompetionListener to your setValue():
reference.setValue(mLocations, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Log.i(TAG, "onComplete: OKAY");
} else {
Log.e(TAG, "onComplete: FAILED " + databaseError.getMessage());
}
}
});
When you hit the 3 minute mark, if the callback fires with an error, such as permission failure, you can investigate why. If it stops firing at all, that probably means you've lost connection with the Firebase server. You can monitor the connection status using a listener, as described in the documentation.

Categories