AppWidgetProvider public void onEnabled(上下文上下文)不影响小部件 [英] AppWidgetProvider public void onEnabled (Context context) does not effect widget

查看:19
本文介绍了AppWidgetProvider public void onEnabled(上下文上下文)不影响小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AppWidgetProvider 并试图覆盖 onEnabled,我认为这是当应用从用户添加到主屏幕时调用的.我的 AppWidgetProvider 类看起来像这样并调用一个异步任务,该任务应该更新我的文本视图:

I am using an AppWidgetProvider and attempting to override the onEnabled which I assume is what is called when the app gets added to the home screen from the user. My AppWidgetProvider class looks like this and calls an async task which is supposed to update my text view:

package com.example.beerportfoliopro;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;

/**
 * Created by Mike on 12/26/13.
 */
public class HelloWidget extends AppWidgetProvider {

    @Override
    public void onEnabled(Context context){

        //build url for async task
        String url = "hiddenURL";

        //call async task
        new GetRandomBeer(context).execute(url);



    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){

        //todo: call update code, which should be the same as onEnabled


    }


}

显示小部件外观的小部件 xml 文件是:

My widget xml file that displays what the widget looks like is:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@drawable/widget_bg_normal"
    >


    <TextView
        android:id="@+id/widget_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="testing 123"
        android:layout_gravity="center_horizontal|center"
        android:layout_marginTop="5dip"
        android:padding="10dip"
        android:textColor="@android:color/black"
        >
    </TextView>

</LinearLayout>

我的异步任务最终会解析一些 JSON 以添加到我的小部件中,如下所示:

And my async task which will eventually parse some JSON to add to my widget looks like this:

public class GetRandomBeer extends AsyncTask
        <String, Void, String> {

    Context c;

    public GetRandomBeer(Context context)
    {
        c = context;

    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }



    protected void onPostExecute(String result){
        Log.d("taste","Inside get taste");
        //decode json here
        try{

            //todo: get all beer data



            //todo: set text views with data
            TextView breweryTitle = (TextView) ((Activity) c).findViewById(R.id.widget_tv);
            breweryTitle.setText("changed in the async task!");




        }
        catch(Exception e){

        }


    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

}

根据我上面的代码,当用户将小部件添加到他们的主屏幕时,它应该运行 onEnabled(),它应该调用我的异步任务并将文本视图从测试 123"更改为更改异步任务!"

Based on my code above, when the user adds the widget to their homes screen it should run onEnabled() which should call my async task and change the textview from saying "testing 123" to "change in the async task!"

现在没有任何变化,我不知道为什么.

Right now nothing is changing and I can not figure out why.

更新:

这是我的清单中与小部件相关的代码:

Here is code I have in my manifest related to my widget:

   <receiver android:name="com.example.beerportfoliopro.HelloWidget" android:label="@string/app_name">
        <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            <action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
        </intent-filter>

我也知道我的异步任务正在被调用,因为我只是将一些 Log.d 放入其中,它正在运行异步任务,只是没有在小部件中设置 textview 值.

I also know my async task is getting called because I just put some Log.d into it and it is running the async task its just not setting the textview value in the widget.

更新 2

我还尝试将远程视图与下面的建议答案一起使用,现在我的异步任务中有这个:

I have also tried to use remote view with the suggested answer below and now I have this in my async task:

 @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub

        String beerText =  "try number 3";

        AppWidgetManager mgr = AppWidgetManager.getInstance(c);
        int[] appWidgetIds = mgr.getAppWidgetIds(new ComponentName(c, HelloWidget.class));

        //You need a static method somewhere (I usually put in widget provider class)
        //that builds the RemoteView and sets everything up.
        RemoteViews rv = HelloWidget.buildRemoteViews(c, mgr, appWidgetIds);

        rv.setTextViewText(R.id.widget_tv, beerText);

        mgr.updateAppWidget(appWidgetIds, rv);


        return readJSONFeed(arg0[0]);
    }

但是我得到了一个无法解决的方法错误

But I get a cannot resolve method error

 RemoteViews rv = HelloWidget.buildRemoteViews(c, mgr, appWidgetIds);

buildRemoteViews

推荐答案

在清单中注册广播:

<receiver android:name="MyWidget" android:label="Widget">
<intent-filter>
    <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    <action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
</intent-filter>
....
</receiver>

还要注意关于 onEnabled() 的这一点:

Also note this about onEnabled():

这是在第一次创建 App Widget 实例时调用的.例如,如果用户添加了您的 App Widget 的两个实例,则只会在第一次调用."

"This is called when an instance the App Widget is created for the first time. For example, if the user adds two instances of your App Widget, this is only called the first time."

您还有一个事实,即在添加实例时无论如何都会调用 onUpdate(),因此在 onEnabled() 中执行相同的操作可能是多余的.

You also have the fact that onUpdate() will be called anyway when an instance is added, so doing the same thing in onEnabled() may be redundant.

此外,一旦你执行了 AsyncTask,你就会遇到很多问题,首先是 Context 对象不是一个 Activity.

Also, once you get that AsyncTask to execute, you're going to have a host of problems, first of which is the Context object is not an Activity.

既然您的方法正在被调用,您将需要使用 RemoteViews 设置文本.您不需要在 onPostExecute() 中执行此操作,因为这是跨进程更新.

Now that your method is being called, you will need to set the text using RemoteViews. You don't need to do it in onPostExecute() since this is cross-process update.

protected Void doInBackground(String... arg0) {

    String beerText =  readJSONFeed(arg0[0]);

    AppWidgetManager mgr = AppWidgetManager.getInstance(c);
    int[] appWidgetIds = mgr.getAppWidgetIds(new ComponentName(c, HelloWidget.class));

    //You need a static method somewhere (I usually put in widget provider class) 
    //that builds the RemoteView and sets everything up.
    RemoteViews rv = HelloWidget.buildRemoteViews(c, mgr, appWidgetIds);

    rv.setTextViewText(R.id.text_view_in_layout, beerText);

    mgr.updateAppWidget(appWidgetIds, rv);
}

这会更新你所有的AppWidget,如果你只想更新一个,你需要传入它的id.

That will update all your AppWidget's, if you only want one to update, you will need to pass in it's id.

这篇关于AppWidgetProvider public void onEnabled(上下文上下文)不影响小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