I've a problem with checking is device supports Mutli Window Mode. I'm using this function to check it isInMultiWindowMode() but it've added in API 24, and when i'm runs my app on device with lower api version it cause an exception. There is any replacement for this function for lower api versions?
There is any replacement for this function for lower api versions?
Not in the Android SDK. There is no multi-window mode (from the Android SDK's standpoint) prior to API Level 23. And, for whatever reason, Google elected not to add isInMultiWindowMode() to ActivityCompat, perhaps because they cannot support the corresponding event (onMultiWindowModeChanged()).
So, here's a free replacement method:
public static boolean isInMultiWindowMode(Activity a) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
return false;
}
return a.isInMultiWindowMode();
}
Add that to some utility class somewhere and call it as needed.
Also note that isInMultiWindowMode() suffers from a race condition that makes it unreliable, IMHO.
What #CommonsWare explained is true, it is a race condition. Hence, isInMultiWindowMode() will give actual result if you call it from inside post method:
View yourView = findViewById(R.id.yourViewId);
yourView.post(new Runnable() {
#Override
public void run() {
boolean actualResult = isInMultiWindowMode();
}
});
Related
Utilizing onSignalStrengthsChanged, getAllCellInfo(), and related methods, my app monitors cell signal data and displays the results in realtime. My code works very well when targeting API 28 and lower, automatically refreshing the data as it changes. Targeting API 29 results in some Android 10 devices failing to update the data -- but not all.
I discovered TelephonyManager.requestCellInfoUpdate() was added to API 29, which may(?) be needed to resolve this issue. However, I have been unable to find any information about this method beyond the concise definition on the Android Reference. Does this method need to be used to refresh cell info? Are any code samples or further explanations available?
If that method is not relevant, is there another change in API 29 that could cause this behavior? ACCESS_FINE_LOCATION is confirmed to be granted, which appears to be the only other relevant API change.
I have noticed the same behaviour targeting Android 10 (API Level 29). The only workaround I have found is to regularly poll the API and look for changes.
Example code below:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
tm.requestCellInfoUpdate(minThreadExecutor, new TelephonyManager.CellInfoCallback() {
#Override
public void onCellInfo(#NonNull List<CellInfo> list) {
//Extract needed data
}
});
}
}, 1000, 1000 );
Reading the docs there is a mention of this in the getAllCellInfo() documentation.
Apps targeting Android Q or higher will no longer trigger a refresh of the cached CellInfo by invoking this API. Instead, those apps will receive the latest cached results, which may not be current. Apps targeting Android Q or higher that wish to request updated CellInfo should call requestCellInfoUpdate(); however, in all cases, updates will be rate-limited and are not guaranteed. To determine the recency of CellInfo data, callers should check CellInfo#getTimeStamp().
So the preference is if you are targeting Android Q or higher, you should be opting for requestCellInfoUpdate()
// 1. Create a TelephonyManager instance
telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
// 2. Define a CellInfoCallback callback
TelephonyManager.CellInfoCallback cellInfoCallback = new TelephonyManager.CellInfoCallback() {
#Override
public void onCellInfo(List<CellInfo> cellInfo) {
// DO SOMETHING
}
}
// 3. Now you can call the method to DO SOMETHING
telephonyManager.requestCellInfoUpdate(this.getMainExecutor(), cellInfoCallback);
In an Android app, we wish to have an iOS-like horizontal scroll wheel, and we are using HorizontalPicker.
This requires API 17 for calls getTextDirection() and getLayoutDirection().
For getTextDirection, the usage is:
switch (getTextDirection()) {
default:
case TEXT_DIRECTION_FIRST_STRONG:
return (defaultIsRtl ? TextDirectionHeuristicsCompat.FIRSTSTRONG_RTL :
TextDirectionHeuristicsCompat.FIRSTSTRONG_LTR);
case TEXT_DIRECTION_ANY_RTL:
return TextDirectionHeuristicsCompat.ANYRTL_LTR;
case TEXT_DIRECTION_LTR:
return TextDirectionHeuristicsCompat.LTR;
case TEXT_DIRECTION_RTL:
return TextDirectionHeuristicsCompat.RTL;
case TEXT_DIRECTION_LOCALE:
return TextDirectionHeuristicsCompat.LOCALE;
}
Looking at dashboard, I see ~20% of devices using APIs 15 or 16, so I'm thinking we should target API 15 rather than 17.
How should I change this code?
Is there a way to only run this code if the device is new enough? If so, what should the function return for an older device?
Is there an alternative mechanism I should rewrite this method to use?
Never mind. Leaving this question here in case it is useful to others, to know how to work around APIs missing in a given version.
My real issue was not knowing how to mark the calls so that "lint" would not complain about them.
Here is the complete implementation in HorizontalPicker:
private TextDirectionHeuristicCompat getTextDirectionHeuristic() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return TextDirectionHeuristicsCompat.FIRSTSTRONG_LTR;
} else {
// Always need to resolve layout direction first
final boolean defaultIsRtl = (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
switch (getTextDirection()) {
default:
case TEXT_DIRECTION_FIRST_STRONG:
return (defaultIsRtl ? TextDirectionHeuristicsCompat.FIRSTSTRONG_RTL :
TextDirectionHeuristicsCompat.FIRSTSTRONG_LTR);
case TEXT_DIRECTION_ANY_RTL:
return TextDirectionHeuristicsCompat.ANYRTL_LTR;
case TEXT_DIRECTION_LTR:
return TextDirectionHeuristicsCompat.LTR;
case TEXT_DIRECTION_RTL:
return TextDirectionHeuristicsCompat.RTL;
case TEXT_DIRECTION_LOCALE:
return TextDirectionHeuristicsCompat.LOCALE;
}
}
}
It already has logic to handle older builds!
So all that is needed is to mark the two calls getLayoutDirection() and getTextDirection() so that lint does not complain.
The simplest way to do so, without hiding problems elsewhere, is to mark this method to suppress lint complaints about API versions:
#SuppressLint("NewApi")
private TextDirectionHeuristicCompat getTextDirectionHeuristic() {
...
CAUTION: Only make such a change, after examining the lint complaints and the logic, and your AndroidManifest.xml, to be sure the complaints can be safely ignored.
In my case, manifest has minimum API = 15 and target API = 19, the two complaints were "Call requires API level 17, minimum is 15)", and
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
directs all devices less than 17 to use the one-line implementation, which does not use the API 17 calls. That is, the calls will only be made on devices with API 17 or above.
You can use ViewCompat from android.support.v4 with something like :
if (ViewCompat.getLayoutDirection(mView) == ViewCompat.LAYOUT_DIRECTION_RTL) {
//...
}
This question already has answers here:
Programmatically obtain the Android API level of a device?
(7 answers)
Closed 8 years ago.
I have an application, and it behaves differently when I run it on API 18 or 19. This is not a problem, and I know why does it happen.
However, I want to write one code that will deal with both the versions.
Is there any way to get in runtime which API my application was built with? Specifically, I would like to get 18 or 19 if I build my application with these APIs.
EDIT
It seems to be a duplicate question. I thought that the BUILD_VERSION is something else, because, when I compiled both the versions to API 18 and 19, and print the version, I receive 18. It looks like another problem (although I specified API 19, it is compiled according to 18).
I found that the problem was in the emulator configurations.
I didn't understand your problem completely. But if you want to check which Build Version your app is working on and then act accordingly the you can use the following.
if(Build.VERSION.SDK_INT == 18 ){
// Do some stuff
}
else if (Build.VERSION.SDK_INT == 19) {
// Do some stuff
}
else{
// Do some stuff
}
The Android docs provides some sample code of how to load bitmaps effectively that handles this problem.
The code defines static methods in a class Utils that it references when it needs to know what platform the app is running on. The benefit of doing this is that you can reuse the function calls rather than rewriting long conditional statements over and over. The code looks like this:
public static boolean hasFroyo() {
// Can use static final constants like FROYO, declared in later versions
// of the OS since they are inlined at compile time. This is guaranteed behavior.
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}
public static boolean hasGingerbread() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}
public static boolean hasHoneycomb() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
public static boolean hasHoneycombMR1() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
}
public static boolean hasJellyBean() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
}
public static boolean hasKitKat() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
}
android.os.Build.VERSION.SDK_INT
Check this link out
Build Version Codes
So you can use as follows...
int thisDevicesApi =Build.VERSION.SDK_INT;
if (thisDevicesApi <=Build.VERSION_CODES.GINGERBREAD) {
//for example
//do something
}
For instance, this code:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
myCalendarView.setOnDateChangeListener(
new OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
Toast.makeText
(
getApplicationContext(), ""+dayOfMonth, 0
).show();
}
}
);
}
Gives error:
Description Resource Path Location Type Call requires API level 11
(current min is 8):
android.widget.CalendarView#setOnDateChangeListener example.java /example/src/com/example/example line
20 Android Lint Problem
I understand why I get this error compile-time. But is there any way to mark a source Java class to only be used on certain API level-11? Or surround code blocks with a define/similar so the code is late-bound/jitted only on devices above API level-11? What is the best solution to achieve what I want? (Which is to provide an activity with CalendarView on devices capabile of it.)
I'm not sure if this is going to solve your issue,
but what you are using to check version is not working under API 9
(and you are supporting since API 8).
You should use:
if (Build.VERSION.SDK_INT > 9) {
Or as problematic function is API 11, check for "SDK_INT>10"
Then for lint errors on eclipse, do as people comment, disable lint errors or add the #SuppressLint("NewAPi") or the target to that function to 11.
For anyone stumbling upon this much later, conditionally executing code based on the API version at runtime is currently a valid way of supporting different platform versions.
See: https://developer.android.com/training/basics/supporting-devices/platforms#version-codes
Where it says:
Android provides a unique code for each platform version in the Build
constants class. Use these codes within your app to build conditions
that ensure the code that depends on higher API levels is executed
only when those APIs are available on the system.
And gives examples:-
Java:
private void setUpActionBar() {
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
Kotlin:
private fun setUpActionBar() {
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
actionBar.setDisplayHomeAsUpEnabled(true)
}
}
In one of our methods, we use smoothScrolling in a list view. As this method is not available before API Level 8 (FROYO), we used the TargetApi annotation to prevent the method from being called in previous SDK versions.
As you can see, we do use TargetApi annotation both in class definition and in statements that use the objects of the class. This is more than needed.
Our problem is that the TargetApi annotation is not taken into account and make our emulator crash in version ECLAIR (SDK 7). By tracing, we just realize that the code that should only be executed in versions 8+ is also executed in version 7.
Are we missing something?
This code is in a listener :
#TargetApi(8)
private final class MyOnMenuExpandListener implements OnMenuExpandListener {
#Override
public void onMenuExpanded( int position ) {
doScrollIfNeeded( position );
}
#Override
public void onMenuCollapsed( int position ) {
doScrollIfNeeded( position );
}
protected void doScrollIfNeeded( int position ) {
if ( mListViewDocuments.getLastVisiblePosition() - 2 < position ) {
mListViewDocuments.smoothScrollToPosition( position + 1 );
}
}
}
And the listener is registered this way :
#TargetApi(8)
private void allowSmothScrollIfSupported() {
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO ) {
//This if should not be necessary with annotation but it is not taken into account by emulator
Log.d( LOG_TAG, "Smooth scroll support installed." );
folderContentAdapter.setOnMenuExpandListener( new MyOnMenuExpandListener() );
}
}
BTW, we run the code in debug mode, so the issue is not related to obfuscation removing annotations.
#TargetApi does not prevent any code from being run, it is merely for annotating code and preventing compiler errors for new APIs once you know you are only conditionally calling them.
You still need to add something along the lines of
if (Build.VERSION.SDK_INT > 7){
//...
}
With almost one year of more thinking about this, I would like to add a tiny complement to #Guykun 's answer :
The #TargetApi will be only be used by tools to say developers "Hey, don't use this method below XXX android SDK". Typically lint.
So, if you design a method like :
if (Build.VERSION.SDK_INT > 7){
//...
}
then you should add #TargetApi( 7 ) to your method's signature.
BUT, if you add an else statement, and provide an alternative that makes it work for all versions of Android like :
if (Build.VERSION.SDK_INT > 7){
//...
} else {
//...
}
then you should not add #TargetApi( 7 ) to your method's signature. Otherwise, other developers will think they can't use your method belw api level 7, but indeed, it would work for them as well.
So this annotation has to be used, for static analysis, to indicate the minimum api level supported by the method. As in :
#TargetApi( 7 )
public void foo() {
if (Build.VERSION.SDK_INT > 7){
//...
else if (Build.VERSION.SDK_INT > 10){
//...
}
}
and even better, use constants defined in android.Build.VERSION_CODES.*.
BTW, you would have noticed that this is useless for private methods indeed, except to get a cleaner code and help to promote the method public in the future.
To enforce lint error when using a method targeted towards higher Api Level, you can use RequiresApi instead of TargetApi and whenever you'll try to use the method without checking the version code, you'll get compilation error.
This is what the documentation says about RequiresApi
This is similar in purpose to the older #TargetApi annotation, but
more clearly expresses that this is a requirement on the caller,
rather than being used to "suppress" warnings within the method that
exceed the minSdkVersion.