【发布时间】:2010-12-01 21:40:58
【问题描述】:
下面的代码应该描述一个应用程序,一旦单击小部件按钮,它就会发送一个应由 TestReceiver 接收的意图。但是,在运行下面的代码时,从未调用过 TestReceiver 的 onReceive。
谁能告诉我我做错了什么?
小部件代码
public class Widget extends AppWidgetProvider {
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this provider
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch ExampleActivity
//Intent intent = new Intent(context.getApplicationContext(), TestReceiver.class);
Intent intent = new Intent();
intent.setAction(TestReceiver.TEST_INTENT);
intent.setClassName(TestReceiver.class.getPackage().getName(), TestReceiver.class.getName());
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// Get the layout for the App Widget and attach an on-click listener to the button
RemoteViews views;
views = new RemoteViews(context.getPackageName(), R.layout.main);
views.setOnClickPendingIntent(R.id.btnTest, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current App Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
接收者代码:
public class TestReceiver extends BroadcastReceiver {
public static final String TEST_INTENT= "MyTestIntent";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "Test", Toast.LENGTH_SHORT);
if(intent.getAction()==TEST_INTENT)
{
System.out.println("GOT THE INTENT");
Toast.makeText(context, "Test", Toast.LENGTH_SHORT);
}
}
}
清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.intenttest"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:name=".TestReceiver" android:label="@string/app_name">
<intent-filter>
<action android:name="MyTestIntent">
</action>
</intent-filter>
</receiver>
<receiver android:label="@string/app_name" android:name="Widget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget" />
</receiver>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
【问题讨论】:
-
首先是愚蠢的问题 - 如果您只是创建一个常规 Intent() 并在应用程序的某处调用 startActivity() 是否有效?只需确保接收器设置正确。
-
我添加了 context.sendBroadcast(intent);到小部件中的 onUpdate 函数。现在调试它,似乎它在该语句上调用接收器,现在当我单击按钮时。我想我很困惑,因为我打的 Toast 电话没有任何作用。
-
是的,因为你没有添加
.show():) -
噢,天哪。学习新事物的斗争。哦,好吧,至少它终于可以工作了。
-
不在 Toast 末尾添加 show() 是一个常见的错误。无论如何,很高兴它有效。嘿,我还不如添加一个答案来完成这个问题。
标签: android android-intent broadcastreceiver