请求接口Api-Version的心得

参考方向
需求:
后端服务在提供api接口时,随着业务的变化,原有的接口很有可能不能满足现有的需求。在无法修改原有接口的情况下,只能提供一个新版本的接口来开放新的业务能力。
区分不同版本的api接口的方式有多种,其中一种简单通用的方式是在uri中添加版本的标识,例如/api/v1/user,api/v3/user。通过v+版本号来指定不同版本的api接口。在后端服务的代码中,可以将版本号直接写入代码中,例如,user接口提供两个入口方法,url mapping分别指定为/api/v1/user和/api/v2/user。

一、通过URI来获取版本号,进行拦截
1.创建注解@ApiVersion,代码如下

package tbcloud.admin.until;

import org.springframework.stereotype.Component;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author: Dmm
 * @date: 2019/4/11 19:45
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface ApiVersion {

    // 定义接口的版本号
    int value() default 1;
}

2.创建条件处理类ApiVersionRequestCondition,代码如下

package tbcloud.admin.until;

import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: Dmm
 * @date: 2019/4/11 19:51
 */
public class ApiVersionRequestCondition implements RequestCondition<ApiVersionRequestCondition> {

    // 用于匹配request中的版本号  v1 v2
    private static final Pattern VERSION_PATTERN = Pattern.compile("/v(\\d+).*");
    // 保存当前的版本号
    private int version;
    // 保存所有接口的最大版本号
    private static int maxVersion = 1;

    public ApiVersionRequestCondition(int version) {
        this.version = version;
    }

    @Override
    public ApiVersionRequestCondition combine(ApiVersionRequestCondition other) {
        // 上文的getMappingForMethod方法中是使用 类的Condition.combine(方法的condition)的结果
        // 确定一个方法的condition,所以偷懒的写法,直接返回参数的版本,可以保证方法优先,可以优化
        // 在condition中增加一个来源于类或者方法的标识,以此判断,优先整合方法的condition
        return new ApiVersionRequestCondition(other.version);
    }

    @Override
    public ApiVersionRequestCondition getMatchingCondition(HttpServletRequest request) {
        // 正则匹配请求的uri,看是否有版本号 v1
//        Matcher matcher = VERSION_PATTERN.matcher(request.getRequestURI());
//
//        System.out.println(request.getRequestURI()+"请求接口111111");
//
//        if (matcher.find()) {
//            String versionNo = matcher.group(1);
//            int version = Integer.valueOf(versionNo);
//            // 超过当前最大版本号或者低于最低的版本号均返回不匹配
//            if (version <= maxVersion && version >= this.version) {
//                return this;
//            }
//        }
//        return null;
    }

    @Override
    public int compareTo(ApiVersionRequestCondition other, HttpServletRequest request) {
        // 以版本号大小判定优先级,越高越优先
        return other.version - this.version;
    }

    public int getVersion() {
        return version;
    }

    public static void setMaxVersion(int maxVersion) {
        ApiVersionRequestCondition.maxVersion = maxVersion;
    }
}

3.处理器ApiHandlerMapping

package tbcloud.admin.until;


import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * @author: Dmm
 * @date: 2019/4/11 19:55
 */
public class ApiHandlerMapping extends RequestMappingHandlerMapping {


    private int latestVersion = 1;

    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {

        // 判断是否有@ApiVersion注解,构建基于@ApiVersion的RequestCondition
        ApiVersionRequestCondition condition = buildFrom(AnnotationUtils.findAnnotation(handlerType, ApiVersion.class));
        // 保存最大版本号
        if (condition != null && condition.getVersion() > latestVersion) {
            ApiVersionRequestCondition.setMaxVersion(condition.getVersion());
        }
        return condition;
    }

    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        // 判断是否有@ApiVersion注解,构建基于@ApiVersion的RequestCondition
        ApiVersionRequestCondition condition =  buildFrom(AnnotationUtils.findAnnotation(method, ApiVersion.class));
        // 保存最大版本号
        if (condition != null && condition.getVersion() > latestVersion) {
            ApiVersionRequestCondition.setMaxVersion(condition.getVersion());
        }
        return condition;
    }


    private ApiVersionRequestCondition buildFrom(ApiVersion apiVersion) {
        return apiVersion == null ? null : new ApiVersionRequestCondition(apiVersion.value());
    }
}

4.配置拦截器WebConfig

package tbcloud.admin.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import tbcloud.admin.until.ApiHandlerMapping;

/**
 * @author: Dmm
 * @date: 2019/4/12 10:06
 */
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = new ApiHandlerMapping();

        handlerMapping.setOrder(0);
        handlerMapping.setInterceptors(getInterceptors());
        return handlerMapping;
    }
}

