GoogleApiClient is not working in marshmallow and above devices? - android

Am using googleapi client for getting user location it is working fine below marshmallow devices but on marshmallow devices application getting crashed don't know the reason can someone help me out let me post my code this is the activity am trying to get location:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.gcm.GcmNetworkManager;
import com.google.android.gms.gcm.PeriodicTask;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import java.text.DateFormat;
import java.util.Date;
import static precisioninfomatics.backgroundgps.MyLocationService.TASK_GET_LOCATION_PERIODIC;
public class GPS extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, GetMethod {
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
Button btnFusedLocation;
TextView tvLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
private AsyncTaskGet asyncTaskGet;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate ...............................");
if (!checkPlayServices()) {
finish();
}
createLocationRequest();
startService(new Intent(this, GPSService.class));
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_gps);
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
btnFusedLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (mCurrentLocation != null) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
String userID = "1";
String time = String.valueOf(System.currentTimeMillis());
String url = "http://172.16.6.106:8080/gpstracker/api/coordinates/" + lat + "/" + lng + "/" + userID + "/" + time;
Log.d("url", url);
GetNoteList(getApplicationContext());
asyncTaskGet.execute(url);
}
}
});
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(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
startLocationUpdates();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
GPS.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
startPeriodicLocationTask();
}
public void startPeriodicLocationTask() {
Log.d("periodictask", "startPeriodicLocationTask");
GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(this);
PeriodicTask taskBuilder = new PeriodicTask.Builder()
.setService(MyLocationService.class)
.setTag(TASK_GET_LOCATION_PERIODIC)
.setPeriod(30).setFlex(20)
.setPersisted(true).build();
mGcmNetworkManager.schedule(taskBuilder);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean checkPlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
}
return false;
}
return true;
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
} else {
Log.d(TAG, "location is null ...............");
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
public void GetNoteList(Context context) {
asyncTaskGet = new AsyncTaskGet(context);
asyncTaskGet.getMethod = this;
}
#Override
public Void getDataFromServer(String objects) {
Log.d("response", objects);
return null;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
Log.d("nogps", "nogps");
break;
}
break;
}
}
}
My gradle:
dependencies {
compile 'com.google.android.gms:play-services:9.8.0'
testCompile 'junit:junit:4.12'
}
I think am making mistake in googleplay service am using late googleplay service version can somebody help me to solve this issue!!

Runtime permissions are your issue, in Android M and above google added the need to request for permissions when they are needed (like in iOS).
See this link: https://developer.android.com/training/permissions/requesting.html
There are many wrappers around to make adding permissions easier on sites like https://android-arsenal.com/tag/235?category=1
Here is some code, taken from android developers site to help you along:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}

Related

Why my location data create a unique ID fields each time the location updates were stored in Firebase

