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

发布于 2024-12-25 10:51:42 字数 9063 浏览 0 评论 0原文

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

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



}   

}

现在我在这里有我的提供程序类,当我单击按钮时,我想在其中进行小部件更新(例如更改文本视图)。 public class MyWeatherAppWidgetProvider extends 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);
    }


}

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

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>

This is my Configure activity when I try to deploy the widget initially.

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



}   

}

Now I have my provider class here, where I want to do widget update (chhnge the textview for eg)when I click on the button.
public class MyWeatherAppWidgetProvider extends 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);
    }


}

Further I use service class to get this update done. Here for the startup I just want to change one of the textview label, just to see how it works

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

}

But I somehow cant get this done. When I use context.startService(intent) in the provider class the service class gets called. But again this textview on widget doesnt change. I have not seen a tutorial that explains both the configure(at startup) and update the widget later on user click. So I am not sure about my approach. I have my manifest file as

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

给我一枪 2025-01-01 10:51:42

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

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

It must be a problem with this line in your widget provider

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

Most likely a problem with "context.getApplicationContext()"
Try using a few different values, such as "Context", "context", "getBaseContext()", or "this". I'm not exactly sure which is correct, in a similar situation in my app I use "context", which works for me.

Also try changing

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

to:

 Intent intent = new Intent(context, UpdateWeatherAppWidgetService.class);
梦里人 2025-01-01 10:51:42

嘿,我在韦克舍参加你们的 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

Hey i am in your android course here in Vaxjo:D
For your question: I solved that in the AppWidgetProvider and then "transfered it to a service" with some minor changes.

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

And in your 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);
             }

     }

And permission for service and permission to receive broadcast in Manifest.
Please don't judge my hardwired values that i update the boxes , i am still trying to find out how to fetch the data properly :D

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文