我在onUpdate()方法中初始化了一些数组,然后使用一个意图和一个按钮,尝试调用onReceive()函数,该函数运行良好,但无法访问在onUpdate()方法中设置的数组。为什么会这样呢?这些数组是对象变量,并声明为公共变量。我是不是遗漏了什么?
package net.aerosoftware.widgettest;
import java.util.HashMap;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
public class WidgetTest extends AppWidgetProvider {
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
public HashMap<Integer, String> channelsImages;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
Log.e("UPDATE", "Start");
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
channelsImages = new HashMap<Integer, String>();
channelsImages.put(0, "one");
channelsImages.put(1, "two");
Intent active = new Intent(context, WidgetTest.class);
active.setAction(ACTION_WIDGET_RECEIVER);
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.buttonclick, actionPendingIntent);
super.onUpdate(context, appWidgetManager, appWidgetIds);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
Log.e("UPDATE", "End");
}
@Override
public void onReceive(Context context, Intent intent)
{
Log.e("RECEIVE", "Start 2");
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER))
{
try
{
Log.e("SIZE", "Size Of channel array: "+channelsImages.size());
}
catch(Exception e)
{
Log.e("ON_RECIEVE_ERROR", " "+e.getMessage());
}
}
super.onReceive(context, intent);
Log.e("RECEIVE", "End");
}
}发布于 2010-08-12 23:31:17
您将获得一个不同的AppWidgetProvider实例(因为它扩展了BroadcastReceiver)
接口名:"A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active."
您可以使用服务来避免这种情况。
发布于 2010-08-09 17:17:26
在AppWidgetProvider应用编程接口中:
onReady():“在对上述每个回调方法进行之前,每次广播和都会调用此方法。您通常不需要实现此方法,因为默认的AppWidgetProvider实现会过滤所有App Widget广播并适当地调用上述方法。”
这意味着onReceive()在onUpdate()之前被调用,这就是为什么您会得到null
http://developer.android.com/reference/android/appwidget/AppWidgetProvider.html
https://stackoverflow.com/questions/3438565
复制相似问题