I had create a Location Listener by FusedLocation. Each time when my logged auth user start to track their location, the location were write under the currentuser user-id but it keep added a different unique ID for each location that were written in the database. I need that 'location' in the same tree with my current login user description ('name' & 'type') and each time my current user have a location changed data, it will overwrite the data in the 'latitude' and 'longitude'. How I can reconstruct my code?
Here my screenshot of my database
my firebase database
Here my location.class
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Created by AKMAL NIZAR ROSLE on 12/6/2017.
*/
public class DriverActivity extends AppCompatActivity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "DriverActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
private FirebaseAuth auth;
private DatabaseReference databaseReference;
Button btnFusedLocation;
TextView tvLocation, textViewUser;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
//get current user
if (auth.getCurrentUser() == null) {
startActivity(new Intent(DriverActivity.this, LoginActivity.class));
finish();
}
databaseReference = FirebaseDatabase.getInstance().getReference();
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_driver);
FirebaseUser user = auth.getCurrentUser();
textViewUser = (TextView) findViewById(R.id.textViewUser);
textViewUser.setText("Welcome"+" "+user.getEmail());
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
btnFusedLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
updateUI();
}
});
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.d(TAG, "This device is not supported.");
}
return false;
}
return true;
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
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) {
// 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(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
saveToFirebase();
updateUI();
}
private void saveToFirebase() {
FirebaseUser user = auth.getCurrentUser();
Map mLocations = new HashMap();
Map mCoordinate = new HashMap();
mCoordinate.put("latitude", mCurrentLocation.getLatitude());
mCoordinate.put("longitude", mCurrentLocation.getLongitude());
mLocations.put("location", mCoordinate);
databaseReference.child(user.getUid()).push().setValue(mLocations);
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
} else {
Log.d(TAG, "location is null ...............");
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
}
private void saveToFirebase() {
FirebaseUser user = auth.getCurrentUser();
Map mLocations = new HashMap();
Map mCoordinate = new HashMap();
mCoordinate.put("latitude", mCurrentLocation.getLatitude());
mCoordinate.put("longitude", mCurrentLocation.getLongitude());
mLocations.put("location", mCoordinate);
databaseReference.child(user.getUid()).push().setValue(mLocations);
}
Just remove the push() method in your setValue database operation:
private void saveToFirebase() {
FirebaseUser user = auth.getCurrentUser();
Map mCoordinate = new HashMap();
mCoordinate.put("latitude", mCurrentLocation.getLatitude());
mCoordinate.put("longitude", mCurrentLocation.getLongitude());
databaseReference.child(user.getUid() + "/location").setValue(mCoordinate);
}
The push() method generates a new node with an unique key to your database reference.

unable to get current location using FusedLocationApi without Gps

I am trying to get users current location using FusedLocationApi using the following code. I am following the guide provided here: https://developer.android.com/training/location/retrieve-current.html
I have tried this so far:
package com.abhishek.locationawareapp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
protected void createLocationRequest(){
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Main Activity: ","onCreate");
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();//.addApi(LocationServices.class)
}
//For Location Request
/*LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);*/
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
Log.d("Main Activity: ","onStart");
super.onStart();
}
#Override
protected void onStop() {
Log.d("Main Activity: ","onStop");
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d("Main Activity: ","onConnected");
if(Build.VERSION.SDK_INT >=23){
checkLocationPermission();
}else{
locationPermission = true;
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation !=null){
String mLatitudeText = String.valueOf(mLastLocation.getLatitude());
String mLongitudeText = String.valueOf(mLastLocation.getLongitude());
Log.d("Location: ","mLatitudeText: "+ mLatitudeText +" mLongitudeText: "+ mLongitudeText);
}
}
}
boolean locationPermission = false;
final static int LOC_REQ_CODE = 100;
private void checkLocationPermission(){
int locationPermissionCheck = ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION);
if(locationPermissionCheck == PackageManager.PERMISSION_GRANTED){
locationPermission = true;
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation !=null){
String mLatitudeText = String.valueOf(mLastLocation.getLatitude());
String mLongitudeText = String.valueOf(mLastLocation.getLongitude());
Log.d("Location: ","mLatitudeText: "+ mLatitudeText +" mLongitudeText: "+ mLongitudeText);
}
}else{
locationPermission = false;
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOC_REQ_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case LOC_REQ_CODE:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
locationPermission = true;
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation !=null){
String mLatitudeText = String.valueOf(mLastLocation.getLatitude());
String mLongitudeText = String.valueOf(mLastLocation.getLongitude());
Log.d("Location: ","mLatitudeText: "+ mLatitudeText +" mLongitudeText: "+ mLongitudeText);
}
}else{
final Snackbar snackBar = Snackbar.make(findViewById(R.id.rl_layout), "Location access is required to get last location.",
Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Dismiss", new View.OnClickListener() {
#Override
public void onClick(View v) {
checkLocationPermission();
snackBar.dismiss();
}
});
snackBar.show();
}
break;
}
}
#Override
public void onConnectionSuspended(int i) {
Log.d("Main Activity: ","onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d("Main Activity: ","onConnectionFailed");
}
}
I got the location with gps enabled but once i disable gps, mLastLocation
always returns null. Isn't it possible to get location from FusedLocationApi without using Gps? Please help!!

