【发布时间】:2021-09-23 20:23:32
【问题描述】:
我无法在 android 11 上启动小部件。
此代码适用于我的 android 9 手机, 但 android 11 Google Pixel 3a 模拟器无法正常工作。 我该怎么做。 好的,所以我想做的是创建一个小部件,当小部件被按下时,它会简单地启动另一个应用程序。
小部件 XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Whatsapp Launch"
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:layout_marginLeft="30dp"
android:text="Spotify Launch"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
小部件类
class SimpleAppWidget : AppWidgetProvider() {
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
// There may be multiple widgets active, so update all of them
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
private fun updateAppWidget(
context: Context, appWidgetManager: AppWidgetManager,
appWidgetId: Int
) {
// Construct the RemoteViews object
val views = RemoteViews(context.packageName, R.layout.simple_app_widget)
// Construct an Intent object includes web adresss.
val launchIntent12 = context!!.packageManager.getLaunchIntentForPackage("com.spotify.music")
val launchIntent122 = context!!.packageManager.getLaunchIntentForPackage("com.whatsapp")
// In widget we are not allowing to use intents as usually. We have to use PendingIntent instead of 'startActivity'
val pendingIntent = PendingIntent.getActivity(context, 0, launchIntent122, 0)
val pendingIntent2 = PendingIntent.getActivity(context, 0, launchIntent12, 0)
// Here the basic operations the remote view can do.
views.setOnClickPendingIntent(R.id.button, pendingIntent)
views.setOnClickPendingIntent(R.id.button2, pendingIntent2)
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views)
}
}
【问题讨论】:
标签: java android android-studio kotlin android-widget