将Target SDK33的Android WebView应用升级至SDK34/35的方法
旧WebView项目升级至SDK34/35+环境迁移与功能扩展指南
一、解决新版Android Studio无法打开项目的问题
- 自动导入修复:直接用新版AS打开旧项目,AS会弹出「Gradle版本不兼容」提示,点击「Update Gradle and Sync Project」,工具会自动更新Gradle插件和wrapper版本,完成后同步项目即可。
- 手动修复(自动失败时):
- 修改项目根目录
build.gradle中的插件版本(对应新版AS要求,如AS Hedgehog对应8.2.0):dependencies { classpath 'com.android.tools.build:gradle:8.2.0' } - 修改
gradle/wrapper/gradle-wrapper.properties中的Gradle分发地址:distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip - 点击工具栏「Sync Now」,同步期间若旧库版本报错,直接替换为对应AndroidX版本。
- 修改项目根目录
二、SDK34/35代码适配
1. 迁移至AndroidX(必做)
在项目根目录gradle.properties中添加以下配置,AS会自动迁移大部分Support库至AndroidX:
android.useAndroidX=true android.enableJetifier=true
手动修正剩余代码导入路径,例如:
- 将
android.support.v4.widget.SwipeRefreshLayout改为androidx.swiperefreshlayout.widget.SwipeRefreshLayout - 将
android.support.v7.app.AppCompatActivity改为androidx.appcompat.app.AppCompatActivity
2. 升级Target/Compile SDK版本
在app/build.gradle中修改版本配置:
android { compileSdk 35 // 与Target SDK版本保持一致 defaultConfig { targetSdk 35 minSdk 26 // 建议最低支持API26,可按需调整 } }
3. 适配SDK34+关键行为变更
- 通知权限申请:SDK34+需主动申请
POST_NOTIFICATIONS权限,先在AndroidManifest.xml声明:
再在启动页/首页动态申请:<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> { // 处理权限申请结果 }).launch(Manifest.permission.POST_NOTIFICATIONS); } } - 网页上传文件适配:SDK34+用
ActivityResultContracts替代旧文件选择逻辑,在WebChromeClient中实现:@Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { registerForActivityResult(new ActivityResultContracts.OpenMultipleDocuments(), uris -> { filePathCallback.onReceiveValue(uris); }).launch(fileChooserParams.getAcceptTypes()); return true; } - URL跳转浏览器:SDK30+需添加
FLAG_ACTIVITY_NEW_TASK并检查Intent可执行性:Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); }
三、原有功能迁移验证
- 推送通知:若用旧版GCM,直接替换为FCM;自定义推送需创建SDK26+要求的通知渠道:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel("channel_id", "通知渠道", NotificationManager.IMPORTANCE_DEFAULT); getSystemService(NotificationManager.class).createNotificationChannel(channel); } - 下拉刷新:替换为AndroidX的
SwipeRefreshLayout后,原有setOnRefreshListener逻辑无需大幅修改,仅需确保刷新完成后调用setRefreshing(false)。 - 启动页:改用
android:windowBackground设置背景图,减少白屏:<style name="SplashTheme" parent="Theme.MaterialComponents.NoActionBar"> <item name="android:windowBackground">@drawable/splash_bg</item> </style>
四、添加新特性建议
- 深色模式适配:将App主题改为
Theme.MaterialComponents.DayNight.NoActionBar,配置WebView跟随系统:webSettings.setForceDark(WebSettings.FORCE_DARK_AUTO); - 离线缓存:开启WebView缓存功能:
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); webSettings.setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath()); webSettings.setAppCacheEnabled(true); - 自定义错误页:重写
WebViewClient的onReceivedError方法,加载本地错误页面:@Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { view.loadUrl("file:///android_asset/error.html"); } - 手势返回:通过
GestureDetector实现侧滑返回:GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e1.getX() - e2.getX() > 100 && Math.abs(velocityX) > 200) { if (webView.canGoBack()) { webView.goBack(); return true; } } return super.onFling(e1, e2, velocityX, velocityY); } });
内容的提问来源于stack exchange,提问作者user15549225
相关产品推荐
相关产品推荐

