赞
踩
最新版本的Android Studio 添加了Gemini,Gemini 是 Android 开发方面的AI编码助手。他可以帮助我们生成代码、学习最佳实践、查阅资料帮助你解决问题等等,Gemini 提供的问答可能是不准确的,需要开发者甄别使用。
在Android Studio工具栏依次点击 View > Tool Windows > Gemini,然后点击右侧的Gemini角标,这样就能看到Gemini的功能框啦。
打开的时候会遇到 Gemini it’s not available in my country这个问题。在设置里面设置下代理就好了。
初始化Gemini的时候可以设置是否开启代码补全,后面也可以在设置中开关。
如果是公司项目,会涉及到隐私问题,比如说一些关键的秘钥,不想让ai扫描到,可以通过设置.aiexclude文件的方式排除掉那些文件。格式的话跟.gitignore类似。
在控制台中右键错误,选择explain this crash,Gemini会帮助你分析错误原因。
Gemini 的回答因问题而异,向Gemini提问时尽量简明扼要,这里让Gemini提供了Android使用Okhttp下载文件的最佳实践,以下是Gemin生成的代码。注释、以及接口设计的很详细。如果不满意你可以通过连续对话的方式让Gemini优化他的代码。
object OkHttpUtil { // 下载文件 fun downloadFile(url: String, file: File, progressListener: ((Long, Long) -> Unit)? = null): Call { val request = Request.Builder() .url(url) .build() val client = OkHttpClient.Builder() .addNetworkInterceptor { chain -> val originalResponse = chain.proceed(chain.request())originalResponse.newBuilder() .body(ProgressResponseBody(originalResponse.body!!, progressListener)) .build() } .build() val call = client.newCall(request) call.enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { // 处理下载失败 } override fun onResponse(call: Call, response: Response) { // 处理下载成功 val inputStream = response.body!!.byteStream() val outputStream = FileOutputStream(file) outputStream.use { output -> inputStream.copyTo(output) } } }) return call } } // 下载状态枚举类 enum class DownloadStatus { Success(val file: File), Error(val error: Throwable) } // 进度回调接口 typealias ProgressListener = (bytesDownloaded: Long, totalBytes: Long) -> Unit // 进度响应体 class ProgressResponseBody( private val responseBody: ResponseBody, private val progressListener: ProgressListener? ) : ResponseBody() { private var bufferedSource: BufferedSource? = null override fun contentType(): MediaType? { return responseBody.contentType() } override fun contentLength(): Long { return responseBody.contentLength() } override fun source(): BufferedSource { if (bufferedSource == null) { bufferedSource = source(responseBody.source()).buffer() } return bufferedSource!! } private fun source(source: Source): Source { return object : ForwardingSource(source) { var totalBytesRead = 0L override fun read(sink: Buffer, byteCount: Long): Long { val bytesRead = super.read(sink, byteCount) totalBytesRead += if (bytesRead != -1L) bytesRead else 0 progressListener?.invoke(totalBytesRead, responseBody.contentLength()) return bytesRead } } } }
选择代码块,选择Suggest Improvements,Gemini能够给出相应的优化建议,相当于让AI帮你code review了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。