桌面小部件
技术概述
用来自定义安卓的桌面小部件,实现桌面组件的定制化,也方便用户快速获取信息。难点在于组件的绘制过程不能进行耗时操作,以及周期性的更新问题。
技术详述
动态获取权限
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//是否获取到权限
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
GlobalScope.launch {
initData()
withContext(Dispatchers.Main){
btn_quit.visibility = View.VISIBLE
}
}
}
}
获取数据信息,并进行筛选
for (t in TimeLineApi.getTimeLine().result){
max = if(max > t.seasons.size)max else t.seasons.size
}
for (i in 0 until (7*max)){
animeList.add(Season(i,"","","","",""))
}
var num = 0
for (t in TimeLineApi.getTimeLine().result){
if(t.day_of_week == 1)
flag = true
///...
if(num == 7)
break
}
在service层,进行桌面组件itemd绘制
override fun getViewAt(position: Int): RemoteViews? {
val views =
RemoteViews(mContext.packageName, R.layout.item_grid_layout)
if (position < 7){
views.setTextViewText(R.id.tv_title, weekday[position])
views.setViewVisibility(R.id.iv_pic,View.GONE)
views.setViewVisibility(R.id.tv_time,View.GONE)
}else {
if (animeList[position-7].title.isNullOrEmpty() || animeList[position-7].square_cover.isNullOrEmpty()){
views.setViewVisibility(R.id.ll_item,View.GONE)
return views
}
views.setTextViewText(R.id.tv_title, animeList[position-7].title)
views.setTextViewText(R.id.tv_time,animeList[position-7].pub_time)
var dir = if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED)
Environment.getExternalStorageDirectory().absolutePath;
else
Environment.getRootDirectory().absolutePath
var title = rename(animeList[position-7].title!!)
val fs = FileInputStream("$dir/bilibiliWidgt/$title.jpg")
var bitmap = BitmapFactory.decodeStream(fs)
bitmap = Bitmap.createBitmap(bitmap)
views.setImageViewBitmap(R.id.iv_pic,bitmap)
}
return views
}
技术使用中遇到的问题和解决过程。
原来是在service层通过url进行图片的绘制,但是一直为加载中。因为无法在service层进行数据请求获取图片,所以就打算先把图片缓存到本地,再通过本地资源来加载图片得以解决。
参考文献
《Android开发艺术探索》