单击按钮后如何通过服务执行小部件更新?

Posted

技术标签:

【中文标题】单击按钮后如何通过服务执行小部件更新?【英文标题】:how to perform widget update by service after clicking a button? 【发布时间】:2012-02-05 10:04:43 【问题描述】:

这是我最初尝试部署小部件时的配置活动。

public class WeatherAppWidgetConfigure extends PreferenceActivity
private List<WeatherForecast> weatherData = new ArrayList<WeatherForecast>();
private String city_url;
private String city_key;
OnSharedPreferenceChangeListener listener;
int mAppWidgetId;
WeatherForecast wfObj;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    // Set the result to CANCELED.  This will cause the widget host to cancel
    // out of the widget placement if they press the back button.
    setResult(RESULT_CANCELED);

    addPreferencesFromResource(R.xml.prefs);

    // Find the widget id from the intent.
    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null) 
        //Here I do some PreferenceActivity
                      mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
        System.out.println(mAppWidgetId);
        SharedPreferences prefs = PreferenceManager.
                                        getDefaultSharedPreferences(getBaseContext());

        listener = new SharedPreferences.OnSharedPreferenceChangeListener()  
               public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                        String key) 
                   SharedPreferences prefs = PreferenceManager.
                                                getDefaultSharedPreferences(getBaseContext());


                   city_url = prefs.getString("cities", 
                           "http://www.yr.no/place/Nepal/Bagmati/Kathmandu/forecast.xml");
                   //System.out.println(city_url);
                   if (city_url.contains("Kathmandu")) city_key = "Kathmandu";
                   else if( city_url.contains("Växjö")) city_key = "Växjö";
                   else city_key = "Los Angeles";

                   try 

                       URL url = new URL(city_url);
                       WeatherReport report = WeatherHandler.getWeatherReport(url);

                       int count = 0;
                       for (WeatherForecast forecast : report) 
                            count++;
                            //System.out.println("Forecast "+count);
                            //System.out.println( forecast.toString() );
                            weatherData.add(forecast);
                       

                       wfObj =  weatherData.get(0);
                   
                   catch (IOException ioe ) 
                       ioe.printStackTrace();
                   

                   RemoteViews views = new RemoteViews(getBaseContext().getPackageName(),
                           R.layout.widget_layout);

                   String temp = new Integer(wfObj.getTemp()).toString()+"C";
                   String date = wfObj.getStartYYMMDD();
                   String rain = new Double(wfObj.getRain()).toString()+"mm/h";
                   prefs.edit().putString("temp",temp).commit();
                   prefs.edit().putString("date",date).commit();
                   prefs.edit().putString("rain", rain).commit();

                   views.setTextViewText(R.id.city, city_key);
                   views.setTextViewText(R.id.temp, prefs.getString("temp", ""));
                   views.setTextViewText(R.id.date, prefs.getString("date", ""));
                   views.setTextViewText(R.id.rain, prefs.getString("rain", ""));
                        AppWidgetManager appWidgetManager = AppWidgetManager.
                                                            getInstance(getBaseContext());
                   appWidgetManager.updateAppWidget(mAppWidgetId, views);
                   //System.out.println(temp +" "+date+" "+ rain);  

                   // Make sure we pass back the original appWidgetId 
                   Intent resultValue = new Intent();
                   resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
                   setResult(RESULT_OK, resultValue);
                   finish();

                
            ;

        prefs.registerOnSharedPreferenceChangeListener(listener);
    
                // If they gave us an intent without the widget id, just bail.
    if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID)   
        finish(); 
    



   


现在我在这里有我的提供程序类,当我单击按钮时,我想在其中进行小部件更新(例如更改文本视图)。 公共类 MyWeatherAppWidgetProvider 扩展 AppWidgetProvider

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) 
    // TODO Auto-generated method stub



    final int N = appWidgetIds.length;
    Intent intent = new Intent(context.getApplicationContext(),
                                        UpdateWeatherAppWidgetService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        PendingIntent pendingIntent = PendingIntent.getService(context.getApplicationContext(), 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.widget_layout);

        remoteViews.setOnClickPendingIntent(R.id.button1, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    



我还使用服务类来完成此更新。这里对于启动我只想更改其中一个 textview 标签,只是为了看看它是如何工作的

public class UpdateWeatherAppWidgetService extends Service 

@Override
public int onStartCommand(Intent intent, int flags, int startId) 

    System.out.println("called");
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this
                                                            .getApplicationContext());
    Bundle extras = intent.getExtras();
    int[] appWidgetIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS);
    //other way
    //int[] appWidgetIds =intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);

    for(int widgetId : appWidgetIds)
        System.out.println(widgetId);
    



    if (appWidgetIds.length > 0) 
        for (int widgetId : appWidgetIds) 
            RemoteViews remoteViews = new RemoteViews(getPackageName(),
                    R.layout.widget_layout);
            remoteViews.setTextViewText(R.id.city, "BLAh");
            appWidgetManager.updateAppWidget(widgetId, remoteViews);
        
        stopSelf(startId);
    
    super.onStart(intent, startId);
    return START_STICKY;



