我正在尝试发送更新主屏幕小部件的意图。我无法成功发送意图并得到错误
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.stream.homewidgets/com.stream.homewidgets.Parking}; have you declared this activity in your AndroidManifest.xml?
来自我片段的startActivity(intent)
行。
我看过多个Stack Overflow帖子,如下所示:
这些还不能为我解决问题,我的代码看起来非常相似。
这是我的小部件中的一个片段:
class Parking : 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, currentFloor)
val intent = Intent(context, Parking::class.java)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds)
PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
}
...
}
这是调用片段的摘录:
class HomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
...
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
context?.let {
val componentName = ComponentName(it, Parking::class.java)
val intent = Intent(context, Parking::class.java)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
val ids = AppWidgetManager.getInstance(it).getAppWidgetIds(componentName)
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
startActivity(intent)
}
}
}
return root
}
}
这是我的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.stream.homewidgets">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver android:name=".Parking">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/parking_info" />
</receiver>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
因此,我希望能够发送一个意图来更新我的小部件。我不确定如何解决这个问题。我的“ .Parking”接收器在清单中,尽管它是接收器而不是活动。我不知道是否有更好的方式表达意图。如果您知道将意图发送到小部件的更正确方法,请告诉我。
答案 0 :(得分:3)
从策略上讲,您正在尝试使用广播Intent
来启动活动,但该广播将不起作用。使用sendBroadcast()
,而不是startActivity()
。
但是,使用AppWidgetManager
及其updateAppWidget()
方法之一直接更新应用程序小部件会更快,更高效。您的Parking
类仅是系统请求更新的一种方式。如果您希望推送更新,则可以在不涉及Parking
的情况下进行。将您的应用程序小部件更新代码移到另一个可以在HomeFragment
和Parking
中使用的类中。