RequiresApi vs TargetApi android annotations

前端 未结 5 1430
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 09:48

Whats the difference between RequiresApi and TargetApi?

Sample in kotlin:

@RequiresApi(api = Build.VERSION_CODES.M)
@Target         


        
5条回答
  •  醉话见心
    2020-12-02 10:17

    I'll first assume your min api version is lower than the api you are going to call, because that's where these kind of annotations make any sense

    @RequiresApi(Build.VERSION_CODES.N_MR1)
    public void hello() { // codes that call system apis introduced in android N_MR1}
    

    When a method is annotated with this, anytime you call that method, your receive a nice red warning that this call requires api version that is higher than your min api version, but it doesn't stop you from compiling and building your apk, it will just crash on lower versions of android as I tested it.

    @TargetApi
    

    This doesn't help at all, it suppress warnings of calling new apis in your method, but when you call this method from somewhere else, there is no lint warning at all, and you can still build and install your apk only to meet a crash when that method is called.

提交回复
热议问题