@Override
public IBinder onBind(Intent arg0) 
    // TODO Auto-generated method stub
    return null;

但我不知何故无法完成这项工作。当我在提供程序类中使用 context.startService(intent) 时,服务类被调用。但是小部件上的这个文本视图再次没有改变。我还没有看到解释配置(在启动时)和稍后在用户单击时更新小部件的教程。所以我不确定我的方法。我的清单文件为

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="assignment3.demos"
  android:versionCode="1"
  android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />


<application android:icon="@drawable/icon" android:label="@string/app_name">
    <uses-library android:name="com.google.android.maps"/>
    <activity android:name=".MainListActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="TheCityMap"></activity>
    <activity android:name=".RoadMapActivity"></activity>
    <activity android:name=".TheRoadMap"></activity>
    <!-- <activity android:name="assignment3.demos.EditPrefs" android:label="Edit Preferences"/> -->
    <!-- <activity android:name=".VaxjoWeather" android:label="Vaxjo Weather"/> -->

    <activity android:name=".WeatherAppWidgetConfigure">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
        </intent-filter>
    </activity>

    <service android:enabled="true" android:name=".UpdateWeatherAppWidgetService"></service>
    <receiver android:name="MyWeatherAppWidgetProvider">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        </intent-filter>
        <meta-data android:name="android.appwidget.provider"
            android:resource="@xml/widgetproviderinfo" />
    </receiver>


</application>
<uses-permission android:name="android.permission.INTERNET" > </uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" > </uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" > </uses-permission>

【问题讨论】:

所以我说你可以启动服务,但服务不能正常工作,对吗? 当我在提供程序类中使用 context.startService(intent) 时,最初尝试部署小部件时会调用服务类。稍后当我单击按钮时它不起作用。 【参考方案1】:

一定是你的小部件提供程序中的这一行有问题

PendingIntent pendingIntent = PendingIntent.getService(context.getApplicationContext(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

很可能是“context.getApplicationContext()”的问题 尝试使用几个不同的值,例如“Context”、“context”、“getBaseContext()”或“this”。我不确定哪个是正确的,在我的应用程序的类似情况下,我使用“上下文”,这对我有用。

也尝试改变

Intent intent = new Intent(context.getApplicationContext(),
                                    UpdateWeatherAppWidgetService.class);

到:

 Intent intent = new Intent(context, UpdateWeatherAppWidgetService.class);

【讨论】:

我使用了 PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);但这一个也不好用 编辑了另一个建议,如果这不起作用我没有想法,对不起!【参考方案2】:

嘿,我在 Vaxjo 参加你的 android 课程:D 对于您的问题:我在 AppWidgetProvider 中解决了这个问题,然后通过一些小改动“将其转移到服务”。

private static final String WIDGET_BUTTON = "com.example.ass3.WIDGET_BUTTON";

@Override
  public int onStartCommand(Intent intent,int flag, int startId) 


    System.out.println("inService");
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this
            .getApplicationContext());

     RemoteViews views = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.main);
     ComponentName  watchWidget = new ComponentName(this.getApplicationContext(), WeatherWidget.class);

       views.setOnClickPendingIntent(R.id.widget_refresh, myIntent( WIDGET_BUTTON,this.getApplicationContext()));
       appWidgetManager.updateAppWidget(watchWidget, views);





        stopSelf(startId);

    return START_STICKY;

  

 protected PendingIntent myIntent(String button,Context context) 
        Intent intent = new Intent(context, WeatherWidget.class);
        intent.setAction(button);
        return PendingIntent.getBroadcast(context, 0, intent, 0);
    

在你的 Widget Provider 中

 @Override
     public void onReceive(Context context, Intent intent) 
            super.onReceive(context, intent);

            //Toast.makeText(context, "onReceiver()", Toast.LENGTH_LONG).show();
            //System.out.println("Intent get Action"+ intent.getAction());
         if (WIDGET_BUTTON.equals(intent.getAction())) 

             AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

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


                remoteViews.setTextViewText(R.id.widget_curtemp, "20");
                remoteViews.setTextViewText(R.id.widget_minmaxtemp, "10/30");  
                remoteViews.setImageViewResource(R.id.widget_image, R.drawable.sun);
                remoteViews.setTextViewText(R.id.widget_city, "vaxjo");
                remoteViews.setTextViewText(R.id.widget_desc,"trying to refreshs");
                appWidgetManager.updateAppWidget(widget, remoteViews);
             

     

以及 Manifest 中的服务权限和接收广播的权限。 请不要判断我更新盒子的硬连线值,我仍在尝试找出如何正确获取数据:D

【讨论】:

以上是关于单击按钮后如何通过服务执行小部件更新?的主要内容,如果未能解决你的问题,请参考以下文章

颤振:单击该小部件内的按钮后如何将小部件更改为另一个小部件

在小部件中单击按钮后服务未启动

通过服务更新 Android 小部件,即执行 http 请求

如何在 leaveEvent 上强制更新小部件的样式?

如何通过单击放置在同一页面上的小部件来显示不同的小部件

WorkManager 如何用于小部件更新?