小怪兽 - val
type: channel
link: https://blog.zmonster.top/tag/val/
items: OkHttp4 RequestBody().create() 提示过时
items: Android Kotlin 文件读写操作扩展函数，Raw资源读取，Assets资源读取
items: Android Result API详解

OkHttp4 RequestBody().create() 提示过时
type: item
date: 2022-12-04T18:15:29+08:00
description: OkHttp4 写法kotlin版本：import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.RequestBody.Companion.asRequestBody //String转RequestBody String、ByteArray、ByteString都可以用toRequestBody() val stringBody ="body参数".toRequestBody("application/json;charset=utf-8".toMediaType()) val request:Request=Request .Builder() .post(stringBody) .build() //File转RequestBody val file=File("") val fileBody=file.asRequestBody("text/x-markdown; charset=utf-8".toMediaType()) val request = MultipartBody.Builder() .addFormDataPart("file", file.name,fileBody) .build()java版本:import okhttp3.MediaType.Companion.*; import okhttp3.RequestBody.Companion.*; //String转RequestBody String、ByteArray、ByteString都可以用toRequestBody() MediaType mediaType=MediaType.Companion.parse("application/json;charset=utf-8"); RequestBody stringBody=RequestBody.Companion.create("body参数",mediaType); Request request=new Request .Builder() .post(stringBody) .build(); //File转RequestBody MediaType mediaType=MediaType.Companion.parse("text/x-markdown; charset=utf-8"); File file=new File(""); RequestBody fileBody=RequestBody.Companion.create(file,mediaType); Request request=new MultipartBody.Builder() .addFormDataPart("file", file.getName(),fileBody) .build();4.0之前写法:val request:Request=Request .Builder() .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"),"body参数")) .build()编译器提示如下：又是一个小技巧

Android Kotlin 文件读写操作扩展函数，Raw资源读取，Assets资源读取
type: item
date: 2022-11-29T14:40:00+08:00
description: 作者：snow_lyGirl链接：https://blog.csdn.net/qq_31028313/article/details/125299445来源：CSDN小记一下1、保存内容到文件及文件读取/** * 保存信息到File * @param fileName 文件名 * @param content 保存内容 * @param mode 模式 */ fun Context.saveIntoFile( fileName: String, content: String, mode: Int = Context.MODE_PRIVATE ): Boolean { return try { openFileOutput(fileName, mode).use { it.write(content.toByteArray()) true } } catch (e: Exception) { false } } /** * 读取文件 * @param fileName 文件名 */ fun Context.readFromFile(fileName: String): String { val sb = StringBuilder() openFileInput(fileName).use { val temp = ByteArray(1024) var len = 0 while (true) { len = it.read(temp) if (len <= 0) break sb.append(String(temp, 0, len)) } } return sb.toString() }在Activity中使用//保存 saveIntoFile(FILE_NAME, content) //读取 val content = readFromFile(FILE_NAME)2、保存内容到SD卡中的文件及SD卡文件读取/** * 写文件到SD卡 * eg:/storage/emulated/0/Android/data/com.guc.androiddemo/files/Documents/fileName * @param fileName 文件名 * @param content 内容 * @param type 文件类型 * {@link android.os.Environment#DIRECTORY_MUSIC}, * {@link android.os.Environment#DIRECTORY_PODCASTS}, * {@link android.os.Environment#DIRECTORY_RINGTONES}, * {@link android.os.Environment#DIRECTORY_ALARMS}, * {@link android.os.Environment#DIRECTORY_NOTIFICATIONS}, * {@link android.os.Environment#DIRECTORY_PICTURES}, or * {@link android.os.Environment#DIRECTORY_MOVIES}. */ fun Context.saveFileToSD( fileName: String, content: String, type: String = Environment.DIRECTORY_DOCUMENTS ) { if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) { val fn = getExternalFilesDir(type)?.canonicalPath + "/" + fileName FileOutputStream(fn).use { it.write(content.toByteArray()) } } else { throw Exception("没有存储卡") } } /** * 读取SD中文件 * eg:/storage/emulated/0/Android/data/com.guc.androiddemo/files/Documents/fileName * @param fileName 文件名 * @param type 文件类型-Documents */ fun Context.readFromSD( fileName: String, type: String = Environment.DIRECTORY_DOCUMENTS ): String { return if (Environment.getExternalStorag…

Android Result API详解
type: item
date: 2022-11-12T16:34:20+08:00
description: Android Result API详解旧版本startActivityForResult使用方式（传统方式）在两个Activity之间交换数据class FirstActivity : AppCompatActivity() { //传统方式 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val firstButton = findViewById (R.id.button2) firstButton.setOnClickListener { val intent = Intent(this, SecondActivity::class.java) startActivityForResult(intent, 1) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when(resultCode){ 1 -> { if (resultCode == RESULT_OK){ val data = data?.getStringExtra("data") } } } } }调用statActivityForResult()方法去向SecondActivity请求数据，然后在onActivityResult()方法去解析SecondActivity返回的结果。另一个SecondActivityclass SecondActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val secondButton = findViewById (R.id.button2) secondButton.setOnClickListener { val intent = Intent() intent.putExtra("data","data from SecondActivity") setResult(RESULT_OK,intent) finish() } } }使用Activity Result API来实现同样的功能class FirstActivity : AppCompatActivity() { //传统方式 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val firstButton = findViewById (R.id.button2) firstButton.setOnClickListener { //传统方式 val intent = Intent(this, SecondActivity::class.java) requestDataLauncher.launch(intent) } } //使用 Activity Result API来实现同样的功能 private val requestDataLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if(result.resultCode == RESULT_OK){ val data = result.data?.getStringExtra("data") } } }首先移除来对onActivityResult()方法的重写，通过调用registerForActivityResult()方法注册一个对Activity结果的监听。registerForActivityResult()：接收两个参数，第一个参数是一种Contract类型；第二个是一个Lambda表达式，当有结果返回时会回调到这里，然后我们在这里获取并处理数据。registerForActivityResult()方法的返回值是一个ActivityResult…