I am receiving location update through this class everything working fine, except sometimes location callbacks don't stop after calling StopLocationUpdate(). Please help me to rectify the bug. I have checked answers available to stop location updates and i have implemented the same.
FusedLocationProvider Class:
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
class FusedLocationProvider {
/*Fused API Client Objects.*/
private FusedLocationProviderClient mFusedLocationClient;
private LocationCallback mLocationCallback;
private LocationRequest mLocationRequest;
/*Listener Interface.*/
private FusedLocationListener iFusedLocationListener;
/*Source activity.*/
private Context context;
private boolean isRequestingUpdates = false;
FusedLocationProvider(Context context, LocationRequest locationRequest) {
this.context = context;
mLocationRequest = locationRequest;
/*Get FusedLocationProviderClient.*/
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this.context);
/*Start process of building the LocationCallback, LocationRequest.*/
createLocationRequestCallback();
}
void StartLocationUpdate(FusedLocationListener iListener) {
/*Hook the listener for callbacks.*/
iFusedLocationListener = iListener;
/*Check if request already ongoing.*/
if (!isRequestingUpdates) {
initiateLocationUpdate();
}
}
void StopLocationUpdate() {
if (isRequestingUpdates) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
iFusedLocationListener.OnLocationUpdateStopped();
isRequestingUpdates = false;
}
}
private void createLocationRequestCallback() {
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
iFusedLocationListener.OnLocationUpdate(locationResult);
}
};
}
private void initiateLocationUpdate() {
if (ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_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;
}
iFusedLocationListener.OnLocationUpdateStarted();
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null /* Looper */);
isRequestingUpdates = true;
}
}
I had a similar problem. The issue turned out to be that I had multiple instances of the class that held the locationCallback so the instance that was called to stop the location updates was different than the instance that started them.
So for your code, do you maybe have multiple instances of FusedLocationProvider?
Related
I've been struggling to implement a camera function into my app in a way that doesn't generate the below error:
E/ContextImpl: Tried to access visual service WindowManager from a
non-visual Context:com.camtest.App#385f002 Visual services,
such as WindowManager, WallpaperService or LayoutInflater should be
accessed from Activity or other visual Context. Use an Activity or a
Context created with Context#createWindowContext(int, Bundle), which
are adjusted to the configuration and visual bounds of an area on
screen.
java.lang.IllegalAccessException: Tried to access visual service
WindowManager from a non-visual Context:com.camtest.App#385f002
That error is triggered by this line:
final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
I looked at implementing createWindowContext as the error suggests, but some of the target devices are older and not eligible for upgrade to Android 11, thus createWindowContext is not an option.
The first time around, I followed one of the CodeLabs for implementing CameraX. The camera behaved as expected, but triggered the exception. So I found a different example of implementing CameraX, but I get the same IllegalAccessException exception.
Any suggestions?
package com.camtest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.common.util.concurrent.ListenableFuture;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class CamTest extends AppCompatActivity {
private Executor executor = Executors.newSingleThreadExecutor();
private int REQUEST_CODE_PERMISSIONS = 9001;
private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA", "android.permission.WRITE_EXTERNAL_STORAGE"};
PreviewView mPreviewView;
ImageView captureImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_test);
mPreviewView = findViewById(R.id.camera);//was previewView
captureImage = findViewById(R.id.captureImg);
if(allPermissionsGranted()){
startCamera(); //start camera if permission has been granted by user
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
}
private void startCamera() {
final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this); //This line triggers `E/ContextImpl: Tried to access visual service WindowManager from a non-visual Context`
cameraProviderFuture.addListener(new Runnable() {
#Override
public void run() {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
bindPreview(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
// No errors need to be handled for this Future.
// This should never be reached.
}
}
}, ContextCompat.getMainExecutor(this));
}
void bindPreview(#NonNull ProcessCameraProvider cameraProvider) {
Preview preview = new Preview.Builder().build();
ImageCapture imageCapture = new ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.build();
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
Camera camera = cameraProvider.bindToLifecycle(
((LifecycleOwner) this),
cameraSelector,
preview,
imageCapture);
preview.setSurfaceProvider(
mPreviewView.getSurfaceProvider());
captureImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
File file = new File(getBatchDirectoryName(), mDateFormat.format(new Date())+ ".jpg");
ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(file).build();
imageCapture.takePicture(outputFileOptions, executor, new ImageCapture.OnImageSavedCallback () {
#Override
public void onImageSaved(#NonNull ImageCapture.OutputFileResults outputFileResults) {
new Handler().post(new Runnable() {
#Override
public void run() {
Toast.makeText(CamTest.this, "Image Saved successfully", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onError(#NonNull ImageCaptureException error) {
error.printStackTrace();
}
});
}
});
}
public String getBatchDirectoryName() {
String app_folder_path = "";
app_folder_path = Environment.getExternalStorageDirectory().toString() + "/images";
File dir = new File(app_folder_path);
if (!dir.exists() && !dir.mkdirs()) {
}
return app_folder_path;
}
private boolean allPermissionsGranted(){
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
this.finish();
}
}
}
}
And this activity is started by the below code within onCreate of MainActivity:
Button button_test = findViewById(R.id.button_test);
button_test.setOnClickListener(view -> {
Intent intent = new Intent(MainActivity.this, CamTest.class);
startActivityForResult(intent,0);
});
EDIT: full stack trace-
E/ContextImpl: Tried to access visual service WindowManager from a non-visual Context:com.camtest.App#dd90e6b Visual services, such as WindowManager, WallpaperService or LayoutInflater should be accessed from Activity or other visual Context. Use an Activity or a Context created with Context#createWindowContext(int, Bundle), which are adjusted to the configuration and visual bounds of an area on screen.
java.lang.IllegalAccessException: Tried to access visual service WindowManager from a non-visual Context:com.camtest.App#dd90e6b
at android.app.ContextImpl.getSystemService(ContextImpl.java:1914)
at android.content.ContextWrapper.getSystemService(ContextWrapper.java:803)
at androidx.camera.camera2.internal.Camera2UseCaseConfigFactory.<init>(Camera2UseCaseConfigFactory.java:50)
at androidx.camera.camera2.Camera2Config.lambda$defaultConfig$1(Camera2Config.java:60)
at androidx.camera.camera2.-$$Lambda$Camera2Config$g_hY10kZhqC56um0PalOLTzuFlU.newInstance(Unknown Source:0)
at androidx.camera.core.CameraX.lambda$initAndRetryRecursively$9$CameraX(CameraX.java:575)
at androidx.camera.core.-$$Lambda$CameraX$u-Xx2b6YXY5GXNXRh-mDiDnHdpQ.run(Unknown Source:10)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
EDIT #2: In order to reproduce this error, the StrictMode for VmPolicy must be enabled. The below code is added to MainActivity.onCreate:
if( BuildConfig.BUILD_TYPE.contentEquals( "debug" ) ){
/*StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build());*/
StrictMode.setVmPolicy( new StrictMode.VmPolicy.Builder()
.detectAll()//.detectNonSdkApiUsage()
.penaltyLog()
.build());
}
EDIT #3:
Updating from CameraX version 1.0.0-beta12 to 1.0.0-rc1 (current version as of today) had no effect
Pass the Context from the Activity rather than the Application.
The stack trace indicates you're passing an instance of com.camtest.App. Since you're just passing it from your Activity.this, I imagine the library you're using is calling Context.getApplicationContext() incorrectly. You'll need to chase this up with the library maintainers.
I develop a simple app that shows me the imei of the device and the lat and long after pressing a button. Now, i want to save this data (lat, long, imei) in firestore, and i have some understanding problem where and what should i do to save this data into firestore.
I can't provide background with what i've done because i have understanding problem with what i should code.
package com.example.locatieimei;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient client;
private TextView imei;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imei = findViewById(R.id.imei);
loadIMEI();
client = LocationServices.getFusedLocationProviderClient(this);
Button button = findViewById(R.id.Chk);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(MainActivity.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;
}
client.getLastLocation().addOnSuccessListener(new
OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location!=null){
TextView textView = findViewById(R.id.textView);
Double longitude = location.getLongitude();
Double latitude = location.getLatitude();
textView.setText(String.valueOf("latitudine"+longitude+
"\n"+"longitutine"+latitude));
}
}
});
}
});
}
public void loadIMEI() {
// Check if the READ_PHONE_STATE permission is already available.
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
// get_imei_data();
} else {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
} else {
TelephonyManager mngr =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
IMEI = mngr.getDeviceId();
imei.setText(mngr.getDeviceId());
// READ_PHONE_STATE permission is already been granted.
}
}
private String device_unique_id;
private static String IMEI;
private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
}
i have some error when i try to add real time database from android
ERROR: Manifest merger failed : Attribute application#appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:10:5-24:19 to override.
I had the same problem, you need to migrate your project to androidx, check out this reference, He will guide how to do this. https://developer.android.com/jetpack/androidx/migrate
click Refactor > Migrate to AndroidX in the menu.
My issue: I am attempting to create an app that can be used university wide. It requires constant access to location. I followed a tutorial online and completed the code underneath. This code works perfectly for my android emulator, but does not work on my device. I get the permission request on my device, but nothing gets updated. Now, the strange thing is, if I use a mock location app on my device, this app DOES work. But only with the mock location app.
Does anyone have any suggestions on how to fix this?
(The xml file is just a single textview. Like i said, I was just testing this first)
package com.example.dylan.locationexample;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private LocationManager locationManager;
private LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("Location: ", location.toString());
TextView tv = findViewById(R.id.textView);
tv.setText(tv.getText() + Double.toString(location.getLatitude()) + "\t" + Double.toString(location.getLongitude()) + "\n");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_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.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}else{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
Please ensure you have the following in the manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
And enable gps on your physical device.
If you still face the problem, check the permission settings on your mobile phone for the app. You may have denied permission to access location.
Here is my code am using:
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
com.google.android.gms.location.LocationListener mLocationListener = new com.google.android.gms.location.LocationListener() {
#Override
public void onLocationChanged(final Location location) {
listener.onLocation(location);
}
};
if(location != null) {
listener.onLocation(location);
}else{
locationListener = new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
listener.onLocation(location);
locationManager.removeUpdates(locationListener);
Log.d(TAG,"Location: " + String.valueOf(location.getLongitude()));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
I'm actually experiencing the same thing and I found a solution to make it work on the physical device. Disable the WI-FI connection and it works. Idk how or why it works though. Now I just opened back the WI-Fi connection and it's working again. If the Wi-fi thing doesn't work for you try restarting the device.
You might also need to wait for a bit before it starts getting the location while moving around the house so it constantly changes.
In a section of an application I'm building, there's an embedded zxing qr scanner, and I'm using it inside a fragment.
If the app has not granted Manifest.permission.CAMERA permission yet, it asks for the permission and then continue with enabling the scanner.
The problem is, I call barcodeView.resume() inside onResume() and I ask for the permission in onStart(). So it should ask for the permission first and after that call barcodeView.resume() inside the onResume(). But apparently the opposite happens, if the app is not granted the permission yet, it throws this exception
java.lang.NullPointerException: Attempt to invoke virtual method 'void
com.journeyapps.barcodescanner.DecoratedBarcodeView.resume()' on a
null object reference
How come is that happening ? Isn't onResume() called after onStart() not before?
Here's my fragment code:
package com.lab.rafael.smartattendance;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.zxing.ResultPoint;
import com.google.zxing.client.android.BeepManager;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import java.util.List;
public class TakeAttendanceFragment extends Fragment {
private final int CAMERA_PERM_REQUEST = 0;
private static final String TAG = TakeAttendanceFragment.class.getSimpleName();
DecoratedBarcodeView barcodeView = null;
BeepManager beepManager = null;
String lastText;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_take_attendance, container, false);
}
#Override
public void onStart() {
super.onStart();
if(getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(getActivity(), new String[] {Manifest.permission.CAMERA}, CAMERA_PERM_REQUEST);
} else {
startCamera();
}
}
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == CAMERA_PERM_REQUEST) {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startCamera();
}
}
}
private void startCamera() {
try {
if(getView() != null) {
barcodeView = (DecoratedBarcodeView) getView().findViewById(R.id.barcode_scanner);
barcodeView.decodeContinuous(barcodeCallback);
beepManager = new BeepManager(getActivity());
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
private BarcodeCallback barcodeCallback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if(result.getText() == null || result.getText().equals(lastText)) return;
lastText = result.getText();
barcodeView.setStatusText(lastText);
beepManager.playBeepSoundAndVibrate();
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
public void onResume()
{
super.onResume();
barcodeView.resume();
}
public void onPause() {
super.onPause();
barcodeView.pause();
}
}
onStart is called before onResume, yes.
The Permission request dialog is not blocking, so the fragments lifecycles will continue when you ask for permissions.
So it'll go like this:
- onStart
- Request permission
- onResume (at this point the user hasn't granted permission yet).
You'll need to have a check in onResume to see if the barcodeView is not null and permission have been granted.
If the permission is granted, the onRequestPermissionsResult will be called immediately after onStart, as it's not async if the permission is granted, then this code would work fine.
This question is directly related to the same prevailing stackoverflow question at "Android: get current location of user without using gps or internet" where the accepted answer is actually not answering the question.
I should be able to get the current location name (eg:city name, village name) of the device via network provider not with GPS or internet.
Following is the accepted answer in that question. (The following code parts should be included in the onCreate() method)
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
I changed the above code given in the linked answer as following but no success.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView txtView = (TextView) findViewById(R.id.tv1);
txtView.setText("ayyo samitha");
////
// Acquire a reference to the system Location Manager
LocationManager locationManager;
locationManager= (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
private void makeUseOfNewLocation(Location location) {
txtView.setText("sam came in");
txtView.append(location.toString());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {
// makeUseOfNewLocation(location);
}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
How to accomplish what I want by correcting above code or any other method? Note that I want to get the location name, but not the longitudes and latitudes. Can somebody please help me.
What you are referring to here (showing location name on older phones) is done using "Cell Broadcast" (or "CB"). This has absolutely nothing to do with the Location API or any variations on that.
Cell towers can send out broadcast information that can be received by devices (something like "one to many SMS"). Some operators have used Cell Broadcast to broadcast the name of the location where the cell tower is. Some operators have used Cell Broadcast to broadcast the location (lat/long) of the cell tower. Some operators have used Cell Broadcast to send advertising tickers. There are no standards for the information contained in a CB broadcast message and each mobile operator can choose to use this or not.
Since most operators do not send these messages, it probably doesn't make sense to invest any time in trying to receive and decode them. But if you want to try, you can register a BroadcastReceiver listening for this Intent action: android.provider.Telephony.SMS_CB_RECEIVED. See the documentation for more details about what data is contained in the Intent.
The problem is that the code you tried does work, probably just not as well as you wished. For example, the accuracy such a method provides on Samsung Galaxy S3 is 2000m, meaning the actual position is anywhere within a circle of 2 kilometers radius. Additional it would probably take quite a large change in location before your app would be informed of a location change since the margin of error is so big.
A GPS or LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY (if Google Play Services is used) is required to get a reasonably good location. This does require android.permission.ACCESS_FINE_LOCATION, however unless you only require km level accuracy, otherwise this permission is a must.
Finally note that using Google Play Services with LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY I can get location data as accurate as 10m without turning on GPS, so this should still satisfy your requirement.
Below is a complete example:
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
MainActivity.java
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends Activity implements
com.google.android.gms.location.LocationListener, ConnectionCallbacks,
OnConnectionFailedListener {
private final FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
private GoogleApiClient mGoogleAPIClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleAPIClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
#Override
protected void onResume() {
super.onResume();
mGoogleAPIClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleAPIClient != null) {
mGoogleAPIClient.disconnect();
}
}
#Override
public void onConnected(Bundle arg0) {
final LocationRequest locationRequest = LocationRequest.create();
locationRequest
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
fusedLocationProviderApi.requestLocationUpdates(mGoogleAPIClient,
locationRequest, this);
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// the location is no more than 10 min old, and with reasonable
// accurarcy (50m), done
if (System.currentTimeMillis() < location.getTime() + 10 * 60 * 1000
&& location.getAccuracy() < 50) {
mGoogleAPIClient.disconnect();
mGoogleAPIClient = null;
((TextView) findViewById(R.id.test)).setText(location.toString());
}
}
}
According to android docs using LocationManager is not the current recomended API (see reference):
The Google Play services location APIs are preferred over the
Android framework location APIs (android.location) as a way of
adding location awareness to your app.
To learn how to set up the Google Services client library, see Setup in the Google Play services guide.
Once you have linked Google Services client library to your app you can achieve user location using FusedLocationProviderApi:
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
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.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends ActionBarActivity
implements ConnectionCallbacks, OnConnectionFailedListener {
// ..
private GoogleApiClient mGoogleAPIClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create google api client object
mGoogleAPIClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleAPIClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleAPIClient.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,
"Could not connect to Google Play Services",
Toast.LENGTH_SHORT).show();
finish();
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG,
"Successfuly connect to Google Play Services");
// retrieve last location once connected
Location lastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleAPIClient);
if (lastLocation == null) {
// should request new one
// location should be enabled
Log.i(TAG,
"No location data previously acquired.. should request!");
Toast.makeText(this,
"Requesting location data ..",
Toast.LENGTH_SHORT).show();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
PendingResult<Status> result = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleAPIClient,
locationRequest,
new LocationListener() {
#Override
public void onLocationChanged(Location location) {
makeUseOfNewLocation(location);
}
});
// TODO: use result to retrieve more info
} else {
makeUseOfNewLocation(lastLocation);
}
}
#Override
public void onConnectionSuspended(int i) {
}
private void makeUseOfNewLocation(Location location) {
// do your stuff here
}
I have tested the code above and it works without internet connection but it requires that user enable location feature on device. Also it requires that the user have already enabled Location History feature into location feature.
Hope that this helps you.
You can try getting a country level accuracy using the Locale object or using the Telephony service. No internet or GPS required.
Getting country code from Locale:
String locale = context.getResources().getConfiguration().locale.getCountry();
Getting country code from Android's Telephony service:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
// Will work on all networks. Only provide the SIM card's country
String countryCode = tm.getSimCountryIso();
// Might not work well on CDMA networks. Will provide the country code
// for the country the device is currently in.
String currentCountryCode = tm.getNetworkCountryIso();
Better code samples and discussion here.
Good luck with this. It's called geocoder. Or more specifically reverse geocoding to turn coordinates into a human readable output. I'm fairly sure the one google provides is a pay service but you get a bunch free. So plan on caching the results and using your cached results when ever possible.
List<Address> list = geoCoder.getFromLocation(location
.getLatitude(), location.getLongitude(), 1);
if (list != null & list.size() > 0) {
Address address = list.get(0);
result = address.getLocality();
return result;
https://developer.android.com/training/location/display-address.html
How to get city name from latitude and longitude coordinates in Google Maps?
try this code..
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
and next class is
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidLocationActivity extends Activity {
Button btnGPSShowLocation;
Button btnNWShowLocation;
AppLocationService appLocationService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appLocationService = new AppLocationService(
AndroidLocationActivity.this);
btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (GPS): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("GPS");
}
}
});
btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("NETWORK");
}
}
});
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
AndroidLocationActivity.this);
alertDialog.setTitle(provider + " SETTINGS");
alertDialog
.setMessage(provider + " is not enabled! Want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
AndroidLocationActivity.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and this user permission given At Manifest File
<!-- to get location using GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- to get location using NetworkProvider -->
<uses-permission android:name="android.permission.INTERNET" />