在onRecive中调用AsyncTask

时间:2015-07-14 08:11:12

标签: android android-asynctask widget

AsyncTask以来我需要调用onReceive()函数。问题是当我调用该函数时,必须在TextViews中更改不同的onPostExecute(),不要更改它!

这是代码:

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    super.onReceive(context, intent);

    if (SYNC_CLICKED.equals(intent.getAction())) {

        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);


            RemoteViews remoteViews;
            ComponentName watchWidget;

            remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
            watchWidget = new ComponentName(context, widget.class);

            remoteViews.setTextViewText(R.id.textView56, "ACTUALIZANDO"); 
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
            new LongOperation(views, appWidgetId, appWidgetManager).execute("MyTestString"); //Calling the asyncTask

            appWidgetManager.updateAppWidget(watchWidget, remoteViews);

    }
}

protected PendingIntent getPendingSelfIntent(Context context, String action) {
        Intent intent = new Intent(context, getClass());
        intent.setAction(action);
        return PendingIntent.getBroadcast(context, 0, intent, 0);
    }

AsyncTask。我们使用的这部分代码也适用于我将onUpdate

称为sice的情况
public class LongOperation extends AsyncTask<String, Void, String> {
        private RemoteViews views;
        private int WidgetID;
        private AppWidgetManager WidgetManager;

        public LongOperation(RemoteViews views, int appWidgetID, AppWidgetManager appWidgetManager){
            this.views = views;
            this.WidgetID = appWidgetID;
            this.WidgetManager = appWidgetManager;

        }

        @Override
        public void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        public String doInBackground(String... params) {
            try {
                ....
            } catch (Exception e) {
                ....
            }

            return temperatura;
        }

        @Override
        public void onPostExecute(String result) {
            views.setTextViewText(R.id.textView66, result+ "ºC ");

            WidgetManager.updateAppWidget(WidgetID, views);
        }
    }

我认为问题出在appWidgetId,但我无法解决......

谢谢,

MARC

1 个答案:

答案 0 :(得分:0)

AsyncTask中使用BroadCast是不好的做法,因为如果没有任何有效的onReceive()Service,Android可能会在Activity中删除您的流程,并没有保证它的回归。

在这种情况下,official documentation建议IntentService

  

“BroadcastReceiver执行时间的具体约束   强调广播接收器的意图:小,离散   背景中的工作量,例如保存设置或   注册通知。就像在UI中调用的其他方法一样   线程,应用程序应避免可能长时间运行的操作   或广播接收机中的计算。但不是做   通过工作线程的密集型任务,您的应用程序应该启动   IntentService,如果需要采取可能长时间运行的操作   响应意图广播。“