我的应用程序用于保存传感器数据并上传到服务器。
首先我有这个数据。
data class SensorRecord (val upDown:String,
val config:Int,
val date: Date,
val ms: Int,
val dur: Int,
public var v:MutableList<SensorValue>
)
data class SensorValue (var accelerometer:Accelerometer? = null,
var gyroscope:Gyroscope? = null,
var gravity:Gravity? = null,
var magnetic:Magnetic? = null,
var linearAcceleration:LinearAcceleration? = null,
var rotationVector:RotationVector? = null,
var gameRotationVector:GameRotationVector? = null,
var pressure:Pressure? = null,
var orientation:Orientation? = null
){
data class Accelerometer(var x:Float,
var y:Float,
var z:Float
)
data class Gyroscope(var x:Float,
var y:Float,
var z:Float
)
data class Gravity(var x:Float,
var y:Float,
var z:Float
)
data class Magnetic(var x:Float,
var y:Float,
var z:Float
)
data class LinearAcceleration(var x:Float,
var y:Float,
var z:Float
)
data class RotationVector(var x:Float,
var y:Float,
var z:Float,
var scalar:Float
)
data class GameRotationVector(var x:Float,
var y:Float,
var z:Float
)
data class Pressure(var hpa:Float)
data class Orientation(var azimuth:Float,
var pitch:Float,
var roll:Float)
}
然后将很多值添加到列表中,因此数据非常大。
var record:SensorRecord? = null
record = SensorRecord(upDown, config, Date(), ms.toInt(), duration.toInt(), arrayListOf<SensorValue>())
record!!.v.add(sensorValue)
record!!.v.add(sensorValue)
record!!.v.add(sensorValue)
record!!.v.add(sensorValue)
.
.
.
.
add many data
最后上传到服务器
fun upload(){
val gson = GsonBuilder()
.setDateFormat("yyyy-MM-dd HH-mm-ss")
.create();
var jsonString = gson.toJson(record)
val requestQueue = Volley.newRequestQueue(applicationContext)
val stringRequest = object : StringRequest(Request.Method.POST, "http://myupload.com",
object : Response.Listener<String> {
override fun onResponse(response: String) {
}
},
object : Response.ErrorListener {
override fun onErrorResponse(error: VolleyError) {
}
})
{
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params["record"] = jsonString
return params
}
}
requestQueue.add(stringRequest)
}
如果数据小,没有问题,但如果数据大,应用程序崩溃。
抛出 OutOfMemoryError“无法分配 150994952 字节分配,25165824 可用字节和 86MB 直到 OOM,最大允许占用空间 135855256,增长限制 201326592”
我找到了一些答案,他们建议使用流媒体
java.lang.OutOfMemoryError:尝试将 Java 对象转换为 Json 字符串时的 Java 堆空间
但我不明白如何使用流媒体上传我的对象