我正在尝试做一些应该很容易的事情,但这让我发疯。我正在尝试在按下主屏幕小部件时启动活动,例如小部件的配置活动。我想我已经逐字阅读了 Android 开发者网站上的教程,甚至还有一些非官方的教程,但我一定错过了一些重要的东西,因为它不起作用。
这是代码:
public class VolumeChangerWidget extends AppWidgetProvider {
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
final int N = appWidgetIds.length;
for (int i=0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Log.d("Steve", "Running for appWidgetId " + appWidgetId);
Toast.makeText(context, "Hello from onUpdate", Toast.LENGTH_SHORT);
Log.d("Steve", "After the toast line");
Intent intent = new Intent(context, WidgetTest.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
将小部件添加到主屏幕时,Logcat 显示两条调试行,但不显示 Toast。(有什么想法为什么不呢?)然而,更令人烦恼的是,当我点击带有 PendingIntent 关联的按钮时,什么也没有发生。我知道“WidgetTest”活动可以运行,因为如果我从主活动中设置一个 Intent,它可以正常启动。
万一这很重要,这里是 Android Manifest 文件:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.steve"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Volume_Change_Program"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".WidgetTest"
android:label="@string/hello">
<intent_filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent_filter>
</activity>
<receiver android:name=".VolumeChangerWidget" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/volume_changer_info" />
</receiver>
</application>
<uses-sdk android:minSdkVersion="3" />
有没有办法测试故障在哪里?即按钮没有正确链接到PendingIntent,或者PendingIntent 或Intent 没有找到WidgetTest.class 等故障?
非常感谢您的帮助!
史蒂夫