Launcher简介
Launcher就是Android系统的桌面,它也是一个app,用于管理其他的app。
注册AndroidManifest
要让app作为Launcher,需要在Manifest中添加两个category:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name=""/>
<category android:name=""/>
<category android:name=""/>
<category android:name=""/>
</intent-filter>
</activity>
此时安装此app之后,点击Home键就会看到以下界面,让你选择使用哪一个桌面应用
使用PackageManager扫描所有app
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
(savedInstanceState)
setContentView(.activity_main)
initView()
}
private fun initView() {
val apps = scanApps()
val adapter = AppAdapter(apps)
= GridLayoutManager(this, 3)
= adapter
}
private fun scanApps():List<ResolveInfo>{
val intent = Intent(Intent.ACTION_MAIN, null).apply {
addCategory(Intent.CATEGORY_LAUNCHER)
}
return (intent, 0)
}
}
我们在MainActivity中使用PackageManager的queryIntentActivities
方法扫描出手机上已安装的所有app信息。
activity_main 布局代码:
<?xml version="1.0" encoding="utf-8"?>
< xmlns:andro
xmlns:tools="/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<
android:
android:layout_width="match_parent"
android:layout_height="match_parent" />
</>
由于布局中使用了 RecyclerView,记得导入 RecyclerView 库:
implementation ':recyclerview:1.1.0'
新建AppAdapter类:
class AppAdapter(private val apps: List<ResolveInfo>) : <>() {
private lateinit var context: Context
class AppHolder(itemView: View) : (itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppHolder {
context =
val view = (context, .item_app, null)
return AppHolder(view)
}
override fun getItemCount(): Int {
return
}
override fun onBindViewHolder(holder: AppHolder, position: Int) {
val resolveInfo = apps[position]
val activityInfo =
(())
= ()
{
val intent = Intent().apply {
component = ComponentName(, )
}
(intent)
}
}
}
在此类中使用方法加载app图标,使用
方法加载app名字,并且添加了点击启动对应app的点击事件。
item_app布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
< xmlns:andro
xmlns:app="/apk/res-auto"
xmlns:tools="/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<ImageView
android:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="36dp"
android:maxHeight="36dp"
app:layout_constraintBottom_toTopOf="@id/tvName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:src="@mipmap/ic_launcher" />
<TextView
android:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:singleLine="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/ivIcon"
tools:text="@string/app_name" />
</>
运行效果这里就不贴了。