I am trying to make a speedometer using implement LocationListener.
How ever when make a call to onLocationChanged it is saying the reference to onLocationChanged is ambiguous
my codes :
//speedometer and llocation servie
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) {
Toast.makeText(this, "First enable LOCATION ACCESS in settings.", Toast.LENGTH_LONG).show();
return;
}
LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,this);
this.onLocationChanged(null);
After trying for some time I realised it is because this was of doing it is probably deprecated
So I tried tweeking compile sdk from 32 to 29 which seemed to remove that error but added a lot of library related compile errors... somebody please Help !
Thanks in advance
If you have any alternative way of making a speedometer do tell
The error indicates that there are two signatures for that method:
onLocationChanged(List<Location> locations)
onLocationChanged(Location location)
When using null, the compiler cannot determine which one of the two methods you are targeting. You need to cast null either to a Location or a List:
this.onLocationChanged((Location) null);
this.onLocationChanged((List<Location>) null);
Related
I came across the following syntax, which is alien to me. I know String[] is a String array, but what are the curly braces doing
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}
in the following code snippet:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
Calling this Android method displays a dialog box that prompts the app to grant permission and invokes onRequestPermissionsResult when the choice is made. Once this permission has been granted to the system, startAcquisition, stopAcquisition, and acquireGeoPosition are granted access to the location services.
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}
For this syntax it an inline initializing for a list of string.
Hello I am still fairly new to this, so please help me understand why I am having this error. I have tried many solutions, so I'm just going to list everything I've done since I can't seem to understand why this is happening.
I created a project that integrates GoogleMaps at min SDK 21 to target/compile at SDK 28. I did call the permissions needed inside the Manifesto.
I created a file that extends the MapFragment class and everything seems to be working fine. I am able to check and request permission for the user's location (the box does show up), but when I called the onRequestPermissionResult method it is shown differently and gives me an error saying "error: cannot find symbol class NonNull":
#Override
public void onRequestPermissionsResult(int requestCode, #androidx.annotation.NonNull String[] permissions, #androidx.annotation.NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
In my other Fragment (android.support.v4.app) classes the #androidx.annotation.NonNull is #NonNull instead. I first thought maybe I needed to add implementation 'com.android.support:support-annotations:28.0.0' to the build.gradle, but that wasn't the case. I then tried to just replace the #androidx.annotation.NonNull with #NonNull which made the error go away, but whenever I clicked allow or deny it wasn't hitting the onRequestPermissionResult method.
I created a method that checks for a permission, but it won't let me use requestPermission on its own without checking if the build is greater or equal to SDK 23, but my min SDK is 21. So instead I just checked if the build is greater or equal to 21 and used ActivityCompat to get the requestPermission method and it works. It will check and ask for permission, so I'm thinking maybe the onRequestPermissionResult only works in the MainActivity which is what I don't want. I want to be able to call a method after checking if the request was granted inside the MapFragment. Is it because MapFragment isn't supported with android.support.v4.app? It looks like this:
private boolean checkAskPermission(int requestCode, String permissionString){
if(Build.VERSION.SDK_INT >= 21){
int permission = ContextCompat.checkSelfPermission(mContext, permissionString);
if(permission!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(getActivity(), new String[]{permissionString}, requestCode);
return false;
}
}
return true;
}
At this point I don't know what else to try. I thought maybe I wasn't checking the permission correctly inside onRequestPermissionResult when I change #androidx.annotation.NonNull to #NonNull to be able to use it, but the method doesn't hit when I use a break on it.
Please leave detail responses, so I can fully understand my problem. I have been stuck on this for a day.
Edit: Solution
private boolean checkAskPermission(int requestCode, String permissionString){
if(Build.VERSION.SDK_INT >= 23){
int permission = ContextCompat.checkSelfPermission(mContext, permissionString);
if(permission!=PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{permissionString}, requestCode);
return false;
}
}
return true;
}
and just changed the #androidx.annotation.NonNull to #NonNull and now it hits the method.
Thanks to Eugene for clearing up SDK permissions. Only SDK 23 and higher require permission.
import that annotation class:
import androidx.annotation.NonNull;
which is either coming from this dependency:
implementation "androidx.annotation:annotation:1.0.0"
or from this dependency, in case not yet using androidx:
implementation "com.android.support:support-annotations:28.0.0"
then you can use it as usual:
#NonNull
The only work-around that I found useful was to fore-go the react-native run-android command and manually go into the react-native library (for me: ProjectHome/node_modules/ModuleIWantToChange/android/src/main/java/FileToChange.java) that was importing androidx.annotation.NonNull, changing that dependency to android.support.annotation.NonNull and then making sure to compile with the com.android.support:support-annotations under "dependencies" in that node_module's "android/build.gradle" file. In my case, I'm using version "com.android.support:support-annotations:25.3.1". You'll have to make sure that you have the version you call out here. Look at what you have installed with Android Studio under $ANDROID_HOME/extras/android/m2repository/com/android/support/support-annotations.
Then, instead of react-native run-android, I moved to the android directory under the project's home directory and ran sudo ./gradlew --stacktrace installDebug (stacktrace is optional) to build and install the apk on my emulator/device.
This might not work for everyone, but it was a tolerable fix in my case.
[...] but the method doesn't hit when I use a break on it.
[...] used ActivityCompat to get the requestPermission [...]
You're in a fragment. Don't ask the activity for permissions. If you ask the fragment you also get callback in the fragment.
requestPermissions(new String[]{permissionString}, requestCode);
Runtime permissions were introduced in API 23 (that's why the method is only available since API 23). Fix your condition. Before that having the permission declared in manifest is enough.
Off-topic: Platform fragments have been deprecated. Use support fragments instead. Extend SupportMapFragment.
#androidx.annotation.NonNull cannot be found because you don't use AndroidX in your project. You can use whatever other #NonNull annotation is available (either from the SDK or from the support library).
I have written an application for Android that has an issue (crash) when it is launched immediately (with in 5 seconds or so) after the phone is rebooted. Due to one reason or another, the OnCreate method is called for a second time. I thought this may have been the problem, but after researching this, I found out the android system may recall onCreate after start up as it is still starting system services - such as getting the "MCM".
In my application in the MainActivity I have a statically bound fragment that is bound through XML. The fragment has code in it that checks that location permissions were granted:
if (ActivityCompat.checkSelfPermission(this.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
The problem is, this.getContext() returns null! It definitely has something to do with the fact onCreate is being called more than once, because when the phone is not booting and onCreate is only called once the application works perfectly!
Here is the only reference I make to the fragment in my onCreate method in the mainActivity:
android.support.v4.app.Fragment fragMap = getSupportFragmentManager().findFragmentById(R.id.mv_1);
if (fragMap instanceof FragmentMap)
{
theMap = (FragmentMap) fragMap;
}
Here is the fragment bound through XML:
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/mv_1"
android:name="com.sunhillo.personneltrackerv002.FragmentMap"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="64dp"/>
Thank you very much for any help you can provide! I am still new to Android programming, and am attempting to learn the ins and outs!
If your ultimate aim is to access the location permissions, simply add these permissions in manifest file. And if you wish to perform this check via java, don't add this to individual fragments. Add this syntax only to the MainActivity java file that refers to the fragments. I hope this helps. :)
You should use launch mode Single Task or Single top which will avoid calling multiple onCreate and you should use getApplicationContext().
I'm trying to make my app ready for Android 6 and now I'm stuck to the point where you need to request and check permissions.
I tried the following from the docs:
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_CALENDAR);
The problem is that Android Studio says Cannot resolve method 'checkSelfPermission'.
I already included the appcompat and support lib. ContextCompat is known to AS but the method itself isn't known. I don't know what am I doing wrong - in another project I can write this method and it gets recognized.
TargetAPI is 23.
Does anyone know a solution?
Here is how you need to call in various scenarios,
In case of activity:
ContextCompat.checkSelfPermission(MyActivity.this,
Manifest.permission.WRITE_CALENDAR);
In case of fragment:
ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_CALENDAR);
In case of any utility class use context:
ContextCompat.checkSelfPermission(context,
Manifest.permission.WRITE_CALENDAR);
Comment below for further information
Oh my godness - what a stupid mistake.
AS imported the supportlib as a jar and this jar was from like 2014. I just replaced the jarimport with the real dependency and know it is working.
Thanks for your help guys!
For Fragment use getActivity().checkSelfPermission
For Activity use this..checkSelfPermission or simply checkSelfPermission
#SuppressLint("NewApi")
I simply used this on top of my page and it works for me...
As silly as it maybe, it could be in the wrong place. I had the same problem. The bolded part is where I had originally put the code. The italic part is where it should have gone
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("-----------", location.toString());
}
**if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {'some code'}**
}; 'End of LocationListener method
*if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) { 'some code'}*
I had the same problem.
In my case I added a library that was using an old appcompat version, then the compiler could not find the right appcompat.
To fix the problem I added the option {transitive = false} while importing the culprit library, and this fixed the problem.
Now I have:
api ('org.library.using.old.appcompat:1.0.1') {transitive = false}
Trying to use checkSelfPermission() in a Fragment with Kotlin and wondering how to get around Context being null?
Have a look at the sample below, and remember, before the Fragment is attached to the Activity, the Context will be null.
private fun fineLocationPermissionApproved(): Boolean {
val context = context ?: return false
return PackageManager.PERMISSION_GRANTED == checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
)
}
I try to write application, which shows GPS coordinates on button click.
#Override
public void onClick(View arg0) {
EditText editText;
editText = (EditText) findViewById(R.id.editText1);
LocationManager locationManager;
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation("gps");
editText.setText(location.toString());
}
Is problem: while in first time I got coordinates of location with time of GPS reading, second click get the same location. Even when I stop program and run again, it get the same location!
How enforce to refresh reading GPS?
while in first time I got coordinates of location with time of GPS reading, second click get the same location
That is not surprising.
Even when I stop program and run again, it get the same location!
That too is not surprising.
How enforce to refresh reading GPS?
Generally speaking, you don't. There is no requirement that the device has to have a fresh update just because you request the last-known location. It may be physically impossible to provide a new location fix. And, if you are not calling requestLocationUpdates(), it is very possible for getLastKnownLocation() to simply return null.
Your parameters to requestLocationUpdates() may have some impact for how aggressively the device tries to update GPS, versus saving power. However, there are no guarantees.
Try to get best provider that available to fetch the Location data ,
using this code before you get the location
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
and in your getLastKnownLocation pass the best Location Provider to get the location like this
Location location = locationManager.getLastKnownLocation(bestProvider );