从API请求数据时以编程方式获得数据访问速度
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从API请求数据时以编程方式获得数据访问速度相关的知识,希望对你有一定的参考价值。
我构建了一个简单的android应用程序,使用Retrofit显示来自TMDb API的数据,但是如何在从服务器请求数据并在Android studio Logcat上显示时以编程方式获取数据访问速度?
class MainActivity : AppCompatActivity() {
lateinit var apiKey : String
var movies : MutableList<Movie> = mutableListOf()
var adapter = MovieAdapter(movies)
val movieService : MovieService = ApiClient.getClient()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
rvMovie.layoutManager = LinearLayoutManager(applicationContext)
rvMovie.adapter = adapter
apiKey = getString(R.string.api_key)
getPopularMovies(apiKey)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.action_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return super.onOptionsItemSelected(item)
}
fun getPopularMovies(apiKey: String) {
val call : Call<MovieResult> = movieService.getPopularMovies(apiKey)
getMovieData(call)
}
fun getMovieData(call : Call<MovieResult>) {
call.enqueue(object : Callback<MovieResult> {
override fun onFailure(call: Call<MovieResult>?, t: Throwable?) {
Toast.makeText(applicationContext, "${t.toString()}", Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<MovieResult>?, response: Response<MovieResult>?) {
if (response?.body() != null) {
movies = response.body()!!.movies.toMutableList()
adapter = MovieAdapter(movies)
rvMovie.adapter = adapter
// HOW DO I MEASURE THE DATA SPEED TRANSFER
Log.i("speedtest", "Data transfer speed is = 99Kb/s");
}
}
})
}
答案
试试这个
@Streaming // make you add this, since you are downloading movie
@Get("bla/bla/bla") // any Http method you are using
fun getPopularMovies(apiKey : Int)
...
// where you consume the apiservice
val call : Call<MovieResult> = movieService.getPopularMovies(apiKey)
getMovieData(call)
fun getMovieData(call : Call<MovieResult>){
call.enqueue(object : Callback<MovieResult> {
override fun onFailure(call: Call<MovieResult>?, t: Throwable?) {
Toast.makeText(applicationContext, "${t.toString()}", Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<MovieResult>?, response: Response<MovieResult>?) {
if (response?.body() != null) {
val moviebytes = ByteArray(1024 * 1024 * 1024) // also try this val bytes = byteArrayOf() if does not work
val inputStream = body.byteStream();
val numberOfbytes = inputStream.read(moviebytes)
log(Log.i("speedtest", "Data transfer speed is = ${numberOfbytes}bytes/s");
}
}
})
}
以上是关于从API请求数据时以编程方式获得数据访问速度的主要内容,如果未能解决你的问题,请参考以下文章
以编程方式访问 Graphite 数据的最佳方式是啥? [关闭]