Starting a BroadcastReceiver from activity - android

I'm trying to start a BroadcastReceiver from an activity - and it seems the receiver doesnt start and I dont get any output in logCat for it.
Im trying to start the receiver by doing this:
Intent intent = new Intent();
intent.setAction(getPackageName()+".mybroadcast");
sendBroadcast(intent);
Also here is my receiver class:
public class TriggerReceiver extends BroadcastReceiver implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private Vibrator v;
private CountDownTimer timer;
private final long INTERVAL = 1000;
private final long TWO_MINUTES = INTERVAL * 60 * 2;
// === variables
private Context context;
private final String TAG = TriggerReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
Log.e(TAG, "Trigger receiver starting");
v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
mRequestingLocationUpdates = false;
buildGoogleApiClient();
mGoogleApiClient.connect();
}
//
private void startTimer(final Location location) {
String message = context.getString(R.string.emergency_text).replace("/location here/", getMapLink(location));
sendSMS(message);
showNotification();
Log.e(TAG, " sending sms and this is the location " + location.getLatitude() + " " + location.getLongitude());
timer = new CountDownTimer(TWO_MINUTES, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
Log.e(TAG, "Tick " + (millisUntilFinished / 1000));
int elapsedTime = (int) ((millisUntilFinished / 1000) % 60);
int minutes = (int) ((millisUntilFinished / 1000) / 60);
Log.e(TAG, elapsedTime + " | " + minutes);
if (minutes == 2) {
minutes = 1;
elapsedTime = 60;
}
}
//TODO start activity and pass extras to intent
#Override
public void onFinish() {
startTimer(mCurrentLocation);
}
}.start();
}
private void sendSMS(String message) {
ArrayList<Contact> contacts = ((BaseActivity) context).getContacts();
for (Contact contact : contacts) {
sendSMSmsg(contact.getNumber(), message);
}
}
private void stopTimer() {
timer.cancel();
}
/*location*/
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Stores parameters for requests to the FusedLocationProviderApi.
*/
protected LocationRequest mLocationRequest, quickLocationRequest;
/**
* Represents a geographical location.
*/
protected Location mCurrentLocation, mLastLocation;
protected Boolean mRequestingLocationUpdates;
/**
* Builds a GoogleApiClient. Uses the {#code #addApi} method to request the
* LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
protected void createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(110000);
mLocationRequest.setFastestInterval(55000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected void doQuickLocationUpdate() {
quickLocationRequest = new LocationRequest();
quickLocationRequest.setInterval(1000);
quickLocationRequest.setFastestInterval(500);
quickLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, quickLocationRequest, this);
}
protected void stopLocationUpdates() {
//TODO add this in onbackpresses and onStop
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
startTimer(mLastLocation);
} else {
doQuickLocationUpdate();
}
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.d(TAG, "onConnected mCurrentLocation = " + mCurrentLocation.getLatitude());
}
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
if (quickLocationRequest != null) {
quickLocationRequest = null;
}
if (timer == null) {
startTimer(location);
}
Log.d(TAG, "onLocationChanged mCurrentLocation = " + mCurrentLocation.getLatitude());
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
public void sendSMSmsg(String phoneNumber, String message) {
v.vibrate(50);
// ArrayList<PendingIntent> sentPendingIntents = new ArrayList<PendingIntent>();
// ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<PendingIntent>();
// PendingIntent sentPI = PendingIntent.getBroadcast(context, 0,
// new Intent(context, SmsSentReceiver.class), 0);
// PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0,
// new Intent(context, SmsDeliveredReceiver.class), 0);
// try {
// SmsManager sms = SmsManager.getDefault();
// ArrayList<String> mSMSMessage = sms.divideMessage(message);
// for (int i = 0; i < mSMSMessage.size(); i++) {
// sentPendingIntents.add(i, sentPI);
// deliveredPendingIntents.add(i, deliveredPI);
// }
// sms.sendMultipartTextMessage(phoneNumber, null, mSMSMessage,
// sentPendingIntents, deliveredPendingIntents);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
}
public void showNotification() {
NotificationCompat.Builder mBuilder;
if (Build.VERSION.SDK_INT >= 16) {
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.sosicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentTitle(context.getString(R.string.app_name))
.setAutoCancel(true)
.setContentText(context.getString(R.string.notification_text));
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent();
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(10142, mBuilder.build());
}
}
public String getMapLink(Location location) {
if (location != null) {
Log.d(TAG, "http://maps.google.com/maps?z=12&t=m&q=loc:" + location.getLatitude() + "+" + location.getLongitude());
return "http://maps.google.com/maps?z=12&t=m&q=loc:" + location.getLatitude() + "+" + location.getLongitude();
} else {
return null;
}
}
//
}
and also the declaration in the manifest:
<receiver
android:name=".TriggerReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="PACKAGENAME.mybroadcast" />
</intent-filter>
</receiver>
So what can be wrong here and why is the receiver not starting?
Thanks

Related

Location Update not working in OPPO, VIVO and MI Phones on Oreo

I am updating the location in the background every 5 minutes.
I checked below code in Android Oreo and above in Samsung and Motorola Devices. It is working fine. But when I checked in MI, OPPO and VIVO, location is not updating if I remove an application from recent task.
I checked this solution but didn't work.
public class GpsTracker extends Service
implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, LocationListener {
final static int REQUEST_LOCATION = 199;
private static final String TAG = GpsTracker.class.getSimpleName();
private static final int PERMISSIONS_REQUEST_PLAYLOCATION = 2000;
private static final int PERMISSIONS_REQUEST_LOCATION = 2001;
public static boolean IS_SERVICE_RUNNING = false;
protected LocationManager locationManager;
private PowerManager pm;
private PowerManager.WakeLock wl;
private Handler handler = new Handler();
private boolean mPlayLocationPermissionGranted;
private boolean mLocationPermissionGranted;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
private LocationTypes locationTypes = LocationTypes.HEARTBEAT;
private GPSTrackerVM gpsTrackerVM;
private boolean noConnect = true;
private Runnable periodicUpdate = new Runnable() {
#Override
public void run() {
handler.postDelayed(periodicUpdate, 5 * 60 * 1000 - SystemClock.elapsedRealtime() % 1000);
// whatever you want to do below
Utils.Log(TAG, "run: Service");
locationTypes = LocationTypes.HEARTBEAT;
buildGoogleApiClient();
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction() != null) {
showNotification();
Utils.Log(TAG, "onStartCommand: " + intent.getAction());
switch (intent.getAction()) {
case AppConfig.ACTION.START_FOREGROUND_ACTION:
Utils.Log(TAG, "Uploading Start");
locationTypes = LocationTypes.HEARTBEAT;
handler.post(periodicUpdate);
break;
case AppConfig.ACTION.START_DAY:
locationTypes = LocationTypes.IN;
buildGoogleApiClient();
break;
case AppConfig.ACTION.END_DAY:
locationTypes = LocationTypes.OUT;
buildGoogleApiClient();
break;
}
}
return START_STICKY;
}
#Override
public void onCreate() {
gpsTrackerVM = new GPSTrackerVM(MyApp.getInstance());
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp:GpsTracker");
wl.acquire();
}
#Override
public void onDestroy() {
IS_SERVICE_RUNNING = false;
super.onDestroy();
wl.release();
}
private void mStopService() {
Utils.Log(TAG, "Sync Stop");
if (handler != null) {
handler.removeCallbacks(periodicUpdate);
}
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
stopForeground(true);
stopSelf();
}
private void showNotification() {
if (!IS_SERVICE_RUNNING) {
String channelId = AppConfig.NOTIFICATION_ID.SYNC_CHANNEL;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channelId = createmNotificationChannel();
}
Intent notificationIntent = new Intent();
notificationIntent.setAction(AppConfig.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_logo_notification);
Notification notification = new NotificationCompat.Builder(this, channelId)
.setContentTitle(getString(R.string.app_name))
.setTicker(getString(R.string.res_sync))
.setContentText(getString(R.string.res_sync))
.setSmallIcon(R.drawable.ic_logo_notification)
.setPriority(Notification.PRIORITY_DEFAULT)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
startForeground(AppConfig.NOTIFICATION_ID.FOREGROUND_SERVICE_SYNC,
notification);
IS_SERVICE_RUNNING = true;
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private String createmNotificationChannel() {
String channelId = AppConfig.NOTIFICATION_ID.SYNC_CHANNEL;
String channelName = AppConfig.NOTIFICATION_ID.SYNC_CHANNEL;
NotificationChannel chan = new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_DEFAULT);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
service.createNotificationChannel(chan);
return channelId;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public synchronized void buildGoogleApiClient() {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
retrieveCurrentLocation();
return;
}
mGoogleApiClient = new GoogleApiClient.Builder(MyApp.getInstance())
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
mGoogleApiClient.connect();
}
public synchronized void stopLocationUpdates() {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
// mGoogleApiClient.disconnect();
}
}
private void createLocationRequest() {
long UPDATE_INTERVAL_IN_MILLISECONDS = 100000;
long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
retrieveCurrentLocation();
}
private void retrieveCurrentLocation() {
Log.d(TAG, "retrieveCurrentLocation: 11");
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// get GPS status
boolean checkGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!checkGPS) {
Utils.Log(TAG, "retrieveCurrentLocation: GPS is Off");
updateCurrentLocation(null, "GPS is Turned Off");
return;
}
if (!hasLocationPermissions()) {
Utils.Log(TAG, "retrieveCurrentLocation: Location Permission Denied");
updateCurrentLocation(null, "Location Permission Denied");
return;
}
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult result) {
mPlayLocationPermissionGranted = false;
final Status status = result.getStatus();
final LocationSettingsStates states = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
mPlayLocationPermissionGranted = true;
requestLocations();
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
mPlayLocationPermissionGranted = false;
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Utils.Log(TAG, "retrieveCurrentLocation: GPS is On, but they need to allow location access from Settings");
updateCurrentLocation(null, "GPS is On, but they need to allow location access from Settings");
break;
}
}
});
}
private void requestLocations() {
Log.d(TAG, "requestLocations: 11");
try {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mCurrentLocation == null) {
noConnect = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (noConnect) {
updateCurrentLocation(null, "GPS is On, but your device needs one restart to continue locating the device.");
}
}
}, 1000);
}
// updateCurrentLocation(mCurrentLocation);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
} catch (SecurityException ex) {
ex.printStackTrace();
}
}
private boolean hasLocationPermissions() {
if (ActivityCompat.checkSelfPermission(MyApp.getInstance(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(MyApp.getInstance(),
Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED
) {
mLocationPermissionGranted = true;
} else {
mLocationPermissionGranted = false;
}
return mLocationPermissionGranted;
}
#Override
public void onLocationChanged(Location location) {
Utils.LogW(TAG, "onLocationChanged: " + location.toString());
if (noConnect) {
noConnect = false;
}
updateCurrentLocation(location, "None");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed: ");
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended: ");
}
public void updateCurrentLocation(Location location, String remark) {
mCurrentLocation = location;
GPSData gpsData = new GPSData(UUID.randomUUID().toString());
gpsData.setLatitude(location == null ? 0 : location.getLatitude());
gpsData.setLongitude(location == null ? 0 : location.getLongitude());
gpsData.setAddress("None");
gpsData.setRemarks(remark);
gpsData.setTimeStamp(System.currentTimeMillis() / 1000L);
gpsData.setLocationType(locationTypes.getValue());
// Log.w(TAG, "updateCurrentLocation: " + location);
stopLocationUpdates();
if (locationTypes == LocationTypes.IN) {
Utils.Log(TAG, "In Success ");
Intent startIntent = new Intent(this, GpsTracker.class);
startIntent.setAction(AppConfig.ACTION.START_FOREGROUND_ACTION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(startIntent);
} else {
startService(startIntent);
}
} else if (locationTypes == LocationTypes.OUT) {
Utils.Log(TAG, "out Success ");
mStopService();
} else if (locationTypes == LocationTypes.HEARTBEAT) {
Utils.Log(TAG, "HEARTBEAT Success ");
}
serverUpdate(gpsData);
}
private void serverUpdate(GPSData gpsData) {
gpsTrackerVM.updateLocation(gpsData);
}
public void onPermissionGrantStatus(boolean isGratned) {
Log.d(TAG, "onPermissionGrantStatus() called with: isGratned = [" + isGratned + "]");
}
}
In AndroidManifest.xml
<service android:name=".services.GpsTracker" />

Detect GPS in case if Disabled

I want to detect user trip and when trip is started, I have to get LatLng in every 5 seconds. I am using Google FusedLocationAPI and My problem is until My GPS is enabled then its calculating all distance but Once I disabled GPS the its stucked. How can I Show pending trip if user Disabled GPS in mid of trip ?
My Service class is :
public class TripStartedService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static long UPDATE_INTERVAL_IN_MILLISECONDS = 1000 * 5;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
public GoogleApiClient mGoogleApiClient;
public LocationRequest mLocationRequest;
private PendingIntent mPendingIntent;
IBinder mBinder = new TripStartedService.LocalBinder();
public static boolean isGPSOn = false;
#Override
public void onCreate() {
super.onCreate();
Intent mIntentService = new Intent(this, TripStartedIntent.class);
mPendingIntent = PendingIntent.getService(this, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
Log.i("", "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
private void createLocationRequest() {
Log.i("TRIP_START_Request", "createLocationRequest()");
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
Log.i("", "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i("", "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
#Override
public void onLocationChanged(Location location) {
String message = "Latitude : " + location.getLatitude() + "\n Longitude : " + location.getLongitude() + "\n Accuracy: " + location.getAccuracy();
Log.i("", "onLocationChanged: " + message);
}
private void startLocationUpdates() {
Log.i("", "Started Location Updates");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mPendingIntent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
isGPSOn = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (mGoogleApiClient.isConnected()) {
Log.i("GPS init" + " onStartCmd", "Connected");
return START_STICKY;
}
if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) {
Log.i("Connceti" + " onStartCmd", "GoogleApiClient not Connected");
mGoogleApiClient.connect();
}
return START_STICKY;
}
private class LocalBinder extends Binder {
public TripStartedService getServerInstance() {
return TripStartedService.this;
}
}
#Override
public void onDestroy() {
super.onDestroy();
stopLocationUpdates();
}
public void stopLocationUpdates() {
Log.i("", "Stopped Location Updates");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mPendingIntent);
}
}
And My Calculation Class is
if (isGPSOn) {
try {
LocDatabaseHelper database = new LocDatabaseHelper(activity);
Timestamp timestamp_start = new Timestamp(System.currentTimeMillis());
Timestamp timestamp_end = new Timestamp(System.currentTimeMillis());
final int TRIP_START_ID = 0;
ContentValues contentValues = new ContentValues();
final ArrayList<TripDistanceModels> trip_list_values = database.getTripDistance();
try {
Location loc1 = new Location("");
loc1.setLatitude(Double.parseDouble(trip_list_values.get(0).getLatitude()));
loc1.setLongitude(Double.parseDouble(trip_list_values.get(0).getLongitude()));
Location loc2 = new Location("");
loc2.setLatitude(Double.parseDouble(trip_list_values.get(1).getLatitude()));
loc2.setLongitude(Double.parseDouble(trip_list_values.get(1).getLongitude()));
} catch (Exception e) {
e.printStackTrace();
}
contentValues.put(TRIP_STARTED_ID, TRIP_START_ID);
contentValues.put(TRIP_STARTED_LATTITUDE, start_trip_location.getLatitude());
contentValues.put(TRIP_STARTED_LONGITUDE, start_trip_location.getLongitude());
contentValues.put(TRIP_STARTED_TIMESTAMP, String.valueOf(timestamp_start));
contentValues.put(TRIP_END_TIMESTAMP, String.valueOf(timestamp_end));
database.tripInsertionOnDetect(TRIP_START_ID, start_trip_location.getLatitude(), start_trip_location.getLongitude(), timestamp_start, timestamp_end, "pending status");
Log.d("TRIP STARTRED", contentValues.toString());
final int trip_counts = database.getRowCountForTripStarted();
final int back_counts = database.getRowCountForBackground();
Log.e("TRip Database Rows Size", "" + trip_counts + "\t \tBackGroundTable Rows : " + back_counts + "\tGPS>>>: " + Boolean.toString(isGPSOn));
activity.stopService(new Intent(activity, BackgroundLocationService.class));
} catch (Exception e) {
e.printStackTrace();
}
}
If your gps is not enable then you can use cell tower location. it's not accurate. you can get near by location.
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
You should add a broadcast receiver to detect if the gps is enabled or disable :
private BroadcastReceiver gpsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
if (isGpsEnabled) {
//Here code when gps is enabled
} else {
//Here code when gps is disabled
}
}
}
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerReceiver(gpsReceiver, new IntentFilter("android.location.PROVIDERS_CHANGED"));
//here other code ...
return super.onStartCommand(intent, flags, startId);
}

setMockMode doesn't work - FusedLocationApi

I am setting mock location (using FusedLocationApi) for testing my application based on Maps but it doesn't seem to work.
LocationServices.FusedLocationApi.setMockMode(mGoogleApiClient, true);
Location location = new Location("fused");
// Time is needed to create a valid Location
long currentTime = System.currentTimeMillis();
long elapsedTimeNanos = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
elapsedTimeNanos = SystemClock.elapsedRealtimeNanos();
location.setElapsedRealtimeNanos(elapsedTimeNanos);
}
location.setTime(currentTime);
// new york 40.7128° N, 74.0059° W
location.setLatitude(40.7128);
location.setLongitude(74.0059);
PendingResult<Status> s = LocationServices.FusedLocationApi.setMockLocation(mGoogleApiClient, location);
s.setResultCallback(new ResolvingResultCallbacks<Status>(MainActivity.this, 100) {
#Override
public void onSuccess(#NonNull Status status) {
if(status.isSuccess()){
log("mock success");
if (mIsFromContinuousUpdates) {
startContinuousUpdates();
return;
}
getLastKnowLocation();
}
}
#Override
public void onUnresolvableFailure(#NonNull Status status) {
}
});
PendingResult returns success but when I call getLastKnownLocation it returns null and onLocationChanged is not triggered when I request continuous updates.
Am I missing anything here?
when starting location updates, it should receive an pendingIntent that implemnts OnHandleIntent, which extracts the location from the Intent parameter
public class LocationUpdateActivity extends IntentService implements LocationListener {
private static final String TAG = LocationUpdateActivity .class.getSimpleName();
private Location mCurrentLocation;
public LocationUpdateActivity(String name) {
super(name);
}
public LocationUpdateActivity() {
super("LocationUpdateActivity");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Log.i(TAG, "onHandleIntent");
if (LocationResult.hasResult(intent)) {
LocationResult locationResult = LocationResult.extractResult(intent);
mCurrentLocation = locationResult.getLastLocation();
if (mCurrentLocation != null) {
Log.d(TAG, "accuracy: " + mCurrentLocation.getAccuracy() + " lat: " + mCurrentLocation.getLatitude() + " lon: " + mCurrentLocation.getLongitude());
}
}
}
And setting the updates:
Intent locationIntent = new Intent(mContext, LocationUpdateActivity.class);
PendingIntent locationPendingIntent = PendingIntent.getService(
mContext,
0,
locationIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, locationPendingIntent);

Why FusedLocationApi (onLocationChanged) is not called in API > 23?

I have a service that get locations ,this service good work on API < 23 but on API > 23 don't get any location with Network .It just get me location with gps .
public class TrackLocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final long SYNCHRONIZATION_INTERVAL = 60 * 60 * 1000;
private static boolean isServiceRunning;
private static final String TAG = "SADASDQWREQWRwerwer";
private int notificationId = 9999;
private GoogleApiClient googleApiClient;
private TrackLocationApplication app;
private DataHelper dataHelper;
public static boolean isServiceRunning() {
return isServiceRunning;
}
private static void setIsServiceRunning(boolean isServiceRunning) {
TrackLocationService.isServiceRunning = isServiceRunning;
EventBus.getDefault().post(AppEvent.SERVICE_STATE_CHANGED);
}
public TrackLocationService() {
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
app = (TrackLocationApplication) getApplication();
dataHelper = DataHelper.getInstance(getApplicationContext());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
createGoogleApiClient();
connectGoogleApiClient();
TrackLocationService.setIsServiceRunning(true);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
stopLocationUpdates();
cancelNotification();
app.setStartLocation(null);
TrackLocationService.setIsServiceRunning(false);
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged");
if (app.getStartLocation() == null) {
app.setStartLocation(location);
}
Log.i("ASDASDASDASDA", location.getLatitude() + "" + location.getLongitude());
updateLocationData(location);
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected");
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "onConnectionFailed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.d(TAG, "onTaskRemoved");
}
private void createGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private void connectGoogleApiClient() {
if (googleApiClient != null) {
if (!(googleApiClient.isConnected() || googleApiClient.isConnecting())) {
googleApiClient.connect();
} else {
Log.d(TAG, "Client is connected");
startLocationUpdates();
}
} else {
Log.d(TAG, "Client is null");
}
}
private void startLocationUpdates() {
Log.i("ASDASDASDASDA", "1");
LocationRequest locationRequest = app.createLocationRequest();
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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
scheduleDataSynchronization();
}
private void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
googleApiClient, this);
stopDataSynchronization();
}
private void scheduleDataSynchronization() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, TrackLocationSyncReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
SYNCHRONIZATION_INTERVAL, alarmIntent);
}
private void stopDataSynchronization() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, TrackLocationSyncReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.cancel(alarmIntent);
}
private void updateLocationData(Location location) {
Location startLocation = app.getStartLocation();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
float distance = Utils.distFromCoordinates((float) startLocation.getLatitude(),
(float) startLocation.getLongitude(),
(float) latitude,
(float) longitude);
String timeText = Utils.formatTime(System.currentTimeMillis());
long date = System.currentTimeMillis();
dataHelper.saveLocation(LocationData.getInstance(latitude, longitude, "2"));
updateNotification(timeText);
}
private void updateNotification(String text) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.qomGardy))
.setContentText(text);
Intent resultIntent = new Intent(this, GetNumberActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(GetNumberActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = mBuilder.build();
mNotificationManager.notify(notificationId, notification);
}
private void cancelNotification() {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(notificationId);
}
private void synchronizeData() {
new AsyncTask<Void, Void, TrackLocationResponse>() {
private List<LocationData> locations;
#Override
protected TrackLocationResponse doInBackground(Void[] params) {
TrackLocationResponse response = null;
//locations = dataHelper.getLocationsToSync();
if (locations != null && locations.size() > 0) {
String deviceId = TrackLocationPreferencesManager.getDeviceId(getApplicationContext());
String userName = TrackLocationPreferencesManager.getUserName(getApplicationContext());
TrackLocationRequest request = TrackLocationRequest.getInstance(locations, deviceId, userName);
ITrackLocationClient client = new TrackLocationClient();
response = client.addTrack(request);
if (response != null && response.getStatus() == TrackLocationResponse.RESPONSE_CODE_OK) {
Log.d("TrackLocationSync", "Synced " + locations.size() + " items");
//dataHelper.markLocationsSynced(locations);
}
} else {
Log.d("TrackLocationSync", "No data to be synced");
}
return response;
}
#Override
protected void onPostExecute(TrackLocationResponse response) {
super.onPostExecute(response);
if (response != null && response.getStatus() == TrackLocationResponse.RESPONSE_CODE_OK) {
String message = null;
List<FriendResult> results = response.getResult();
if (results != null && results.size() > 0) {
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("Hi from ");
for (FriendResult r : results) {
messageBuilder.append(" ");
messageBuilder.append(r.getTitle());
messageBuilder.append(",");
}
messageBuilder.deleteCharAt(messageBuilder.length() - 1);
message = messageBuilder.toString();
} else {
message = "Sync " + locations.size() + " items at " + Utils.formatTime(System.currentTimeMillis());
}
updateNotification(message);
}
}
}.execute();
}
}
I added these permission in my manifest for API > 23 :
<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION" />
don't called onLocationChanged() !
In my activity I get all of permissions.
On API 23+ you need to request permissions in runtime, not in the manifest:
Requesting Permissions at Run Time
Edit: In the code you posted you do not do ActivityCompat.requestPermissions only check for permissions, and as I said in 23+ you have to request the permissions at runtime, if you do it somewhere else, please add the code as well.
PS: you just need to implement the TODO: you have
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;}

FusedLocaionAPI Searching GPS signal stops

I have a service that when it creates and starts, initiates prerequisites of using FusedLocationAPI . buildGoogleApiClient() and createLocationRequest() with parameters that initiated by my getConfig() method from database.
This solution works great and accurate with parameters like:
UPDATE_INTERVAL= 10000 (10 sec) , FASTEST_INTERVAL= 5000 (5 sec) , DISPLACEMENT= 10 ( m )
But I need to set interval up to 5 minutes. So when i set prameters like :
UPDATE_INTERVAL= 300000 (5 min) , FASTEST_INTERVAL= 180000 (3 min) , DISPLACEMENT= 10 ( m )
GPS behaves differently and after 30 seconds stops searching GPS and location notification that blinks, disappears.
And starts searching again after device locked and unlocked or this Service stops and starts again.
Here is my service. Please tell me why searching GPS stops right after 30 seconds.
Thanks in advanece.
public class MainService extends Service implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener {
private final static String TAG = MainActivity.class.getSimpleName();
private static int UPDATE_INTERVAL;
private static int FASTEST_INTERVAL;
private static int DISPLACEMENT;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mLastLocation;
public String deviceIMEI;
public boolean isGpsEnabled = false;
DatabaseHelper mDBHelper;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
getDeviceIMEI();
getConfig();
startForeGroundService();
if (checkPlayServices() && checkLocationServices()) {
buildGoogleApiClient();
createLocationRequest();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
else {
stopForeground(true);
stopSelf();
}
return (START_NOT_STICKY);
}
#Override
public void onDestroy() {
stopForeground(true);
if (mGoogleApiClient != null)
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
#SuppressWarnings("deprecation")
public void startForeGroundService() {
Notification note = new Notification(
R.drawable.track_notification_alert,
"GPS tracking started ...", System.currentTimeMillis());
Intent i = new Intent();
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
note.setLatestEventInfo(this, "GPS is active.",
"Now this tablet is under tracking. ", pi);
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground(1337, note);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private boolean checkLocationServices() {
LocationManager lm = (LocationManager) getApplicationContext()
.getSystemService(LOCATION_SERVICE);
isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
return isGpsEnabled;
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
return false;
}
return true;
}
#Override
public void onConnected(Bundle arg0) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
if (Globals.isSatelliteFix && Globals.isGPSEnable)
setPoint();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (Globals.isSatelliteFix && Globals.isGPSEnable)
setPoint();
}
private void setPoint() {
mDBHelper = new DatabaseHelper(getApplicationContext());
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
try {
Point p = new Point();
p.setId(UUID.randomUUID().toString());
p.setIMEI(deviceIMEI);
p.setLatitude(String.valueOf(latitude));
p.setLongitude(String.valueOf(longitude));
p.setTimeStamp(createTimeStamp());
long result = mDBHelper.addPoint(p);
if (result != -1) {
Log.i(TAG, "Insertion Successfull With RowId: " + result);
} else
Log.e(TAG, "Insertion Error");
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Insertion Error: " + e.getMessage());
}
}
}
public String createTimeStamp() {
String strTimeStamp = new SimpleDateFormat("yyyy-MM-dd_kk:mm:ss")
.format(new Date());
return strTimeStamp;
}
public void getDeviceIMEI() {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
deviceIMEI = telephonyManager.getDeviceId();
}
public long getTimeInMiliSeconds() {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
return date.getTime();
}
public void getConfig() {
Config config = new Config();
mDBHelper = new DatabaseHelper(getApplicationContext());
config = mDBHelper.getConfig();
UPDATE_INTERVAL = config.getUpdateInterval();
FASTEST_INTERVAL = config.getFastestInterval();
DISPLACEMENT = config.getSmallestDisplacement();
}
}

Categories

Resources