cimenmus
cimenmus

Reputation: 1506

Is @TargetApi annotation just for one Api level or above?

I am using @TargetApi(23) in my app.

@TargetApi(23)
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        onAttachToContext(context);
    }


    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            onAttachToContext(activity);
        }
    }

    protected void onAttachToContext(Context context) {

    }

But i can not understand something: @TargetApi(23) annotation's mean "just for Api level 23" or "for Api level 23 and above" ? For example if Api level of device 24, is onAttach(Context context) method called?

Upvotes: 34

Views: 25279

Answers (5)

Kelly-Chap-Dev88
Kelly-Chap-Dev88

Reputation: 1

Further to @Fivos answer, adding @RequiresApi also means that there will be a build/compile error showing that you are calling a method/functionality that only exists on a target higher than the minimum target you have specified.

Function using @requiresapi

Compilation error after adding requires

Upvotes: 0

Fivos
Fivos

Reputation: 568

You can also use

@RequiresApi(Build.VERSION_CODES.N)

which denotes that the annotated element should only be called on the given API level or higher.

Upvotes: 0

mazend
mazend

Reputation: 464

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
    //to do something
}else{
    //to do something else
}

I upgraded @Yang's answer.

Upvotes: 0

Mike Yang
Mike Yang

Reputation: 2944

@TargetApi does not prevent any code from running, all it does is to remove lint errors.

You still need to add something along the lines of

if (Build.VERSION.SDK_INT > 7){
    //...
}

Upvotes: 8

GoRoS
GoRoS

Reputation: 5375

TargetApi annotation is just for lint tool purposes and has no outcome in runtime. If you use any API methods just available on 23 within your method and don't declare the TargetApi, you will just get some warnings indicating you're using API's not available in your minimum SDK version. It's your responsibility to call this method with coherence being aware of the API level it will be called from.

Upvotes: 31

Related Questions