小部件onUpdate,onReceive

时间:2010-08-09 08:55:53

标签: android android-widget

我在onUpdate()方法中初始化一些数组,之后,使用intent和一个按钮,我尝试调用onReceive()函数,该函数运行正常,但无法访问onUpdate()方法中设置的数组。这是为什么?那些数组是对象变量并被声明为public。 我错过了什么吗?

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");
    }

}

2 个答案:

答案 0 :(得分:4)

你正在获得一个不同的AppWidgetProvider实例(因为它扩展了BroadcastReceiver)

API:"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."

您可以使用服务以避免这种情况。

答案 1 :(得分:0)

来自AppWidgetProvider API:

onReady(): “每个广播都会调用此方法,之前上述每个回调方法。通常不需要实现此方法,因为默认的AppWidgetProvider实现过滤所有App Widget广播并调用上述方法。“

这意味着在onUpdate()之前调用onReceive(),这就是你得到null的原因

http://developer.android.com/reference/android/appwidget/AppWidgetProvider.html