5.注意:需要把标签

<!--<mvc:annotation-driven/>-->

干掉。使用@Configuration,@Bean注册bean。
6.演示(controller层)

package tbcloud.admin.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tbcloud.admin.until.ApiVersion;
import tbcloud.admin.until.User;

/**
 * @author: Dmm
 * @date: 2019/4/11 19:44
 */
@Controller
@RequestMapping("/api/test")
public class ApiVersionTest {


//    @RequestMapping("/{version}/test/1")
//    @ApiVersion
//    @ResponseBody
//    public String indexTo(){
//
//        System.out.println("rfghnj");
//
//        return "1";
//    }
//
//    @RequestMapping("/{version}/test/1")
//    @ApiVersion(2)
//    @ResponseBody
//    public String indexTo2(){
//
//        System.out.println("rfghnj--------------------");
//
//        return "2";
//    }
//
//    @RequestMapping("/{version}/test/1")
//    @ApiVersion(3)
//    @ResponseBody
//    public User indexTo3(){
//
//
//        User user=new User();
//        user.setUserName("2222");
//
//        return user;
//    }
//
//    @RequestMapping("/{version}/test/1")
//    @ApiVersion(4)
//    @ResponseBody
//    public User indexTo4(@RequestBody User user){
//        return user;
//    }

}

请求接口/v1
2.
/v2
3.
/v3
4.
/v4

<think>好的,我现在需要总结如何在Android中实现通知权限请求、进度条通知和添加通知点击行为。首先,关于通知权限,记得Android 13(API 33)之后,应用需要动态请求通知权限,而不仅仅是声明在清单文件中。用户必须授予权限才能发送通知。然后,进度条通知,这可能涉及到使用setProgress(max, progress, indeterminate)方法,不确定模式下显示无限进度条,确定模式显示具体进度。最后,点击行为需要通过PendingIntent关联到Intent,这样用户点击通知时可以跳转到指定Activity或执行操作。 需要确认不同Android版本的差异,比如通知渠道在Android 8.0引入,所以创建渠道是必须的。另外,进度条通知可能需要使用NotificationCompat.Builder来保持兼容性。PendingIntent的获取方式,比如使用getActivity、getBroadcast或getService,取决于需要启动的组件。还要注意设置自动取消通知,可能用setAutoCancel(true)或者在Intent中添加FLAG_ACTIVITY_CLEAR_TOP等标志。 可能遇到的问题:权限请求的处理,比如在onRequestPermissionsResult中检查是否授予权限,并做出相应处理。进度更新的时候需要不断更新通知,可能需要使用NotificationManagerCompat.notify()并传入相同的ID。点击行为中PendingIntent的请求码和标志位是否正确,避免冲突。此外,高版本Android中可能需要处理前台服务权限,尤其是长时间显示进度条的情况。 需要查阅相关文档,确认最新的API使用方法,比如NotificationManager和NotificationChannel的创建步骤。还要注意样式兼容,比如使用MessagingStyle或InboxStyle来丰富通知内容。最后,测试不同场景下的通知显示和用户交互,确保功能正常。</think>### Android通知功能实现总结 #### 一、请求通知权限(Android 13+) 1. **清单文件声明** 在`AndroidManifest.xml`中添加权限: ```xml <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> ``` 2. **动态请求权限** ```java if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_CODE); } } ``` #### 二、创建进度条通知 1. **初始化通知渠道(Android 8.0+)** ```java NotificationChannel channel = new NotificationChannel("progress_channel", "下载", IMPORTANCE_LOW); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); ``` 2. **构建进度通知** ```java NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "progress_channel") .setSmallIcon(R.drawable.ic_download) .setContentTitle("文件下载") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setProgress(100, 0, false); // 最大值,当前进度,是否不确定模式 // 更新进度 builder.setProgress(100, currentProgress, false); NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, builder.build()); // 完成后更新为完成状态 builder.setContentText("下载完成").setProgress(0, 0, false); ``` #### 三、添加通知点击行为 1. **创建Intent** ```java Intent intent = new Intent(this, DetailActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); ``` 2. **绑定PendingIntent** ```java PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE ); NotificationCompat.Builder builder = new NotificationCompat.Builder(...) .setContentIntent(pendingIntent) .setAutoCancel(true); // 点击后自动清除通知 ``` #### 四、关键注意点 1. **版本兼容** - Android 8.0+必须使用通知渠道[^1] - Android 13+需动态请求通知权限 2. **进度更新** 通过`NotificationManager.notify()`使用相同ID更新通知,避免创建重复通知。 3. **点击行为扩展** 可使用`addAction()`添加多个按钮,每个按钮绑定不同的`PendingIntent`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值