AppWidgetProvider公共无效onEnabled(上下文的背景下)不影响部件 [英] AppWidgetProvider public void onEnabled (Context context) does not effect widget

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

问题描述

我使用的是AppWidgetProvider,并试图重写我假设是,当应用程序被添加到该用户的主屏幕上所谓的onEnabled。我AppWidgetProvider类看起来是这样的,并呼吁一个异步任务,这是为了更新我的文本视图:

 包com.example.beerportfoliopro;

进口android.appwidget.AppWidgetManager;
进口android.appwidget.AppWidgetProvider;
进口android.content.Context;

/ **
 *在13年12月26日创建者迈克。
 * /
公共类HelloWidget的扩展AppWidgetProvider {

    @覆盖
    公共无效onEnabled(上下文的背景下){

        //建立网址异步任务
        字符串URL =hiddenURL;

        //调用异步任务
        新GetRandomBeer(上下文).execute(URL);



    }

    @覆盖
    公共无效的OnUpdate(上下文的背景下,AppWidgetManager appWidgetManager,INT [] appWidgetIds){

        // TODO:调用update code,这应该是一样的onEnabled


    }


}
 

:显示什么插件貌似是

我的窗口小部件的XML文件

 < XML版本=1.0编码=UTF-8&GT?;

< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:方向=垂直
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =WRAP_CONTENT
    机器人:layout_gravity =中心
    机器人:背景=@可绘制/ widget_bg_normal
    >


    <的TextView
        机器人:ID =@ + ID / widget_tv
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=试123
        机器人:layout_gravity =center_horizo​​ntal |中心
        机器人:layout_marginTop =5dip
        机器人:填充=10dip
        机器人:文字颜色=@机器人:彩色/黑白
        >
    < / TextView的>

< / LinearLayout中>
 

和我的异步任务,最终将解析某些JSON添加到我的小部件是这样的:

 公共类GetRandomBeer扩展的AsyncTask
        <字符串,太虚,字符串> {

    语境℃;

    公共GetRandomBeer(上下文的背景下)
    {
        C =背景;

    }

    @覆盖
    保护字符串doInBackground(字符串...为arg0){
        // TODO自动生成方法存根
        返回readJSONFeed(为arg0 [0]);
    }



    保护无效onPostExecute(字符串结果){
        Log.d(味,内部得到的味道);
        //德code在这里JSON
        尝试{

            // TODO:让所有的啤酒数据



            // TODO:与数据集文本视图
            TextView的breweryTitle =(TextView中)((活动)C).findViewById(R.id.widget_tv);
            breweryTitle.setText(在异步任务变了!);




        }
        赶上(例外五){

        }


    }

    公共字符串readJSONFeed(字符串URL){
        StringBuilder的StringBuilder的=新的StringBuilder();
        HttpClient的HttpClient的=新DefaultHttpClient();
        HTTPGET HTTPGET =新HTTPGET(URL);
        尝试 {
            HTT presponse响应= httpClient.execute(HTTPGET);
            状态行状态行= response.getStatusLine();
            INT状态code = statusLine.getStatus code();
            如果(状态code == 200){
                HttpEntity实体= response.getEntity();
                InputStream中的InputStream = entity.getContent();
                的BufferedReader读卡器=新的BufferedReader(
                        新的InputStreamReader(InputStream中));
                串线;
                而((行= reader.readLine())!= NULL){
                    stringBuilder.append(线);
                }
                inputStream.close();
            } 其他 {
                Log.d(JSON,无法下载文件);
            }
        }赶上(例外五){
            Log.d(readJSONFeed,e.getLocalizedMessage());
        }
        返回stringBuilder.toString();
    }

}
 

根据我的code以上,当用户添加的窗口小部件家园筛选它应该运行onEnabled(),它应该叫我的异步任务,并从说改变的TextView

测试123在异步变任务!

现在没有什么变化,我想不出为什么。

更新:

下面是code我在我的清单中涉及到我的小工具:

 <接收器的Andr​​oid版本:NAME =com.example.beerportfoliopro.HelloWidget机器人:标签=@字符串/ APP_NAME>
        <意向滤光器> <作用机器人:名称=android.appwidget.action.APPWIDGET_UPDATE/>
            <作用机器人:名称=android.appwidget.action.APPWIDGET_ENABLED/>
        &所述; /意图滤光器>
 

我也知道我的异步任务获取调用,因为我只是把一些Log.d到它,它正在运行的异步任务,它只是不设置在插件的TextView的价值。

更新2

我也尝试使用远程视图与下面的建议的答复,现在我有这个在我的异步任务:

  @覆盖
    保护字符串doInBackground(字符串...为arg0){
        // TODO自动生成方法存根

        字符串beerText =尝试号码3;

        AppWidgetManager经理= AppWidgetManager.getInstance(C);
        INT [] appWidgetIds = mgr.getAppWidgetIds(新的组件名(C,HelloWidget.class));

        //你需要一个静态方法的地方(我通常把在小部件提供商类)
        //即构建远程视窗,并设置一切。
        RemoteViews RV = HelloWidget.buildRemoteViews(C,经理,appWidgetIds);

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

        mgr.updateAppWidget(appWidgetIds,RV);


        返回readJSONFeed(为arg0 [0]);
    }
 

但我得到一个无法解决方法误差

  RemoteViews RV = HelloWidget.buildRemoteViews(C,经理,appWidgetIds);
 

buildRemoteViews

解决方案

注册在清单中的广播:

 <接收器的Andr​​oid版本:NAME =进myWidget机器人:标签=小工具>
<意向滤光器>
    <作用机器人:名称=android.appwidget.action.APPWIDGET_UPDATE/>
    <作用机器人:名称=android.appwidget.action.APPWIDGET_ENABLED/>
&所述; /意图滤光器>
....
< /接收器>
 

另外请注意这一下onEnabled():

时的一个实例在App控件被首次创建这就是所谓的。例如,如果用户添加的应用程序的widget的两个实例,这只是称为第一次。

您也有事实的OnUpdate()总要被调用时,一个实例添加,这样做同样的事情在onEnabled()可能是多余的。

此外,一旦你得到的AsyncTask来执行,你将有一系列的问题,其中第一个是上下文对象没有一个活动。

编辑:现在你的方法被调用时,你需要设置使用RemoteViews文本。你并不需要做的是在onPostExecute(),因为这是跨进程更新。

 保护无效doInBackground(字符串...为arg0){

    串beerText = readJSONFeed(为arg0 [0]);

    AppWidgetManager经理= AppWidgetManager.getInstance(C);
    INT [] appWidgetIds = mgr.getAppWidgetIds(新的组件名(C,HelloWidget.class));

    //你需要一个静态方法的地方(我通常把在小部件提供商类)
    //即构建远程视窗,并设置一切。
    RemoteViews RV = HelloWidget.buildRemoteViews(C,经理,appWidgetIds);

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

    mgr.updateAppWidget(appWidgetIds,RV);
}
 

这将更新所有AppWidget的,如果你只想要一个更新,则需要通过它的ID。

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


    }


}

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>

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

}

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.

Update:

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>

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.

Update 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);

under buildRemoteViews

解决方案

Register for the broadcast in your manifest:

<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>

Also note this about onEnabled():

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

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.

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.

EDIT: 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);
}

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

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

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