Unable to retrieve location Android Marshmallow

I'm having hard times trying to retrieve location with my app. Apparently I'm stuck while trying to fill the location object.
import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.whattaspot.R;
import com.whattaspot.parameters.ParameterConst;
import com.whattaspot.utils.ConnectionDetector;
import com.whattaspot.utils.LocationProvider;
public class NewsfeedActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{
public static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 0x3;
private final int PERMISSION_REQUEST_LOCATION = 0;
private final String TAG = NewsfeedActivity.class.getSimpleName();
private double currentLatitude, currentLongitude;
private String mLastToken;
private LocationProvider mLocationProvider;
private GoogleApiClient mGoogleApiClient;
// views
private View rootView;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
private LocationRequest mLocationRequest = new LocationRequest();
private Location mLastlocation;
#SuppressWarnings("ConstantConditions")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newsfeed);
// Toolbar inizialization
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getString(R.string.title_newsfeed).toUpperCase());
// Restore preferences
SharedPreferences settings = getSharedPreferences(
ParameterConst.WHATTASPOT_TOKEN_TYPE, Activity.MODE_APPEND);
mLastToken = settings.getString(ParameterConst.PARAM_TOKEN_NAME, null);
// Inizializzo il Location provider
//mLocationProvider = new LocationProvider(this, this);
// Initialize views
rootView = findViewById(R.id.container);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.newsfeed_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
/* overridePendingTransition(0, 0); */
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mLocationRequest = LocationRequest.create()
.setInterval(10000)
.setFastestInterval(100)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
#Override
public void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
Log.d(TAG, "GoogleApiClient disconnect");
// Disconnect the GoogleApiClient
//mLocationProvider.disconnect();
}
#Override
public void onStart(){
mGoogleApiClient.connect();
super.onStart();
Log.d(TAG, "GoogleApiClient connect");
}
#Override
public void onResume() {
super.onResume();
// Check the internet connection
if (!ConnectionDetector.isNetworkAvailable(this)) {
Log.d(TAG, "No Internet connection.");
Snackbar.make(rootView, "No Internet connection.", Snackbar.LENGTH_LONG).show();
}
mGoogleApiClient.connect();
Log.d(TAG, "GoogleApiClient connect AGAIN");
}
#Override
public void onConnected(Bundle bundle) {
// Check permission for Android M
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Checkpoint 1");
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
Log.d(TAG, "Checkpoint 2");
String permit = String.valueOf(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION));
Log.d(TAG, permit);
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_LOCATION);
String granted = String.valueOf(PackageManager.PERMISSION_GRANTED);
Log.d(TAG, permit);
Log.d(TAG, granted);
}
}
Log.d(TAG, "Checkpoint 3");
}
#Override
public void onLocationChanged(Location location) {
mLastlocation = location;
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "GoogleApiClient connection has been suspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "GoogleApiClient connection failed");
/*
* 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()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.d(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
Log.d(TAG, "In ORPR.");
switch (requestCode) {
case PERMISSION_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Checkpoint ORPR, Yes.");
if (mLastlocation == null) {
try {
if(mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastlocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.d(TAG, "Location retrieved.");
}
} catch (SecurityException ex){
Log.d(TAG, "Location not retrieved.");
}
} else {
Log.d(TAG, "Location not retrieved");
}
Log.d(TAG, "Location changed. New location: " + String.valueOf(mLastlocation.getLatitude()));
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
Log.d(TAG, "Checkpoint ORPR, No.");
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
When trying to call that
Log.d(TAG, "Location changed. New location: " + String.valueOf(mLastlocation.getLatitude()));
I get this error: java.lang.RuntimeException: Failure delivering result ResultInfo{who=#android:requestPermissions:, request=0, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.myapp/com.myapp.activities.NewsfeedActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
Do you have any idea why I'm not able to retrieve my location?
Thanks in advance!
Try this function for example:
LocationManager locationManager;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
// Log.d("last known location, provider: %s, location: %s", provider, l);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
// Log.d("found best last known location: %s", l);
bestLocation = l;
}
}
lastKnownLocation = bestLocation;
}
please refer these link and add permissions on runtime.
https://blog.xamarin.com/requesting-runtime-permissions-in-android-marshmallow/
Or try these
Create the verifyStoragePermissions()method and called in onCreateView() of Activity
// Declare String array in activity
private static String[] PERMISSIONS_STORAGE = {
Manifest.Permission.AccessCoarseLocation,
Manifest.Permission.AccessFineLocation};
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(activity,
Manifest.permission.AccessCoarseLocation);
if (permission != PackageManager.PERMISSION_GRANTED)
{
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
1001 // pass any request code
);
}

onLactionChanged never called (fusedLocationApi)

I have location tracker app and there is a class, handling the location changing. On 4.2.2 device is works normally - onLocationChanged() callback react. But on other device - lollypop - same code never calls onLocationChanged(). 've tried with GPS enabled/disabled and internet enabled/disabled in all combination. Turning on/off GPS module during app runtime change nothing. I have no clue, where can i find a solution to this problem. Help please.
package kgk.tracker;
import android.content.Context;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import de.greenrobot.event.EventBus;
import kgk.tracker.messages.GPS;
public class LocationProvider implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
GpsStatus.Listener {
public static final String TAG = LocationProvider.class.getSimpleName();
public final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private static LocationProvider locationProvider;
// Объект - клиент сервиса Google Play
private GoogleApiClient googleApiClient;
// Параметры запроса на предоставление координат для Google Play
private LocationRequest locationRequest;
// Объект LocationManager для определения количества используемых спутников
private LocationManager locationManager;
private static int satellitesCount = 0;
// Конструкторы
private LocationProvider() {
locationManager = (LocationManager) KGKTracker.getAppContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.addGpsStatusListener(this);
createLocationRequest();
buildGoogleApiClient();
EventBus.getDefault().register(this);
android.location.LocationListener locationListener = new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Используется другая реалзиация данного метода в библиотеке FusedLocationApi
}
#Override
public void onProviderDisabled(String arg0) {
Log.d("GPS", "Provider disabled");
kgk.tracker.LocationProvider.setSatellitesCount(0);
CommunicationService.setGps_enabled(false);
CommunicationService.getCommunicationService().generateEmptyPacket();
CommunicationService.getCommunicationService().gpsLost();
}
#Override
public void onProviderEnabled(String arg0) {
Log.d("GPS", "Provider enabled");
CommunicationService.setGps_enabled(true);
CommunicationService.getCommunicationService().generateEmptyPacket();
}
#Override
public void onStatusChanged(String provider, int status, Bundle arg2) {
Log.d("GPS STATUS", "STATUS CHANGED");
switch (status) {
case android.location.LocationProvider.AVAILABLE:
Log.d("GPS STATUS", "AVAILABLE");
//gpsFound();
break;
default:
Log.d("GPS STATUS", "LOST");
//gpsLost();
break;
}
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
}
public static LocationProvider getInstance() {
if (locationProvider == null) {
return new LocationProvider();
} else {
return locationProvider;
}
}
// Аксессоры
public static int getSatellitesCount() {
return satellitesCount;
}
public static void setSatellitesCount(int satellitesCount) {
LocationProvider.satellitesCount = satellitesCount;
}
public GoogleApiClient getGoogleApiClient() {
return googleApiClient;
}
// Открытые методы
/**
* Обработка ивента с помощью библиотеки EventBus
*/
public void onEvent(LocationEvent locationEvent) {
if (locationEvent.getDoConnect()) {
if (!googleApiClient.isConnected()) {
googleApiClient.connect();
}
} else {
googleApiClient.disconnect();
}
}
// Внутренние методы
/**
* Создание объекта GoogleApiClient
*/
private synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(KGKTracker.getAppContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Создание LocationRequest
*/
private void createLocationRequest() {
locationRequest = LocationRequest.create()
.setInterval(5000)
.setFastestInterval(5000)
.setSmallestDisplacement(0.0f)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
/**
* Возвращает количество используемых спутников
*/
private int checkSatellitesCount() {
int satellitesInUse = 0;
for (GpsSatellite satellite : locationManager.getGpsStatus(null).getSatellites()) {
if (satellite.usedInFix()) {
satellitesInUse++;
}
}
return satellitesInUse;
}
// Реализация интерфейсов
#Override
public void onConnected(Bundle bundle) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
switch (i) {
case CAUSE_SERVICE_DISCONNECTED:
Log.d(TAG, "CAUSE_SERVICE_DISCONNECTED");
break;
case CAUSE_NETWORK_LOST:
Log.d(TAG, "CAUSE_SERVICE_DISCONNECTED");
break;
default:
Log.d(TAG, "Unknown reason");
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed " + connectionResult);
if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.getMainActivity());
GooglePlayServicesUtil.getErrorDialog(resultCode, MainActivity.getMainActivity(), PLAY_SERVICES_RESOLUTION_REQUEST).show();
}
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Current location at: " + location.getLatitude() + " " + location.getLongitude() + " " + satellitesCount);
CommunicationService service = CommunicationService.getCommunicationService();
if (service != null) {
service.setLastPacket(new Packet(location));
long last_packet_id = DB.getInstance(KGKTracker.getAppContext()).write_packet(service.getLastPacket());
service.getLastPacket().setId(last_packet_id);
service.gpsFound();
try {
service.getMessageQueue().put(new GPS(service.getLastPacket()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
satellitesCount = checkSatellitesCount();
break;
default:
Log.d(TAG, "Unexpected behavior in onGpsStatusChanged callback");
break;
}
}
}

Waking Device When Destination Reached

The program below is used for vibrating the phone when some destination is reached.This works perfectly when the screen is on but doesnt when the device is idle(SCREEN OFF) any suggestion so that it works while screen is off is very much appreciated.I am a novice in Android Development sorry if the question is stupid.`
package com.sset.jibin.wakemethere;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.text.DateFormat;
import java.util.Date;
public class LocationActivity extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
Button btnFusedLocation;
TextView tvLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_location);
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
btnFusedLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
updateUI();
}
});
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
double l = mCurrentLocation.getLatitude();
double le = mCurrentLocation.getLongitude();
String lat = String.valueOf(l);
String lng = String.valueOf(le);
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
MapsActivity MA = new MapsActivity();
Location loc1 = new Location("");
loc1.setLatitude(l);
loc1.setLongitude(le);
Log.d("=====>", "t5");
SharedPreferences preff = getSharedPreferences("ll", 0);
String lal = preff.getString("la", null);
String lnl = preff.getString("ln", null);
Log.d("=====>", "t5.1");
Log.d("=====>", lal);
Log.d("=====>", lnl);
double la = Double.parseDouble(lal);
double ln = Double.parseDouble(lnl);
Location loc2 = new Location("");
loc2.setLatitude(la);
loc2.setLongitude(ln);
Log.d("=====>", "t6");
float distanceInMeters = loc1.distanceTo(loc2);
Log.d("=====>", "t7");
if (distanceInMeters < 20) {
Log.d("=====>", "FOUND");
Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
}
} else {
Log.d(TAG, "location is null ...............");
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
}
`
You have to move your location logic to a service. so it will run even if the application is leave by the user or screen is off.

Categories

Resources